diff --git a/accessible/tests/mochitest/common.js b/accessible/tests/mochitest/common.js index 0459020841e..47bf76cf358 100644 --- a/accessible/tests/mochitest/common.js +++ b/accessible/tests/mochitest/common.js @@ -83,6 +83,8 @@ const kDiscBulletText = String.fromCharCode(0x2022) + " "; const kCircleBulletText = String.fromCharCode(0x25e6) + " "; const kSquareBulletText = String.fromCharCode(0x25aa) + " "; +const MAX_TRIM_LENGTH = 100; + /** * nsIAccessibleRetrieval service. */ @@ -607,7 +609,7 @@ function prettyName(aIdentifier) try { msg += ", role: " + roleToString(acc.role); if (acc.name) - msg += ", name: '" + acc.name + "'"; + msg += ", name: '" + shortenString(acc.name) + "'"; } catch (e) { msg += "defunct"; } @@ -625,6 +627,21 @@ function prettyName(aIdentifier) return " '" + aIdentifier + "' "; } +/** + * Shorten a long string if it exceeds MAX_TRIM_LENGTH. + * @param aString the string to shorten. + * @returns the shortened string. + */ +function shortenString(aString, aMaxLength) +{ + if (aString.length <= MAX_TRIM_LENGTH) + return aString; + + // Trim the string if its length is > MAX_TRIM_LENGTH characters. + var trimOffset = MAX_TRIM_LENGTH / 2; + return aString.substring(0, trimOffset - 1) + "..." + + aString.substring(aString.length - trimOffset, aString.length); +} //////////////////////////////////////////////////////////////////////////////// // Private diff --git a/accessible/tests/mochitest/events/test_text_alg.html b/accessible/tests/mochitest/events/test_text_alg.html index 61d842ae187..ac77650f6dd 100644 --- a/accessible/tests/mochitest/events/test_text_alg.html +++ b/accessible/tests/mochitest/events/test_text_alg.html @@ -56,8 +56,9 @@ this.getID = function changeText_getID() { - return "change text '" + this.textData + "' -> " + this.textNode.data + - "for " + prettyName(this.containerNode); + return "change text '" + shortenString(this.textData) + "' -> '" + + shortenString(this.textNode.data) + "' for " + + prettyName(this.containerNode); } } diff --git a/b2g/chrome/content/shell.js b/b2g/chrome/content/shell.js index a383b8cebff..0ac8f7e4ac6 100644 --- a/b2g/chrome/content/shell.js +++ b/b2g/chrome/content/shell.js @@ -19,7 +19,6 @@ Cu.import('resource://gre/modules/DOMFMRadioParent.jsm'); Cu.import('resource://gre/modules/AlarmService.jsm'); Cu.import('resource://gre/modules/ActivitiesService.jsm'); Cu.import('resource://gre/modules/PermissionPromptHelper.jsm'); -Cu.import('resource://gre/modules/PermissionSettings.jsm'); Cu.import('resource://gre/modules/ObjectWrapper.jsm'); Cu.import('resource://gre/modules/accessibility/AccessFu.jsm'); Cu.import('resource://gre/modules/Payment.jsm'); diff --git a/b2g/components/UpdatePrompt.js b/b2g/components/UpdatePrompt.js index 0ee18292dcd..80f4facacb9 100644 --- a/b2g/components/UpdatePrompt.js +++ b/b2g/components/UpdatePrompt.js @@ -44,8 +44,53 @@ XPCOMUtils.defineLazyServiceGetter(Services, "settings", "@mozilla.org/settingsService;1", "nsISettingsService"); +function UpdateCheckListener(updatePrompt) { + this._updatePrompt = updatePrompt; +} + +UpdateCheckListener.prototype = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateCheckListener]), + + _updatePrompt: null, + + onCheckComplete: function UCL_onCheckComplete(request, updates, updateCount) { + if (Services.um.activeUpdate) { + return; + } + + if (updateCount == 0) { + this._updatePrompt.setUpdateStatus("no-updates"); + return; + } + + let update = Services.aus.selectUpdate(updates, updateCount); + if (!update) { + this._updatePrompt.setUpdateStatus("already-latest-version"); + return; + } + + this._updatePrompt.setUpdateStatus("check-complete"); + this._updatePrompt.showUpdateAvailable(update); + }, + + onError: function UCL_onError(request, update) { + if (update.errorCode == NETWORK_ERROR_OFFLINE) { + this._updatePrompt.setUpdateStatus("retry-when-online"); + } + + Services.aus.QueryInterface(Ci.nsIUpdateCheckListener); + Services.aus.onError(request, update); + }, + + onProgress: function UCL_onProgress(request, position, totalSize) { + Services.aus.QueryInterface(Ci.nsIUpdateCheckListener); + Services.aus.onProgress(request, position, totalSize); + } +}; + function UpdatePrompt() { this.wrappedJSObject = this; + this._updateCheckListener = new UpdateCheckListener(this); } UpdatePrompt.prototype = { @@ -60,6 +105,7 @@ UpdatePrompt.prototype = { _update: null, _applyPromptTimer: null, _waitingForIdle: false, + _updateCheckListner: null, // nsIUpdatePrompt @@ -107,42 +153,6 @@ UpdatePrompt.prototype = { showUpdateHistory: function UP_showUpdateHistory(aParent) { }, showUpdateInstalled: function UP_showUpdateInstalled() { }, - // nsIUpdateCheckListener - - onCheckComplete: function UP_onCheckComplete(request, updates, updateCount) { - if (Services.um.activeUpdate) { - return; - } - - if (updateCount == 0) { - this.setUpdateStatus("no-updates"); - return; - } - - let update = Services.aus.selectUpdate(updates, updateCount); - if (!update) { - this.setUpdateStatus("already-latest-version"); - return; - } - - this.setUpdateStatus("check-complete"); - this.showUpdateAvailable(update); - }, - - onError: function UP_onError(request, update) { - if (update.errorCode == NETWORK_ERROR_OFFLINE) { - this.setUpdateStatus("retry-when-online"); - } - - Services.aus.QueryInterface(Ci.nsIUpdateCheckListener); - Services.aus.onError(request, update); - }, - - onProgress: function UP_onProgress(request, position, totalSize) { - Services.aus.QueryInterface(Ci.nsIUpdateCheckListener); - Services.aus.onProgress(request, position, totalSize); - }, - // Custom functions waitForIdle: function UP_waitForIdle() { @@ -320,7 +330,7 @@ UpdatePrompt.prototype = { let checker = Cc["@mozilla.org/updates/update-checker;1"] .createInstance(Ci.nsIUpdateChecker); - checker.checkForUpdates(this, true); + checker.checkForUpdates(this._updateCheckListener, true); }, handleEvent: function UP_handleEvent(evt) { diff --git a/browser/base/content/browser-menubar.inc b/browser/base/content/browser-menubar.inc index caad61e89d1..3c5c2036912 100644 --- a/browser/base/content/browser-menubar.inc +++ b/browser/base/content/browser-menubar.inc @@ -482,9 +482,7 @@ accesskey="&toolsMenu.accesskey;"> - + class="show-only-for-keyboard"> + + #ifdef MOZ_SERVICES_SYNC diff --git a/browser/base/content/browser-social.js b/browser/base/content/browser-social.js index 901cb59d90c..fa28b169fe1 100644 --- a/browser/base/content/browser-social.js +++ b/browser/base/content/browser-social.js @@ -62,7 +62,7 @@ let SocialUI = { break; case "social:ambient-notification-changed": SocialToolbar.updateButton(); - SocialMenu.updateMenu(); + SocialMenu.populate(); break; case "social:profile-changed": SocialToolbar.updateProfile(); @@ -72,6 +72,8 @@ let SocialUI = { case "nsPref:changed": SocialSidebar.updateSidebar(); SocialToolbar.updateButton(); + SocialMenu.populate(); + break; } }, @@ -99,25 +101,14 @@ let SocialUI = { SocialToolbar.init(); SocialShareButton.init(); SocialSidebar.init(); + SocialMenu.populate(); }, updateToggleCommand: function SocialUI_updateToggleCommand() { let toggleCommand = this.toggleCommand; + // We only need to update the command itself - all our menu items use it. toggleCommand.setAttribute("checked", Services.prefs.getBoolPref("social.enabled")); - - // FIXME: bug 772808: menu items don't inherit the "hidden" state properly, - // need to update them manually. - // This should just be: toggleCommand.hidden = !Social.active; - for (let id of ["appmenu_socialToggle", "menu_socialToggle", "menu_socialAmbientMenu"]) { - let el = document.getElementById(id); - if (!el) - continue; - - if (Social.active) - el.removeAttribute("hidden"); - else - el.setAttribute("hidden", "true"); - } + toggleCommand.setAttribute("hidden", Social.active ? "false" : "true"); }, // This handles "ActivateSocialFeature" events fired against content documents @@ -610,24 +601,28 @@ var SocialMenu = { populate: function SocialMenu_populate() { // This menu is only accessible through keyboard navigation. let submenu = document.getElementById("menu_socialAmbientMenuPopup"); - while (submenu.hasChildNodes()) - submenu.removeChild(submenu.firstChild); + let ambientMenuItems = submenu.getElementsByClassName("ambient-menuitem"); + for (let ambientMenuItem of ambientMenuItems) + submenu.removeChild(ambientMenuItem); let provider = Social.provider; if (Social.active && provider) { let iconNames = Object.keys(provider.ambientNotificationIcons); + let separator = document.getElementById("socialAmbientMenuSeparator"); for (let name of iconNames) { let icon = provider.ambientNotificationIcons[name]; if (!icon.label || !icon.menuURL) continue; let menuitem = document.createElement("menuitem"); menuitem.setAttribute("label", icon.label); + menuitem.classList.add("ambient-menuitem"); menuitem.addEventListener("command", function() { openUILinkIn(icon.menuURL, "tab"); }, false); - submenu.appendChild(menuitem); + submenu.insertBefore(menuitem, separator); } + separator.hidden = !iconNames.length; } - document.getElementById("menu_socialAmbientMenu").hidden = !submenu.querySelector("menuitem"); + document.getElementById("menu_socialAmbientMenu").hidden = !Social.enabled; } }; @@ -692,11 +687,12 @@ var SocialToolbar = { const CACHE_PREF_NAME = "social.cached.notificationIcons"; // provider.profile == undefined means no response yet from the provider // to tell us whether the user is logged in or not. - if (!SocialUI.haveLoggedInUser() && provider.profile !== undefined) { - // The provider has responded with a profile and the user isn't logged - // in. The icons etc have already been removed by - // updateButtonHiddenState, so we want to nuke any cached icons we - // have and get out of here! + if (!Social.provider || !Social.provider.enabled || + (!SocialUI.haveLoggedInUser() && provider.profile !== undefined)) { + // Either no enabled provider, or there is a provider and it has + // responded with a profile and the user isn't loggedin. The icons + // etc have already been removed by updateButtonHiddenState, so we want + // to nuke any cached icons we have and get out of here! Services.prefs.clearUserPref(CACHE_PREF_NAME); return; } @@ -923,7 +919,7 @@ var SocialSidebar = { updateSidebar: function SocialSidebar_updateSidebar() { // Hide the toggle menu item if the sidebar cannot appear let command = document.getElementById("Social:ToggleSidebar"); - command.hidden = !this.canShow; + command.setAttribute("hidden", this.canShow ? "false" : "true"); // Hide the sidebar if it cannot appear, or has been toggled off. // Also set the command "checked" state accordingly. diff --git a/browser/base/content/test/browser_social_toolbar.js b/browser/base/content/test/browser_social_toolbar.js index fc80b295ae5..ca17707b673 100644 --- a/browser/base/content/test/browser_social_toolbar.js +++ b/browser/base/content/test/browser_social_toolbar.js @@ -46,7 +46,8 @@ var tests = { toolsPopup.removeEventListener("popupshown", ontoolspopupshownNoAmbient); let socialToggleMore = document.getElementById("menu_socialAmbientMenu"); ok(socialToggleMore, "Keyboard accessible social menu should exist"); - is(socialToggleMore.hidden, true, "Menu should be hidden when no ambient notifications."); + is(socialToggleMore.querySelectorAll("menuitem").length, 2, "The minimum number of menuitems is two when there are no ambient notifications."); + is(socialToggleMore.hidden, false, "Menu should be visible since we show some non-ambient notifications in the menu."); toolsPopup.hidePopup(); next(); }, false); @@ -85,6 +86,7 @@ var tests = { toolsPopup.removeEventListener("popupshown", ontoolspopupshownAmbient); let socialToggleMore = document.getElementById("menu_socialAmbientMenu"); ok(socialToggleMore, "Keyboard accessible social menu should exist"); + is(socialToggleMore.querySelectorAll("menuitem").length, 3, "The number of menuitems is minimum plus one ambient notification menuitem."); is(socialToggleMore.hidden, false, "Menu is visible when ambient notifications have label & menuURL"); let menuitem = socialToggleMore.querySelector("menuitem"); is(menuitem.getAttribute("label"), "Test Ambient 1", "Keyboard accessible ambient menuitem should have specified label"); @@ -109,11 +111,15 @@ var tests = { testShowSidebarMenuitemExists: function(next) { let toggleSidebarMenuitem = document.getElementById("social-toggle-sidebar-menuitem"); ok(toggleSidebarMenuitem, "Toggle Sidebar menuitem exists"); + let toggleSidebarKeyboardMenuitem = document.getElementById("social-toggle-sidebar-keyboardmenuitem"); + ok(toggleSidebarKeyboardMenuitem, "Toggle Sidebar keyboard menuitem exists"); next(); }, testShowDesktopNotificationsMenuitemExists: function(next) { let toggleDesktopNotificationsMenuitem = document.getElementById("social-toggle-notifications-menuitem"); ok(toggleDesktopNotificationsMenuitem, "Toggle notifications menuitem exists"); + let toggleDesktopNotificationsKeyboardMenuitem = document.getElementById("social-toggle-notifications-keyboardmenuitem"); + ok(toggleDesktopNotificationsKeyboardMenuitem, "Toggle notifications keyboard menuitem exists"); next(); } } diff --git a/browser/themes/browserShared.inc b/browser/themes/browserShared.inc index ee76c46fbfe..f10686db0f8 100644 --- a/browser/themes/browserShared.inc +++ b/browser/themes/browserShared.inc @@ -1,3 +1,3 @@ %filter substitution -%define primaryToolbarButtons #back-button, #forward-button, #reload-button, #stop-button, #home-button, #print-button, #downloads-button, #history-button, #bookmarks-button, #bookmarks-menu-button, #new-tab-button, #new-window-button, #cut-button, #copy-button, #paste-button, #fullscreen-button, #zoom-out-button, #zoom-in-button, #sync-button, #feed-button, #alltabs-button, #tabview-button +%define primaryToolbarButtons #back-button, #forward-button, #reload-button, #stop-button, #home-button, #print-button, #downloads-button, #downloads-indicator, #history-button, #bookmarks-button, #bookmarks-menu-button, #new-tab-button, #new-window-button, #cut-button, #copy-button, #paste-button, #fullscreen-button, #zoom-out-button, #zoom-in-button, #sync-button, #feed-button, #alltabs-button, #tabview-button diff --git a/browser/themes/gnomestripe/browser.css b/browser/themes/gnomestripe/browser.css index 6840c7e16fd..21600013885 100644 --- a/browser/themes/gnomestripe/browser.css +++ b/browser/themes/gnomestripe/browser.css @@ -2734,6 +2734,7 @@ html|*#gcli-output-frame { .chat-titlebar { background-color: #d9d9d9; + background-image: linear-gradient(@toolbarHighlight@, rgba(255,255,255,0)); height: 20px; min-height: 20px; width: 100%; @@ -2754,7 +2755,10 @@ html|*#gcli-output-frame { } .chat-titlebar[activity] { - background-color: #ceeaff; + background-image: radial-gradient(ellipse closest-side at center, rgb(255,255,255), rgba(255,255,255,0)); + background-repeat: no-repeat; + background-size: 100% 20px; + background-position: 0 -10px; } .chat-frame { @@ -2764,6 +2768,7 @@ html|*#gcli-output-frame { } .chatbar-button { + -moz-appearance: none; background-color: #d9d9d9; list-style-image: url("chrome://browser/skin/social/social.png"); border: none; @@ -2775,8 +2780,16 @@ html|*#gcli-output-frame { -moz-border-end: 1px solid #ccc; } -.chatbar-button[open="true"], -.chatbar-button:active:hover { +.chatbar-button > .toolbarbutton-icon { + opacity: .6; + -moz-margin-end: 0; +} +.chatbar-button:hover > .toolbarbutton-icon, +.chatbar-button[open="true"] > .toolbarbutton-icon { + opacity: 1; +} + +.chatbar-button[open="true"] { background-color: #f0f0f0; box-shadow: inset 0 2px 5px rgba(0,0,0,0.6), 0 1px rgba(255,255,255,0.2); } @@ -2787,7 +2800,7 @@ html|*#gcli-output-frame { } .chatbar-button[activity] { - background-color: #ceeaff; + background-image: radial-gradient(circle farthest-corner at center 3px, rgb(233,242,252) 3%, rgba(172,206,255,0.75) 40%, rgba(87,151,201,0.5) 80%, rgba(87,151,201,0)); } .chatbar-button > menupopup > menuitem[activity] { @@ -2811,6 +2824,8 @@ chatbox { background-color: white; border: 1px solid #ccc; border-bottom: none; + border-top-left-radius: 2.5px; + border-top-right-radius: 2.5px; } chatbox[minimized="true"] { diff --git a/browser/themes/gnomestripe/downloads/downloads.css b/browser/themes/gnomestripe/downloads/downloads.css index d54eae2ff61..c7d61a20ddc 100644 --- a/browser/themes/gnomestripe/downloads/downloads.css +++ b/browser/themes/gnomestripe/downloads/downloads.css @@ -61,7 +61,6 @@ richlistitem[type="download"]:last-child { #downloadsListBox:-moz-focusring > richlistitem[type="download"][selected] { outline: 1px -moz-dialogtext dotted; outline-offset: -1px; - -moz-outline-radius: 3px; } .downloadTypeIcon { diff --git a/browser/themes/pinstripe/browser.css b/browser/themes/pinstripe/browser.css index 52aa599f0c8..f9850645bec 100644 --- a/browser/themes/pinstripe/browser.css +++ b/browser/themes/pinstripe/browser.css @@ -4156,6 +4156,7 @@ html|*#gcli-output-frame { .chat-titlebar { background-color: #d9d9d9; + background-image: linear-gradient(rgba(255,255,255,.43), rgba(255,255,255,0)); height: 20px; min-height: 20px; width: 100%; @@ -4172,7 +4173,10 @@ html|*#gcli-output-frame { } .chat-titlebar[activity] { - background-color: #ceeaff; + background-image: radial-gradient(ellipse closest-side at center, rgb(255,255,255), rgba(255,255,255,0)); + background-repeat: no-repeat; + background-size: 100% 20px; + background-position: 0 -10px; } .chat-titlebar[selected] { @@ -4197,8 +4201,15 @@ html|*#gcli-output-frame { -moz-border-end: 1px solid #ccc; } -.chatbar-button[open="true"], -.chatbar-button:active:hover { +.chatbar-button > .toolbarbutton-icon { + opacity: .6; +} +.chatbar-button:hover > .toolbarbutton-icon, +.chatbar-button[open="true"] > .toolbarbutton-icon { + opacity: 1; +} + +.chatbar-button[open="true"] { background-color: #f0f0f0; box-shadow: inset 0 2px 5px rgba(0,0,0,0.6), 0 1px rgba(255,255,255,0.2); } @@ -4209,7 +4220,7 @@ html|*#gcli-output-frame { } .chatbar-button[activity] { - background-color: #ceeaff; + background-image: radial-gradient(circle farthest-corner at center 2px, rgb(254,254,255) 3%, rgba(210,235,255,0.9) 12%, rgba(148,205,253,0.6) 30%, rgba(148,205,253,0.2) 70%); } .chatbar-button > menupopup > menuitem[activity] { @@ -4218,7 +4229,7 @@ html|*#gcli-output-frame { .chatbar-innerbox { background: transparent; - margin: -285px -1px 0 -1px; + margin: -285px 0 0; overflow: hidden; } @@ -4233,6 +4244,8 @@ chatbox { background-color: white; border: 1px solid #ccc; border-bottom: none; + border-top-left-radius: @toolbarbuttonCornerRadius@; + border-top-right-radius: @toolbarbuttonCornerRadius@; } chatbox[minimized="true"] { diff --git a/browser/themes/pinstripe/downloads/downloads.css b/browser/themes/pinstripe/downloads/downloads.css index c526e5ad076..e506857def3 100644 --- a/browser/themes/pinstripe/downloads/downloads.css +++ b/browser/themes/pinstripe/downloads/downloads.css @@ -77,7 +77,6 @@ richlistitem[type="download"]:last-child { #downloadsListBox:-moz-focusring > richlistitem[type="download"][selected] { outline: 1px -moz-dialogtext dotted; outline-offset: -1px; - -moz-outline-radius: 3px; } .downloadTypeIcon { diff --git a/browser/themes/winstripe/browser.css b/browser/themes/winstripe/browser.css index ef9e82ecee0..ee72a4a3e1a 100644 --- a/browser/themes/winstripe/browser.css +++ b/browser/themes/winstripe/browser.css @@ -3438,6 +3438,7 @@ html|*#gcli-output-frame { .chat-titlebar { background-color: #c4cfde; + background-image: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,0)); height: 20px; min-height: 20px; width: 100%; @@ -3458,7 +3459,10 @@ html|*#gcli-output-frame { } .chat-titlebar[activity] { - background-color: #ceeaff; + background-image: radial-gradient(ellipse closest-side at center, rgb(255,255,255), rgba(255,255,255,0)); + background-repeat: no-repeat; + background-size: 100% 20px; + background-position: 0 -10px; } .chat-frame { @@ -3487,9 +3491,16 @@ html|*#gcli-output-frame { padding: 2px; } -.chatbar-button[open="true"], -.chatbar-button:hover, -.chatbar-button:active:hover { +.chatbar-button > .toolbarbutton-icon { + opacity: .6; + -moz-margin-end: 0; +} +.chatbar-button:hover > .toolbarbutton-icon, +.chatbar-button[open="true"] > .toolbarbutton-icon { + opacity: 1; +} + +.chatbar-button[open="true"] { background-color: #dae3f0; box-shadow: inset 0 2px 5px rgba(0,0,0,0.6), 0 1px rgba(255,255,255,0.2); } @@ -3499,8 +3510,8 @@ html|*#gcli-output-frame { display: none; } -.chatbar-button[activity] { - background-color: #ceeaff; +.chatbar-button[activity]:not([open="true"]) { + background-image: radial-gradient(circle farthest-corner at center 3px, rgb(255,255,255) 3%, rgba(186,221,251,0.75) 40%, rgba(127,179,255,0.5) 80%, rgba(127,179,255,0.25)); } .chatbar-button > menupopup > menuitem[activity] { @@ -3509,7 +3520,7 @@ html|*#gcli-output-frame { .chatbar-innerbox { background: transparent; - margin: -285px -1px 0 -1px; + margin: -285px 0 0; overflow: hidden; } @@ -3524,6 +3535,8 @@ chatbox { background-color: white; border: 1px solid #ccc; border-bottom: none; + border-top-left-radius: 2.5px; + border-top-right-radius: 2.5px; } chatbox[minimized="true"] { diff --git a/browser/themes/winstripe/downloads/downloads.css b/browser/themes/winstripe/downloads/downloads.css index 1bda5cb5d56..282500bdc2a 100644 --- a/browser/themes/winstripe/downloads/downloads.css +++ b/browser/themes/winstripe/downloads/downloads.css @@ -72,7 +72,6 @@ richlistitem[type="download"]:first-child { #downloadsListBox:-moz-focusring > richlistitem[type="download"][selected] { outline: 1px -moz-dialogtext dotted; outline-offset: -1px; - -moz-outline-radius: 3px; } .downloadTypeIcon { diff --git a/caps/idl/nsIPrincipal.idl b/caps/idl/nsIPrincipal.idl index 538b5be18a2..119c251179b 100644 --- a/caps/idl/nsIPrincipal.idl +++ b/caps/idl/nsIPrincipal.idl @@ -21,7 +21,7 @@ interface nsIContentSecurityPolicy; [ptr] native JSPrincipals(JSPrincipals); [ptr] native PrincipalArray(nsTArray >); -[scriptable, uuid(96a92f0c-adcb-44ac-a034-37627647ec97)] +[scriptable, uuid(3a283dc9-f733-4618-a36f-e2b68c280ab7)] interface nsIPrincipal : nsISerializable { /** @@ -195,6 +195,12 @@ interface nsIPrincipal : nsISerializable * appId everywhere where we construct principals. */ readonly attribute boolean unknownAppId; + + /** + * Returns true iff this principal is a null principal (corresponding to an + * unknown, hence assumed minimally privileged, security context). + */ + readonly attribute boolean isNullPrincipal; }; /** @@ -217,4 +223,4 @@ interface nsIExpandedPrincipal : nsISupports * should not be changed and should only be used ephemerally. */ [noscript] readonly attribute PrincipalArray whiteList; -}; +}; \ No newline at end of file diff --git a/caps/include/nsPrincipal.h b/caps/include/nsPrincipal.h index 46023cdd8a1..600d8df0f8c 100644 --- a/caps/include/nsPrincipal.h +++ b/caps/include/nsPrincipal.h @@ -71,6 +71,7 @@ public: NS_IMETHOD GetAppId(uint32_t* aAppStatus); NS_IMETHOD GetIsInBrowserElement(bool* aIsInBrowserElement); NS_IMETHOD GetUnknownAppId(bool* aUnknownAppId); + NS_IMETHOD GetIsNullPrincipal(bool* aIsNullPrincipal); #ifdef DEBUG virtual void dumpImpl(); #endif @@ -152,6 +153,7 @@ public: NS_IMETHOD GetAppId(uint32_t* aAppStatus); NS_IMETHOD GetIsInBrowserElement(bool* aIsInBrowserElement); NS_IMETHOD GetUnknownAppId(bool* aUnknownAppId); + NS_IMETHOD GetIsNullPrincipal(bool* aIsNullPrincipal); #ifdef DEBUG virtual void dumpImpl(); #endif diff --git a/caps/src/nsNullPrincipal.cpp b/caps/src/nsNullPrincipal.cpp index 1064e92718e..c1996efeff9 100644 --- a/caps/src/nsNullPrincipal.cpp +++ b/caps/src/nsNullPrincipal.cpp @@ -291,6 +291,13 @@ nsNullPrincipal::GetUnknownAppId(bool* aUnknownAppId) return NS_OK; } +NS_IMETHODIMP +nsNullPrincipal::GetIsNullPrincipal(bool* aIsNullPrincipal) +{ + *aIsNullPrincipal = true; + return NS_OK; +} + /** * nsISerializable implementation */ diff --git a/caps/src/nsPrincipal.cpp b/caps/src/nsPrincipal.cpp index b6df185609b..1ab68fa7f79 100644 --- a/caps/src/nsPrincipal.cpp +++ b/caps/src/nsPrincipal.cpp @@ -541,6 +541,13 @@ nsPrincipal::GetUnknownAppId(bool* aUnknownAppId) return NS_OK; } +NS_IMETHODIMP +nsPrincipal::GetIsNullPrincipal(bool* aIsNullPrincipal) +{ + *aIsNullPrincipal = false; + return NS_OK; +} + NS_IMETHODIMP nsPrincipal::Read(nsIObjectInputStream* aStream) { @@ -852,6 +859,13 @@ nsExpandedPrincipal::GetUnknownAppId(bool* aUnknownAppId) return NS_OK; } +NS_IMETHODIMP +nsExpandedPrincipal::GetIsNullPrincipal(bool* aIsNullPrincipal) +{ + *aIsNullPrincipal = false; + return NS_OK; +} + void nsExpandedPrincipal::GetScriptLocation(nsACString& aStr) { diff --git a/caps/src/nsScriptSecurityManager.cpp b/caps/src/nsScriptSecurityManager.cpp index e265351b45a..c359413d739 100644 --- a/caps/src/nsScriptSecurityManager.cpp +++ b/caps/src/nsScriptSecurityManager.cpp @@ -2992,11 +2992,13 @@ GetExtendedOrigin(nsIURI* aURI, uint32_t aAppId, bool aInMozBrowser, return; } - // aExtendedOrigin = appId + "+" + origin + "+" + { 't', 'f' } + // aExtendedOrigin = appId + "+" + { 't', 'f' } "+" + origin; aExtendedOrigin.Truncate(); aExtendedOrigin.AppendInt(aAppId); - aExtendedOrigin.Append(NS_LITERAL_CSTRING("+") + origin + NS_LITERAL_CSTRING("+")); + aExtendedOrigin.Append('+'); aExtendedOrigin.Append(aInMozBrowser ? 't' : 'f'); + aExtendedOrigin.Append('+'); + aExtendedOrigin.Append(origin); return; } diff --git a/caps/src/nsSystemPrincipal.cpp b/caps/src/nsSystemPrincipal.cpp index ab095e4c6b8..ddc310c908a 100644 --- a/caps/src/nsSystemPrincipal.cpp +++ b/caps/src/nsSystemPrincipal.cpp @@ -198,6 +198,13 @@ nsSystemPrincipal::GetUnknownAppId(bool* aUnknownAppId) return NS_OK; } +NS_IMETHODIMP +nsSystemPrincipal::GetIsNullPrincipal(bool* aIsNullPrincipal) +{ + *aIsNullPrincipal = false; + return NS_OK; +} + ////////////////////////////////////////// // Methods implementing nsISerializable // ////////////////////////////////////////// diff --git a/content/canvas/src/WebGLContext.cpp b/content/canvas/src/WebGLContext.cpp index c4e3b71f205..1ccb181aa7b 100644 --- a/content/canvas/src/WebGLContext.cpp +++ b/content/canvas/src/WebGLContext.cpp @@ -1202,15 +1202,15 @@ WebGLContext::DummyFramebufferOperation(const char *info) // are met. // At a bare minimum, from context lost to context restores, it would take 3 // full timer iterations: detection, webglcontextlost, webglcontextrestored. -NS_IMETHODIMP -WebGLContext::Notify(nsITimer* timer) +void +WebGLContext::RobustnessTimerCallback(nsITimer* timer) { TerminateContextLossTimer(); if (!mCanvasElement) { // the canvas is gone. That happens when the page was closed before we got // this timer event. In this case, there's nothing to do here, just don't crash. - return NS_OK; + return; } // If the context has been lost and we're waiting for it to be restored, do @@ -1243,7 +1243,7 @@ WebGLContext::Notify(nsITimer* timer) // Try to restore the context. If it fails, try again later. if (NS_FAILED(SetDimensions(mWidth, mHeight))) { SetupContextLossTimer(); - return NS_OK; + return; } mContextStatus = ContextStable; nsContentUtils::DispatchTrustedEvent(mCanvasElement->OwnerDoc(), @@ -1258,7 +1258,7 @@ WebGLContext::Notify(nsITimer* timer) } MaybeRestoreContext(); - return NS_OK; + return; } void @@ -1408,7 +1408,6 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WebGLContext) NS_INTERFACE_MAP_ENTRY(nsIDOMWebGLRenderingContext) NS_INTERFACE_MAP_ENTRY(nsICanvasRenderingContextInternal) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) - NS_INTERFACE_MAP_ENTRY(nsITimerCallback) // If the exact way we cast to nsISupports here ever changes, fix our // PreCreate hook! NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, diff --git a/content/canvas/src/WebGLContext.h b/content/canvas/src/WebGLContext.h index 1c4ae5d9f60..9f4aa9a3509 100644 --- a/content/canvas/src/WebGLContext.h +++ b/content/canvas/src/WebGLContext.h @@ -473,7 +473,6 @@ class WebGLContext : public nsIDOMWebGLRenderingContext, public nsICanvasRenderingContextInternal, public nsSupportsWeakReference, - public nsITimerCallback, public WebGLRectangleObject, public nsWrapperCache { @@ -510,8 +509,6 @@ public: NS_DECL_NSIDOMWEBGLRENDERINGCONTEXT - NS_DECL_NSITIMERCALLBACK - // nsICanvasRenderingContextInternal NS_IMETHOD SetDimensions(int32_t width, int32_t height); NS_IMETHOD InitializeWithSurface(nsIDocShell *docShell, gfxASurface *surface, int32_t width, int32_t height) @@ -607,6 +604,12 @@ public: return mMinCapability; } + void RobustnessTimerCallback(nsITimer* timer); + + static void RobustnessTimerCallbackStatic(nsITimer* timer, void *thisPointer) { + static_cast(thisPointer)->RobustnessTimerCallback(timer); + } + void SetupContextLossTimer() { // If the timer was already running, don't restart it here. Instead, // wait until the previous call is done, then fire it one more time. @@ -616,10 +619,11 @@ public: mDrawSinceContextLossTimerSet = true; return; } - - mContextRestorer->InitWithCallback(static_cast(this), - PR_MillisecondsToInterval(1000), - nsITimer::TYPE_ONE_SHOT); + + mContextRestorer->InitWithFuncCallback(RobustnessTimerCallbackStatic, + static_cast(this), + PR_MillisecondsToInterval(1000), + nsITimer::TYPE_ONE_SHOT); mContextLossTimerRunning = true; mDrawSinceContextLossTimerSet = false; } diff --git a/content/events/src/Makefile.in b/content/events/src/Makefile.in index 57552b42b14..64ac844eb64 100644 --- a/content/events/src/Makefile.in +++ b/content/events/src/Makefile.in @@ -64,12 +64,6 @@ CPPSRCS = \ TextComposition.cpp \ $(NULL) -ifdef MOZ_B2G_RIL -CPPSRCS += \ - nsDOMWifiEvent.cpp \ - $(NULL) -endif - # we don't want the shared lib, but we want to force the creation of a static lib. FORCE_STATIC_LIB = 1 diff --git a/content/events/src/nsDOMWifiEvent.cpp b/content/events/src/nsDOMWifiEvent.cpp deleted file mode 100644 index 00e63ae520a..00000000000 --- a/content/events/src/nsDOMWifiEvent.cpp +++ /dev/null @@ -1,179 +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 "nsDOMWifiEvent.h" -#include "nsContentUtils.h" -#include "DictionaryHelpers.h" -#include "nsDOMClassInfoID.h" - -// nsDOMMozWifiStatusChangeEvent - -DOMCI_DATA(MozWifiStatusChangeEvent, nsDOMMozWifiStatusChangeEvent) - -NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMMozWifiStatusChangeEvent) - -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMMozWifiStatusChangeEvent, nsDOMEvent) - NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mNetwork) -NS_IMPL_CYCLE_COLLECTION_UNLINK_END - -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMMozWifiStatusChangeEvent, nsDOMEvent) - NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNetwork) -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END - -NS_INTERFACE_MAP_BEGIN(nsDOMMozWifiStatusChangeEvent) - NS_INTERFACE_MAP_ENTRY(nsIDOMMozWifiStatusChangeEvent) - NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozWifiStatusChangeEvent) -NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent) - -NS_IMPL_ADDREF_INHERITED(nsDOMMozWifiStatusChangeEvent, nsDOMEvent) -NS_IMPL_RELEASE_INHERITED(nsDOMMozWifiStatusChangeEvent, nsDOMEvent) - -NS_IMETHODIMP -nsDOMMozWifiStatusChangeEvent::GetNetwork(nsIVariant** aNetwork) -{ - NS_IF_ADDREF(*aNetwork = mNetwork); - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiStatusChangeEvent::GetStatus(nsAString& aStatus) -{ - aStatus = mStatus; - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiStatusChangeEvent::InitMozWifiStatusChangeEvent(const nsAString& aType, - bool aCanBubble, - bool aCancelable, - nsIVariant* aNetwork, - const nsAString& aStatus) -{ - nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable); - NS_ENSURE_SUCCESS(rv, rv); - - mNetwork = aNetwork; - mStatus = aStatus; - - return NS_OK; -} - -nsresult -nsDOMMozWifiStatusChangeEvent::InitFromCtor(const nsAString& aType, - JSContext* aCx, jsval* aVal) -{ - mozilla::dom::MozWifiStatusChangeEventInit d; - nsresult rv = d.Init(aCx, aVal); - NS_ENSURE_SUCCESS(rv, rv); - return InitMozWifiStatusChangeEvent(aType, d.bubbles, d.cancelable, d.network, d.status); -} - -nsresult -NS_NewDOMMozWifiStatusChangeEvent(nsIDOMEvent** aInstancePtrResult, - nsPresContext* aPresContext, - nsEvent* aEvent) -{ - nsDOMMozWifiStatusChangeEvent* e = new nsDOMMozWifiStatusChangeEvent(aPresContext, aEvent); - return CallQueryInterface(e, aInstancePtrResult); -} - -// nsDOMMozWifiConnectionInfoEvent -DOMCI_DATA(MozWifiConnectionInfoEvent, nsDOMMozWifiConnectionInfoEvent) - -NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMMozWifiConnectionInfoEvent) - -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMMozWifiConnectionInfoEvent, nsDOMEvent) - NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mNetwork) -NS_IMPL_CYCLE_COLLECTION_UNLINK_END - -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMMozWifiConnectionInfoEvent, nsDOMEvent) - NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNetwork) -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END - -NS_INTERFACE_MAP_BEGIN(nsDOMMozWifiConnectionInfoEvent) - NS_INTERFACE_MAP_ENTRY(nsIDOMMozWifiConnectionInfoEvent) - NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozWifiConnectionInfoEvent) -NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent) - -NS_IMPL_ADDREF_INHERITED(nsDOMMozWifiConnectionInfoEvent, nsDOMEvent) -NS_IMPL_RELEASE_INHERITED(nsDOMMozWifiConnectionInfoEvent, nsDOMEvent) - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::GetNetwork(nsIVariant** aNetwork) -{ - NS_IF_ADDREF(*aNetwork = mNetwork); - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::GetSignalStrength(int16_t* aSignalStrength) -{ - *aSignalStrength = mSignalStrength; - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::GetRelSignalStrength(int16_t* aRelSignalStrength) -{ - *aRelSignalStrength = mRelSignalStrength; - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::GetLinkSpeed(int32_t* aLinkSpeed) -{ - *aLinkSpeed = mLinkSpeed; - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::GetIpAddress(nsAString& aIpAddress) -{ - aIpAddress = mIpAddress; - return NS_OK; -} - -NS_IMETHODIMP -nsDOMMozWifiConnectionInfoEvent::InitMozWifiConnectionInfoEvent(const nsAString& aType, - bool aCanBubble, - bool aCancelable, - nsIVariant *aNetwork, - int16_t aSignalStrength, - int16_t aRelSignalStrength, - int32_t aLinkSpeed, - const nsAString &aIpAddress) -{ - nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable); - NS_ENSURE_SUCCESS(rv, rv); - - mNetwork = aNetwork; - mSignalStrength = aSignalStrength; - mRelSignalStrength = aRelSignalStrength; - mLinkSpeed = aLinkSpeed; - mIpAddress = aIpAddress; - - return NS_OK; -} - -nsresult -nsDOMMozWifiConnectionInfoEvent::InitFromCtor(const nsAString& aType, - JSContext* aCx, jsval* aVal) -{ - mozilla::dom::MozWifiConnectionInfoEventInit d; - nsresult rv = d.Init(aCx, aVal); - NS_ENSURE_SUCCESS(rv, rv); - return InitMozWifiConnectionInfoEvent(aType, d.bubbles, d.cancelable, d.network, - d.signalStrength, d.relSignalStrength, d.linkSpeed, - d.ipAddress); -} - -nsresult -NS_NewDOMMozWifiConnectionInfoEvent(nsIDOMEvent** aInstancePtrResult, - nsPresContext* aPresContext, - nsEvent* aEvent) -{ - nsDOMMozWifiConnectionInfoEvent* e = new nsDOMMozWifiConnectionInfoEvent(aPresContext, aEvent); - return CallQueryInterface(e, aInstancePtrResult); -} diff --git a/content/events/src/nsDOMWifiEvent.h b/content/events/src/nsDOMWifiEvent.h deleted file mode 100644 index 948835b84c7..00000000000 --- a/content/events/src/nsDOMWifiEvent.h +++ /dev/null @@ -1,58 +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 nsDOMWifiEvent_h__ -#define nsDOMWifiEvent_h__ - -#include "nsIWifi.h" -#include "nsIWifiEventInits.h" -#include "nsDOMEvent.h" - -class nsDOMMozWifiStatusChangeEvent : public nsDOMEvent, - public nsIDOMMozWifiStatusChangeEvent -{ -public: - nsDOMMozWifiStatusChangeEvent(nsPresContext* aPresContext, nsEvent* aEvent) - : nsDOMEvent(aPresContext, aEvent) {} - - NS_DECL_ISUPPORTS_INHERITED - NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMMozWifiStatusChangeEvent, nsDOMEvent) - // Forward to base class - NS_FORWARD_TO_NSDOMEVENT - - NS_DECL_NSIDOMMOZWIFISTATUSCHANGEEVENT - - virtual nsresult InitFromCtor(const nsAString& aType, - JSContext* aCx, jsval* aVal); -private: - nsCOMPtr mNetwork; - nsString mStatus; -}; - -class nsDOMMozWifiConnectionInfoEvent : public nsDOMEvent, - public nsIDOMMozWifiConnectionInfoEvent -{ -public: - nsDOMMozWifiConnectionInfoEvent(nsPresContext* aPresContext, nsEvent* aEvent) - : nsDOMEvent(aPresContext, aEvent) {} - - NS_DECL_ISUPPORTS_INHERITED - NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMMozWifiConnectionInfoEvent, nsDOMEvent) - // Forward to base class - NS_FORWARD_TO_NSDOMEVENT - - NS_DECL_NSIDOMMOZWIFICONNECTIONINFOEVENT - - virtual nsresult InitFromCtor(const nsAString& aType, - JSContext* aCx, jsval* aVal); -private: - nsCOMPtr mNetwork; - int16_t mSignalStrength; - int16_t mRelSignalStrength; - int32_t mLinkSpeed; - nsString mIpAddress; -}; - -#endif // nsDOMWifiEvent_h__ diff --git a/content/svg/content/src/nsSVGSVGElement.cpp b/content/svg/content/src/nsSVGSVGElement.cpp index c19a5d559e5..2e904a7fe4d 100644 --- a/content/svg/content/src/nsSVGSVGElement.cpp +++ b/content/svg/content/src/nsSVGSVGElement.cpp @@ -167,7 +167,9 @@ nsSVGSVGElement::nsSVGSVGElement(already_AddRefed aNodeInfo, mCurrentScale(1.0f), mPreviousTranslate(0.0f, 0.0f), mPreviousScale(1.0f), - mStartAnimationOnBindToTree(!aFromParser), + mStartAnimationOnBindToTree(aFromParser == NOT_FROM_PARSER || + aFromParser == FROM_PARSER_FRAGMENT || + aFromParser == FROM_PARSER_XSLT), mImageNeedsTransformInvalidation(false), mIsPaintingSVGImageElement(false), mHasChildrenOnlyTransform(false), diff --git a/dom/alarm/AlarmHalService.cpp b/dom/alarm/AlarmHalService.cpp index 851c1a4f34f..e6cc50485f3 100644 --- a/dom/alarm/AlarmHalService.cpp +++ b/dom/alarm/AlarmHalService.cpp @@ -19,20 +19,20 @@ AlarmHalService::Init() if (!mAlarmEnabled) { return; } - RegisterSystemTimeChangeObserver(this); + RegisterSystemTimezoneChangeObserver(this); } /* virtual */ AlarmHalService::~AlarmHalService() { if (mAlarmEnabled) { UnregisterTheOneAlarmObserver(); - UnregisterSystemTimeChangeObserver(this); + UnregisterSystemTimezoneChangeObserver(this); } } /* static */ StaticRefPtr AlarmHalService::sSingleton; -/* static */ already_AddRefed +/* static */ already_AddRefed AlarmHalService::GetInstance() { if (!sSingleton) { @@ -41,7 +41,7 @@ AlarmHalService::GetInstance() ClearOnShutdown(&sSingleton); } - nsCOMPtr service(do_QueryInterface(sSingleton)); + nsRefPtr service = sSingleton.get(); return service.forget(); } @@ -76,7 +76,7 @@ AlarmHalService::SetTimezoneChangedCb(nsITimezoneChangedCb* aTimeZoneChangedCb) } void -AlarmHalService::Notify(const mozilla::void_t& aVoid) +AlarmHalService::Notify(const void_t& aVoid) { if (!mAlarmFiredCb) { return; @@ -85,26 +85,14 @@ AlarmHalService::Notify(const mozilla::void_t& aVoid) } void -AlarmHalService::Notify(const SystemTimeChange& aReason) +AlarmHalService::Notify( + const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) { - if (aReason != SYS_TIME_CHANGE_TZ || !mTimezoneChangedCb) { + if (!mTimezoneChangedCb) { return; } - mTimezoneChangedCb->OnTimezoneChanged(GetTimezoneOffset(false)); -} - -int32_t -AlarmHalService::GetTimezoneOffset(bool aIgnoreDST) -{ - PRExplodedTime prTime; - PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &prTime); - - int32_t offset = prTime.tm_params.tp_gmt_offset; - if (!aIgnoreDST) { - offset += prTime.tm_params.tp_dst_offset; - } - - return -(offset / 60); + mTimezoneChangedCb->OnTimezoneChanged( + aSystemTimezoneChangeInfo.newTimezoneOffsetMinutes()); } } // alarm diff --git a/dom/alarm/AlarmHalService.h b/dom/alarm/AlarmHalService.h index 5bdcb218445..4578a86fd12 100644 --- a/dom/alarm/AlarmHalService.h +++ b/dom/alarm/AlarmHalService.h @@ -13,17 +13,17 @@ #include "nsIAlarmHalService.h" #include "nsIObserver.h" #include "nsIObserverService.h" -#include "prtime.h" namespace mozilla { namespace dom { namespace alarm { - -using namespace hal; + +typedef Observer AlarmObserver; +typedef Observer SystemTimezoneChangeObserver; class AlarmHalService : public nsIAlarmHalService, public AlarmObserver, - public SystemTimeObserver + public SystemTimezoneChangeObserver { public: NS_DECL_ISUPPORTS @@ -32,13 +32,13 @@ public: void Init(); virtual ~AlarmHalService(); - static already_AddRefed GetInstance(); + static already_AddRefed GetInstance(); // Implementing hal::AlarmObserver - void Notify(const mozilla::void_t& aVoid); + void Notify(const void_t& aVoid); - // Implementing hal::SystemTimeObserver - void Notify(const SystemTimeChange& aReason); + // Implementing hal::SystemTimezoneChangeObserver + void Notify(const hal::SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo); private: bool mAlarmEnabled; @@ -46,8 +46,6 @@ private: nsCOMPtr mAlarmFiredCb; nsCOMPtr mTimezoneChangedCb; - - int32_t GetTimezoneOffset(bool aIgnoreDST); }; } // namespace alarm diff --git a/dom/apps/src/Makefile.in b/dom/apps/src/Makefile.in index e42f2a3e049..70c715eb6f4 100644 --- a/dom/apps/src/Makefile.in +++ b/dom/apps/src/Makefile.in @@ -26,6 +26,7 @@ EXTRA_PP_JS_MODULES += \ EXTRA_JS_MODULES += \ AppsServiceChild.jsm \ AppsUtils.jsm \ + OfflineCacheInstaller.jsm \ PermissionsInstaller.jsm \ $(NULL) diff --git a/dom/apps/src/OfflineCacheInstaller.jsm b/dom/apps/src/OfflineCacheInstaller.jsm new file mode 100644 index 00000000000..0d3b0c29467 --- /dev/null +++ b/dom/apps/src/OfflineCacheInstaller.jsm @@ -0,0 +1,174 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 Cu = Components.utils; +const Cc = Components.classes; +const Ci = Components.interfaces; +const CC = Components.Constructor; + +let EXPORTED_SYMBOLS = ["OfflineCacheInstaller"]; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/AppsUtils.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); + +let Namespace = CC('@mozilla.org/network/application-cache-namespace;1', + 'nsIApplicationCacheNamespace', + 'init'); +let makeFile = CC('@mozilla.org/file/local;1', + 'nsIFile', + 'initWithPath'); +const nsICache = Ci.nsICache; +const nsIApplicationCache = Ci.nsIApplicationCache; +const applicationCacheService = + Cc['@mozilla.org/network/application-cache-service;1'] + .getService(Ci.nsIApplicationCacheService); + + +function debug(aMsg) { + //dump("-*-*- OfflineCacheInstaller.jsm : " + aMsg + "\n"); +} + + +function enableOfflineCacheForApp(origin, appId) { + let originURI = Services.io.newURI(origin, null, null); + let principal = Services.scriptSecurityManager.getAppCodebasePrincipal( + originURI, appId, false); + Services.perms.addFromPrincipal(principal, 'offline-app', + Ci.nsIPermissionManager.ALLOW_ACTION); + // Prevent cache from being evicted: + Services.perms.addFromPrincipal(principal, 'pin-app', + Ci.nsIPermissionManager.ALLOW_ACTION); +} + + +function storeCache(applicationCache, url, file, itemType) { + let session = Services.cache.createSession(applicationCache.clientID, + nsICache.STORE_OFFLINE, true); + session.asyncOpenCacheEntry(url, nsICache.ACCESS_WRITE, { + onCacheEntryAvailable: function (cacheEntry, accessGranted, status) { + cacheEntry.setMetaDataElement('request-method', 'GET'); + cacheEntry.setMetaDataElement('response-head', 'HTTP/1.1 200 OK\r\n'); + + let outputStream = cacheEntry.openOutputStream(0); + + // Input-Output stream machinery in order to push nsIFile content into cache + let inputStream = Cc['@mozilla.org/network/file-input-stream;1'] + .createInstance(Ci.nsIFileInputStream); + inputStream.init(file, 1, -1, null); + let bufferedOutputStream = Cc['@mozilla.org/network/buffered-output-stream;1'] + .createInstance(Ci.nsIBufferedOutputStream); + bufferedOutputStream.init(outputStream, 1024); + bufferedOutputStream.writeFrom(inputStream, inputStream.available()); + bufferedOutputStream.flush(); + bufferedOutputStream.close(); + outputStream.close(); + inputStream.close(); + + cacheEntry.markValid(); + debug (file.path + ' -> ' + url + ' (' + itemType + ')'); + applicationCache.markEntry(url, itemType); + cacheEntry.close(); + } + }); +} + +function readFile(aFile, aCallback) { + let channel = NetUtil.newChannel(aFile); + channel.contentType = "pain/text"; + NetUtil.asyncFetch(channel, function(aStream, aResult) { + if (!Components.isSuccessCode(aResult)) { + Cu.reportError("OfflineCacheInstaller: Could not read file " + aFile.path); + if (aCallback) + aCallback(null); + return; + } + + // Obtain a converter to read from a UTF-8 encoded input stream. + let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); + converter.charset = "UTF-8"; + + let data = NetUtil.readInputStreamToString(aStream, + aStream.available()); + aCallback(converter.ConvertToUnicode(data)); + }); +} + +const OfflineCacheInstaller = { + installCache: function installCache(app) { + let cacheDir = makeFile(app.basePath) + cacheDir.append(app.appId); + cacheDir.append("cache"); + if (!cacheDir.exists()) + return; + + let cacheManifest = cacheDir.clone(); + cacheManifest.append("manifest.appcache"); + if (!cacheManifest.exists()) + return; + + enableOfflineCacheForApp(app.origin, app.localId); + + // Get the url for the manifest. + let appcacheURL = app.origin + "cache/manifest.appcache"; + + // The group ID contains application id and 'f' for not being hosted in + // a browser element, but a mozbrowser iframe. + // See netwerk/cache/nsDiskCacheDeviceSQL.cpp: AppendJARIdentifier + let groupID = appcacheURL + '#' + app.localId+ '+f'; + let applicationCache = applicationCacheService.createApplicationCache(groupID); + applicationCache.activate(); + + readFile(cacheManifest, function (content) { + let lines = content.split(/\r?\n/); + // Process each manifest line, read only CACHE entries + // (ignore NETWORK entries) and compute absolute URL for each entry + let urls = []; + for(let i = 0; i < lines.length; i++) { + let line = lines[i]; + // Ignore comments + if (/^#/.test(line) || !line.length) + continue; + if (line == 'CACHE MANIFEST') + continue; + if (line == 'CACHE:') + continue; + // Ignore network entries and everything that comes after + if (line == 'NETWORK:') + break; + + // Prepend webapp origin in case of absolute path + if (line[0] == '/') { + urls.push(app.origin + line.substring(1)); + // Just pass along the url, if we have one + } else if (line.substr(0, 4) == 'http') { + urls.push(line); + } else { + throw new Error('Invalid line in appcache manifest:\n' + line + + '\nFrom: ' + cacheManifest.path); + } + } + urls.forEach(function processCachedFile(url) { + // Get this nsIFile from cache folder for this URL + let path = url.replace(/https?:\/\//, ''); + let file = cacheDir.clone(); + let paths = path.split('/'); + paths.forEach(file.append); + + if (!file.exists()) { + let msg = 'File ' + file.path + ' exists in the manifest but does ' + + 'not points to a real file.'; + throw new Error(msg); + } + + let itemType = nsIApplicationCache.ITEM_EXPLICIT; + storeCache(applicationCache, url, file, itemType); + }); + }); + } +}; + diff --git a/dom/apps/src/PermissionsInstaller.jsm b/dom/apps/src/PermissionsInstaller.jsm index a89b553082e..b716f70aaaa 100644 --- a/dom/apps/src/PermissionsInstaller.jsm +++ b/dom/apps/src/PermissionsInstaller.jsm @@ -9,6 +9,7 @@ const Cu = Components.utils; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/AppsUtils.jsm"); +Cu.import("resource://gre/modules/PermissionSettings.jsm"); var EXPORTED_SYMBOLS = ["PermissionsInstaller"]; @@ -25,16 +26,6 @@ const READWRITE = "readwrite"; const PERM_TO_STRING = ["unknown", "allow", "deny", "prompt"]; -XPCOMUtils.defineLazyServiceGetter(this, - "PermSettings", - "@mozilla.org/permissionSettings;1", - "nsIDOMPermissionSettings"); - -XPCOMUtils.defineLazyServiceGetter(this, - "permissionManager", - "@mozilla.org/permissionmanager;1", - "nsIPermissionManager"); - function debug(aMsg) { //dump("-*-*- PermissionsInstaller.jsm : " + aMsg + "\n"); } @@ -344,7 +335,7 @@ let PermissionsInstaller = { let index = newPerms.indexOf(AllPossiblePermissions[idx]); if (index == -1) { // See if the permission was installed previously - let _perm = PermSettings.get(AllPossiblePermissions[idx], + let _perm = PermissionSettingsModule.getPermission(AllPossiblePermissions[idx], aApp.manifestURL, aApp.origin, false); @@ -415,13 +406,25 @@ let PermissionsInstaller = { **/ _setPermission: function setPermission(aPerm, aValue, aApp) { if (aPerm != "storage") { - PermSettings.set(aPerm, aValue, aApp.manifestURL, aApp.origin, false); + PermissionSettingsModule.addPermission({ + type: aPerm, + origin: aApp.origin, + manifestURL: aApp.manifestURL, + value: aValue, + browserFlag: false + }); return; } ["indexedDB-unlimited", "offline-app", "pin-app"].forEach( function(aName) { - PermSettings.set(aName, aValue, aApp.manifestURL, aApp.origin, false); + PermissionSettingsModule.addPermission({ + type: aName, + origin: aApp.origin, + manifestURL: aApp.manifestURL, + value: aValue, + browserFlag: false + }); } ); } diff --git a/dom/apps/src/Webapps.jsm b/dom/apps/src/Webapps.jsm index 32d13d34a67..5b373fdaae7 100644 --- a/dom/apps/src/Webapps.jsm +++ b/dom/apps/src/Webapps.jsm @@ -17,6 +17,7 @@ Cu.import("resource://gre/modules/FileUtils.jsm"); Cu.import('resource://gre/modules/ActivitiesService.jsm'); Cu.import("resource://gre/modules/AppsUtils.jsm"); Cu.import("resource://gre/modules/PermissionsInstaller.jsm"); +Cu.import("resource://gre/modules/OfflineCacheInstaller.jsm"); function debug(aMsg) { //dump("-*-*- Webapps.jsm : " + aMsg + "\n"); @@ -92,7 +93,7 @@ let DOMApplicationRegistry = { // aNext() is called after we load the current webapps list. loadCurrentRegistry: function loadCurrentRegistry(aNext) { let file = FileUtils.getFile(DIRECTORY_NAME, ["webapps", "webapps.json"], false); - if (file && file.exists) { + if (file && file.exists()) { this._loadJSONAsync(file, (function loadRegistry(aData) { if (aData) { this.webapps = aData; @@ -175,89 +176,99 @@ let DOMApplicationRegistry = { }).bind(this)); }, + updateOfflineCacheForApp: function updateOfflineCacheForApp(aId) { + let app = this.webapps[aId]; + OfflineCacheInstaller.installCache({ + basePath: app.basePath, + appId: aId, + origin: app.origin, + localId: app.localId + }); + }, + // Implements the core of bug 787439 - // 1. load the apps from the current registry. - // 2. if at first run, go through these steps: + // if at first run, go through these steps: // a. load the core apps registry. // b. uninstall any core app from the current registry but not in the // new core apps registry. // c. for all apps in the new core registry, install them if they are not // yet in the current registry, and run installPermissions() + installSystemApps: function installSystemApps(aNext) { + let file; + try { + file = FileUtils.getFile("coreAppsDir", ["webapps", "webapps.json"], false); + } catch(e) { } + + if (file && file.exists()) { + // a + this._loadJSONAsync(file, (function loadCoreRegistry(aData) { + if (!aData) { + aNext(); + return; + } + + // b : core apps are not removable. + for (let id in this.webapps) { + if (id in aData || this.webapps[id].removable) + continue; + delete this.webapps[id]; + // Remove the permissions, cookies and private data for this app. + let localId = this.webapps[id].localId; + let permMgr = Cc["@mozilla.org/permissionmanager;1"] + .getService(Ci.nsIPermissionManager); + permMgr.RemovePermissionsForApp(localId); + Services.cookies.removeCookiesForApp(localId, false); + this._clearPrivateData(localId, false); + } + + let appDir = FileUtils.getDir("coreAppsDir", ["webapps"], false); + // c + for (let id in aData) { + // Core apps have ids matching their domain name (eg: dialer.gaiamobile.org) + // Use that property to check if they are new or not. + if (!(id in this.webapps)) { + this.webapps[id] = aData[id]; + this.webapps[id].basePath = appDir.path; + + // Create a new localId. + this.webapps[id].localId = this._nextLocalId(); + + // Core apps are not removable. + if (this.webapps[id].removable === undefined) { + this.webapps[id].removable = false; + } + } + } + aNext(); + }).bind(this)); + } else { + aNext(); + } + }, + loadAndUpdateApps: function loadAndUpdateApps() { let runUpdate = AppsUtils.isFirstRun(Services.prefs); - // 1. - this.loadCurrentRegistry((function() { -#ifdef MOZ_WIDGET_GONK - // if first run, merge the system apps. - if (runUpdate) { - let file; - try { - file = FileUtils.getFile("coreAppsDir", ["webapps", "webapps.json"], false); - } catch(e) { } - - if (file && file.exists) { - // 2.a - this._loadJSONAsync(file, (function loadCoreRegistry(aData) { - if (!aData) { - this.registerAppsHandlers(); - return; - } - - // 2.b : core apps are not removable. - for (let id in this.webapps) { - if (id in aData || this.webapps[id].removable) - continue; - delete this.webapps[id]; - // Remove the permissions, cookies and private data for this app. - let localId = this.webapps[id].localId; - let permMgr = Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager); - permMgr.RemovePermissionsForApp(localId); - Services.cookies.removeCookiesForApp(localId, false); - this._clearPrivateData(localId, false); - } - - let appDir = FileUtils.getDir("coreAppsDir", ["webapps"], false); - // 2.c - for (let id in aData) { - // Core apps have ids matching their domain name (eg: dialer.gaiamobile.org) - // Use that property to check if they are new or not. - if (!(id in this.webapps)) { - this.webapps[id] = aData[id]; - this.webapps[id].basePath = appDir.path; - - // Create a new localId. - this.webapps[id].localId = this._nextLocalId(); - - // Core apps are not removable. - if (this.webapps[id].removable === undefined) { - this.webapps[id].removable = false; - } - } - - this.updatePermissionsForApp(id); - } - this.registerAppsHandlers(); - }).bind(this)); - } else { - // At first run, set up the permissions for eng builds. + let onAppsLoaded = (function onAppsLoaded() { + if (runUpdate) { + // At first run, set up the permissions for (let id in this.webapps) { this.updatePermissionsForApp(id); + this.updateOfflineCacheForApp(id); } - this.registerAppsHandlers(); } - } else { this.registerAppsHandlers(); - } + }).bind(this); + + this.loadCurrentRegistry((function() { +#ifdef MOZ_WIDGET_GONK + // if first run, merge the system apps. + if (runUpdate) + this.installSystemApps(onAppsLoaded); + else + onAppsLoaded(); #else - if (runUpdate) { - // At first run, set up the permissions for desktop builds. - for (let id in this.webapps) { - this.updatePermissionsForApp(id); - } - } - this.registerAppsHandlers(); + onAppsLoaded(); #endif }).bind(this)); }, @@ -475,14 +486,14 @@ let DOMApplicationRegistry = { aCallback(data); } catch (ex) { Cu.reportError("DOMApplicationRegistry: Could not parse JSON: " + - aFile.path + " " + ex); + aFile.path + " " + ex + "\n" + ex.stack); if (aCallback) aCallback(null); } }); } catch (ex) { Cu.reportError("DOMApplicationRegistry: Could not read from " + - aFile.path + " : " + ex); + aFile.path + " : " + ex + "\n" + ex.stack); if (aCallback) aCallback(null); } @@ -1725,6 +1736,10 @@ let DOMApplicationRegistry = { switch (message.name) { case "Webapps:ClearBrowserData": this._clearPrivateData(appId, true); + // XXXbent This is a hack until bug 802366 is fixed. Currently all data + // loaded in mozbrowser frames within an app believe that their + // appId is 0. + this._clearPrivateData(0, true); break; } }, diff --git a/dom/base/nsDOMClassInfo.cpp b/dom/base/nsDOMClassInfo.cpp index 7843e1ece23..8c8bff266fc 100644 --- a/dom/base/nsDOMClassInfo.cpp +++ b/dom/base/nsDOMClassInfo.cpp @@ -179,7 +179,6 @@ #ifdef MOZ_B2G_RIL #include "nsIWifi.h" -#include "nsIWifiEventInits.h" #endif // includes needed for the prototype chain interfaces @@ -1619,10 +1618,6 @@ static nsDOMClassInfoData sClassInfoData[] = { DOM_DEFAULT_SCRIPTABLE_FLAGS) #ifdef MOZ_B2G_RIL - NS_DEFINE_CLASSINFO_DATA(MozWifiStatusChangeEvent, nsDOMGenericSH, - DOM_DEFAULT_SCRIPTABLE_FLAGS) - NS_DEFINE_CLASSINFO_DATA(MozWifiConnectionInfoEvent, nsDOMGenericSH, - DOM_DEFAULT_SCRIPTABLE_FLAGS) NS_DEFINE_CLASSINFO_DATA(Telephony, nsEventTargetSH, EVENTTARGET_SCRIPTABLE_FLAGS) NS_DEFINE_CLASSINFO_DATA(TelephonyCall, nsEventTargetSH, @@ -1733,10 +1728,6 @@ NS_DEFINE_EVENT_CTOR(Event) NS_DEFINE_EVENT_CTOR(UIEvent) NS_DEFINE_EVENT_CTOR(MouseEvent) NS_DEFINE_EVENT_CTOR(WheelEvent) -#ifdef MOZ_B2G_RIL -NS_DEFINE_EVENT_CTOR(MozWifiStatusChangeEvent) -NS_DEFINE_EVENT_CTOR(MozWifiConnectionInfoEvent) -#endif #define MOZ_GENERATED_EVENT_LIST #define MOZ_GENERATED_EVENT(_event_interface) \ diff --git a/dom/base/nsDOMClassInfoClasses.h b/dom/base/nsDOMClassInfoClasses.h index 17c6f017388..57e5d9c976c 100644 --- a/dom/base/nsDOMClassInfoClasses.h +++ b/dom/base/nsDOMClassInfoClasses.h @@ -488,8 +488,6 @@ DOMCI_CLASS(MutationObserver) DOMCI_CLASS(MutationRecord) #ifdef MOZ_B2G_RIL -DOMCI_CLASS(MozWifiStatusChangeEvent) -DOMCI_CLASS(MozWifiConnectionInfoEvent) DOMCI_CLASS(Telephony) DOMCI_CLASS(TelephonyCall) DOMCI_CLASS(CallEvent) diff --git a/dom/indexedDB/DatabaseInfo.cpp b/dom/indexedDB/DatabaseInfo.cpp index b443e09b7c7..12a61248a48 100644 --- a/dom/indexedDB/DatabaseInfo.cpp +++ b/dom/indexedDB/DatabaseInfo.cpp @@ -181,31 +181,6 @@ DatabaseInfo::Remove(nsIAtom* aId) } } -PLDHashOperator -EnumerateDatabasesRemoveOrigin(nsISupports* aId, - DatabaseInfo*& aDatabaseInfo, - void* aUserArg) -{ - NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - - const nsACString* origin = static_cast(aUserArg); - return aDatabaseInfo->origin.Equals(*origin) ? - PL_DHASH_REMOVE : - PL_DHASH_NEXT; -} - -// static -void -DatabaseInfo::RemoveAllForOrigin(const nsACString& aOrigin) -{ - NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - - if (gDatabaseHash) { - gDatabaseHash->Enumerate(EnumerateDatabasesRemoveOrigin, - const_cast(&aOrigin)); - } -} - bool DatabaseInfo::GetObjectStoreNames(nsTArray& aNames) { diff --git a/dom/indexedDB/DatabaseInfo.h b/dom/indexedDB/DatabaseInfo.h index b3523cf5634..2a9901cc653 100644 --- a/dom/indexedDB/DatabaseInfo.h +++ b/dom/indexedDB/DatabaseInfo.h @@ -62,8 +62,6 @@ struct DatabaseInfo : public DatabaseInfoGuts static void Remove(nsIAtom* aId); - static void RemoveAllForOrigin(const nsACString& aOrigin); - bool GetObjectStoreNames(nsTArray& aNames); bool ContainsStoreName(const nsAString& aName); diff --git a/dom/indexedDB/IDBDatabase.cpp b/dom/indexedDB/IDBDatabase.cpp index 75fc78e8c27..f92839ca229 100644 --- a/dom/indexedDB/IDBDatabase.cpp +++ b/dom/indexedDB/IDBDatabase.cpp @@ -10,6 +10,7 @@ #include "mozilla/Mutex.h" #include "mozilla/storage.h" +#include "mozilla/unused.h" #include "mozilla/dom/ContentParent.h" #include "nsDOMClassInfo.h" #include "nsDOMLists.h" @@ -33,6 +34,7 @@ #include "nsContentUtils.h" #include "ipc/IndexedDBChild.h" +#include "ipc/IndexedDBParent.h" USING_INDEXEDDB_NAMESPACE using mozilla::dom::ContentParent; @@ -269,12 +271,14 @@ IDBDatabase::Invalidate() if (owner) { IndexedDatabaseManager::CancelPromptsForWindow(owner); } -} -bool -IDBDatabase::IsInvalidated() -{ - return mInvalidated; + DatabaseInfo::Remove(mDatabaseId); + + // And let the child process know as well. + if (mActorParent) { + NS_ASSERTION(IndexedDatabaseManager::IsMainProcess(), "Wrong process!"); + mozilla::unused << mActorParent->SendInvalidate(); + } } void @@ -299,8 +303,9 @@ IDBDatabase::DisconnectFromActor() } bool -IDBDatabase::IsDisconnectedFromActor() +IDBDatabase::IsDisconnectedFromActor() const { + NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); return mDisconnected; } @@ -330,7 +335,7 @@ IDBDatabase::CloseInternal(bool aIsDead) } // And let the parent process know as well. - if (mActorChild) { + if (mActorChild && !IsInvalidated()) { NS_ASSERTION(!IndexedDatabaseManager::IsMainProcess(), "Wrong process!"); mActorChild->SendClose(aIsDead); } @@ -338,7 +343,7 @@ IDBDatabase::CloseInternal(bool aIsDead) } bool -IDBDatabase::IsClosed() +IDBDatabase::IsClosed() const { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); return mClosed; diff --git a/dom/indexedDB/IDBDatabase.h b/dom/indexedDB/IDBDatabase.h index afc780d41e4..286d2a67682 100644 --- a/dom/indexedDB/IDBDatabase.h +++ b/dom/indexedDB/IDBDatabase.h @@ -74,12 +74,12 @@ public: return mDatabaseInfo; } - const nsString& Name() + const nsString& Name() const { return mName; } - const nsString& FilePath() + const nsString& FilePath() const { return mFilePath; } @@ -95,7 +95,7 @@ public: return doc.forget(); } - nsCString& Origin() + const nsCString& Origin() const { return mASCIIOrigin; } @@ -103,20 +103,24 @@ public: void Invalidate(); // Whether or not the database has been invalidated. If it has then no further - // transactions for this database will be allowed to run. - bool IsInvalidated(); + // transactions for this database will be allowed to run. This function may be + // called on any thread. + bool IsInvalidated() const + { + return mInvalidated; + } void DisconnectFromActor(); // Whether or not the database has been disconnected from its actor. If true // it is not safe to send any IPC messages to the actor representing this db // or any of its subactors. - bool IsDisconnectedFromActor(); + bool IsDisconnectedFromActor() const; void CloseInternal(bool aIsDead); // Whether or not the database has had Close called on it. - bool IsClosed(); + bool IsClosed() const; void EnterSetVersionTransaction(); void ExitSetVersionTransaction(); diff --git a/dom/indexedDB/IDBFactory.cpp b/dom/indexedDB/IDBFactory.cpp index 2a365896eba..664c48ffe8b 100644 --- a/dom/indexedDB/IDBFactory.cpp +++ b/dom/indexedDB/IDBFactory.cpp @@ -541,8 +541,9 @@ IDBFactory::OpenCommon(const nsAString& aName, IndexedDatabaseManager* mgr = IndexedDatabaseManager::Get(); NS_ASSERTION(mgr, "This should never be null!"); - rv = - mgr->WaitForOpenAllowed(mASCIIOrigin, openHelper->Id(), permissionHelper); + rv = + mgr->WaitForOpenAllowed(OriginOrPatternString::FromOrigin(mASCIIOrigin), + openHelper->Id(), permissionHelper); NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); } else if (aDeleting) { diff --git a/dom/indexedDB/IndexedDatabase.h b/dom/indexedDB/IndexedDatabase.h index f613c4ccc92..c9ff94e0533 100644 --- a/dom/indexedDB/IndexedDatabase.h +++ b/dom/indexedDB/IndexedDatabase.h @@ -175,6 +175,44 @@ struct SerializedStructuredCloneWriteInfo uint64_t offsetToKeyProp; }; +class OriginOrPatternString : public nsCString +{ +public: + static OriginOrPatternString + FromOrigin(const nsACString& aOrigin) + { + return OriginOrPatternString(aOrigin, true); + } + + static OriginOrPatternString + FromPattern(const nsACString& aPattern) + { + return OriginOrPatternString(aPattern, false); + } + + bool + IsOrigin() const + { + return mIsOrigin; + } + + bool + IsPattern() const + { + return !mIsOrigin; + } + +private: + OriginOrPatternString(const nsACString& aOriginOrPattern, bool aIsOrigin) + : nsCString(aOriginOrPattern), mIsOrigin(aIsOrigin) + { } + + bool + operator==(const OriginOrPatternString& aOther) MOZ_DELETE; + + bool mIsOrigin; +}; + END_INDEXEDDB_NAMESPACE #endif // mozilla_dom_indexeddb_indexeddatabase_h__ diff --git a/dom/indexedDB/IndexedDatabaseManager.cpp b/dom/indexedDB/IndexedDatabaseManager.cpp index b7e0d31d579..dde8a65f812 100644 --- a/dom/indexedDB/IndexedDatabaseManager.cpp +++ b/dom/indexedDB/IndexedDatabaseManager.cpp @@ -5,14 +5,15 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "IndexedDatabaseManager.h" -#include "DatabaseInfo.h" +#include "mozIApplicationClearPrivateDataParams.h" #include "nsIAtom.h" #include "nsIConsoleService.h" #include "nsIDOMScriptObjectFactory.h" #include "nsIFile.h" #include "nsIFileStorage.h" #include "nsIObserverService.h" +#include "nsIPrincipal.h" #include "nsIScriptError.h" #include "nsIScriptObjectPrincipal.h" #include "nsIScriptSecurityManager.h" @@ -27,8 +28,10 @@ #include "mozilla/storage.h" #include "nsAppDirectoryServiceDefs.h" #include "nsContentUtils.h" +#include "nsCRTGlue.h" #include "nsDirectoryServiceUtils.h" #include "nsEventDispatcher.h" +#include "nsScriptSecurityManager.h" #include "nsThreadUtils.h" #include "nsXPCOM.h" #include "nsXPCOMPrivate.h" @@ -133,34 +136,247 @@ EnumerateToTArray(const nsACString& aKey, NS_ASSERTION(aValue, "Null pointer!"); NS_ASSERTION(aUserArg, "Null pointer!"); - nsTArray* array = - static_cast*>(aUserArg); - - if (!array->AppendElements(*aValue)) { - NS_WARNING("Out of memory!"); - return PL_DHASH_STOP; - } - + static_cast*>(aUserArg)->AppendElements(*aValue); return PL_DHASH_NEXT; } +bool +PatternMatchesOrigin(const nsACString& aPatternString, const nsACString& aOrigin) +{ + // Aren't we smart! + return StringBeginsWith(aOrigin, aPatternString); +} + +enum MozBrowserPatternFlag +{ + MozBrowser = 0, + NotMozBrowser, + IgnoreMozBrowser +}; + +// Use one of the friendly overloads below. +void +GetOriginPatternString(uint32_t aAppId, MozBrowserPatternFlag aBrowserFlag, + const nsACString& aOrigin, nsAutoCString& _retval) +{ + NS_ASSERTION(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID, + "Bad appId!"); + NS_ASSERTION(aOrigin.IsEmpty() || aBrowserFlag != IgnoreMozBrowser, + "Bad args!"); + + if (aOrigin.IsEmpty()) { + _retval.Truncate(); + + _retval.AppendInt(aAppId); + _retval.Append('+'); + + if (aBrowserFlag != IgnoreMozBrowser) { + if (aBrowserFlag == MozBrowser) { + _retval.Append('t'); + } + else { + _retval.Append('f'); + } + _retval.Append('+'); + } + + return; + } + +#ifdef DEBUG + if (aAppId != nsIScriptSecurityManager::NO_APP_ID || + aBrowserFlag == MozBrowser) { + nsAutoCString pattern; + GetOriginPatternString(aAppId, aBrowserFlag, EmptyCString(), pattern); + NS_ASSERTION(PatternMatchesOrigin(pattern, aOrigin), + "Origin doesn't match parameters!"); + } +#endif + + _retval = aOrigin; +} + +void +GetOriginPatternString(uint32_t aAppId, nsAutoCString& _retval) +{ + return GetOriginPatternString(aAppId, IgnoreMozBrowser, EmptyCString(), + _retval); +} + +void +GetOriginPatternString(uint32_t aAppId, bool aBrowserOnly, + nsAutoCString& _retval) +{ + return GetOriginPatternString(aAppId, + aBrowserOnly ? MozBrowser : NotMozBrowser, + EmptyCString(), _retval); +} + +void +GetOriginPatternString(uint32_t aAppId, bool aBrowserOnly, + const nsACString& aOrigin, nsAutoCString& _retval) +{ + return GetOriginPatternString(aAppId, + aBrowserOnly ? MozBrowser : NotMozBrowser, + aOrigin, _retval); +} + +void +GetOriginPatternStringMaybeIgnoreBrowser(uint32_t aAppId, bool aBrowserOnly, + nsAutoCString& _retval) +{ + return GetOriginPatternString(aAppId, + aBrowserOnly ? MozBrowser : IgnoreMozBrowser, + EmptyCString(), _retval); +} + +template +class PatternMatchArray : public nsAutoTArray +{ + typedef PatternMatchArray SelfType; + + struct Closure + { + Closure(SelfType& aSelf, const nsACString& aPattern) + : mSelf(aSelf), mPattern(aPattern) + { } + + SelfType& mSelf; + const nsACString& mPattern; + }; + +public: + template + void + Find(const T& aHashtable, + const nsACString& aPattern) + { + SelfType::Clear(); + + Closure closure(*this, aPattern); + aHashtable.EnumerateRead(SelfType::Enumerate, &closure); + } + +private: + static PLDHashOperator + Enumerate(const nsACString& aKey, + nsTArray* aValue, + void* aUserArg) + { + NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); + NS_ASSERTION(!aKey.IsEmpty(), "Empty key!"); + NS_ASSERTION(aValue, "Null pointer!"); + NS_ASSERTION(aUserArg, "Null pointer!"); + + Closure* closure = static_cast(aUserArg); + + if (PatternMatchesOrigin(closure->mPattern, aKey)) { + closure->mSelf.AppendElements(*aValue); + } + + return PL_DHASH_NEXT; + } +}; + +typedef PatternMatchArray DatabasePatternMatchArray; + PLDHashOperator -InvalidateAllFileManagers(const nsACString& aKey, - nsTArray >* aValue, - void* aUserArg) +InvalidateAndRemoveFileManagers( + const nsACString& aKey, + nsAutoPtr > >& aValue, + void* aUserArg) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ASSERTION(!aKey.IsEmpty(), "Empty key!"); NS_ASSERTION(aValue, "Null pointer!"); - for (uint32_t i = 0; i < aValue->Length(); i++) { - nsRefPtr fileManager = aValue->ElementAt(i); - fileManager->Invalidate(); + const nsACString* pattern = + static_cast(aUserArg); + + if (!pattern || PatternMatchesOrigin(*pattern, aKey)) { + for (uint32_t i = 0; i < aValue->Length(); i++) { + nsRefPtr& fileManager = aValue->ElementAt(i); + fileManager->Invalidate(); + } + return PL_DHASH_REMOVE; } return PL_DHASH_NEXT; } +void +SanitizeOriginString(nsCString& aOrigin) +{ + // We want profiles to be platform-independent so we always need to replace + // the same characters on every platform. Windows has the most extensive set + // of illegal characters so we use its FILE_ILLEGAL_CHARACTERS and + // FILE_PATH_SEPARATOR. + static const char kReplaceChars[] = CONTROL_CHARACTERS "/:*?\"<>|\\"; + +#ifdef XP_WIN + NS_ASSERTION(!strcmp(kReplaceChars, + FILE_ILLEGAL_CHARACTERS FILE_PATH_SEPARATOR), + "Illegal file characters have changed!"); +#endif + + aOrigin.ReplaceChar(kReplaceChars, '+'); +} + +nsresult +GetASCIIOriginFromURI(nsIURI* aURI, + uint32_t aAppId, + bool aInMozBrowser, + nsACString& aOrigin) +{ + NS_ASSERTION(aURI, "Null uri!"); + + nsCString origin; + mozilla::GetExtendedOrigin(aURI, aAppId, aInMozBrowser, origin); + + if (origin.IsEmpty()) { + NS_WARNING("GetExtendedOrigin returned empty string!"); + return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; + } + + aOrigin.Assign(origin); + return NS_OK; +} + +nsresult +GetASCIIOriginFromPrincipal(nsIPrincipal* aPrincipal, + nsACString& aOrigin) +{ + NS_ASSERTION(aPrincipal, "Don't hand me a null principal!"); + + static const char kChromeOrigin[] = "chrome"; + + nsCString origin; + if (nsContentUtils::IsSystemPrincipal(aPrincipal)) { + origin.AssignLiteral(kChromeOrigin); + } + else { + bool isNullPrincipal; + nsresult rv = aPrincipal->GetIsNullPrincipal(&isNullPrincipal); + NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); + + if (isNullPrincipal) { + NS_WARNING("IndexedDB not supported from this principal!"); + return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; + } + + rv = aPrincipal->GetExtendedOrigin(origin); + NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); + + if (origin.EqualsLiteral(kChromeOrigin)) { + NS_WARNING("Non-chrome principal can't use chrome origin!"); + return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; + } + } + + aOrigin.Assign(origin); + return NS_OK; +} + } // anonymous namespace IndexedDatabaseManager::IndexedDatabaseManager() @@ -297,10 +513,10 @@ IndexedDatabaseManager::GetDirectoryForOrigin(const nsACString& aASCIIOrigin, rv = directory->InitWithPath(GetBaseDirectory()); NS_ENSURE_SUCCESS(rv, rv); - NS_ConvertASCIItoUTF16 originSanitized(aASCIIOrigin); - originSanitized.ReplaceChar(":/", '+'); + nsAutoCString originSanitized(aASCIIOrigin); + SanitizeOriginString(originSanitized); - rv = directory->Append(originSanitized); + rv = directory->Append(NS_ConvertASCIItoUTF16(originSanitized)); NS_ENSURE_SUCCESS(rv, rv); directory.forget(aDirectory); @@ -406,6 +622,37 @@ IndexedDatabaseManager::FireWindowOnError(nsPIDOMWindow* aOwner, return consoleService->LogMessage(scriptError); } +// static +bool +IndexedDatabaseManager::OriginMatchesApp(const nsACString& aOrigin, + uint32_t aAppId) +{ + NS_ASSERTION(!aOrigin.IsEmpty(), "Empty origin!"); + NS_ASSERTION(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID, + "Bad appId!"); + + nsAutoCString pattern; + GetOriginPatternString(aAppId, pattern); + + return PatternMatchesOrigin(pattern, aOrigin); +} + +// static +bool +IndexedDatabaseManager::OriginMatchesApp(const nsACString& aOrigin, + uint32_t aAppId, + bool aInMozBrowser) +{ + NS_ASSERTION(!aOrigin.IsEmpty(), "Empty origin!"); + NS_ASSERTION(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID, + "Bad appId!"); + + nsAutoCString pattern; + GetOriginPatternString(aAppId, aInMozBrowser, pattern); + + return PatternMatchesOrigin(pattern, aOrigin); +} + bool IndexedDatabaseManager::RegisterDatabase(IDBDatabase* aDatabase) { @@ -466,15 +713,16 @@ IndexedDatabaseManager::OnUsageCheckComplete(AsyncUsageRunnable* aRunnable) } nsresult -IndexedDatabaseManager::WaitForOpenAllowed(const nsACString& aOrigin, - nsIAtom* aId, - nsIRunnable* aRunnable) +IndexedDatabaseManager::WaitForOpenAllowed( + const OriginOrPatternString& aOriginOrPattern, + nsIAtom* aId, + nsIRunnable* aRunnable) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - NS_ASSERTION(!aOrigin.IsEmpty(), "Empty origin!"); + NS_ASSERTION(!aOriginOrPattern.IsEmpty(), "Empty pattern!"); NS_ASSERTION(aRunnable, "Null pointer!"); - nsAutoPtr op(new SynchronizedOp(aOrigin, aId)); + nsAutoPtr op(new SynchronizedOp(aOriginOrPattern, aId)); // See if this runnable needs to wait. bool delayed = false; @@ -501,16 +749,18 @@ IndexedDatabaseManager::WaitForOpenAllowed(const nsACString& aOrigin, } void -IndexedDatabaseManager::AllowNextSynchronizedOp(const nsACString& aOrigin, - nsIAtom* aId) +IndexedDatabaseManager::AllowNextSynchronizedOp( + const OriginOrPatternString& aOriginOrPattern, + nsIAtom* aId) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - NS_ASSERTION(!aOrigin.IsEmpty(), "Empty origin!"); + NS_ASSERTION(!aOriginOrPattern.IsEmpty(), "Empty origin/pattern!"); uint32_t count = mSynchronizedOps.Length(); for (uint32_t index = 0; index < count; index++) { nsAutoPtr& op = mSynchronizedOps[index]; - if (op->mOrigin.Equals(aOrigin)) { + if (op->mOriginOrPattern.IsOrigin() == aOriginOrPattern.IsOrigin() && + op->mOriginOrPattern == aOriginOrPattern) { if (op->mId == aId) { NS_ASSERTION(op->mDatabases.IsEmpty(), "How did this happen?"); @@ -531,7 +781,7 @@ IndexedDatabaseManager::AllowNextSynchronizedOp(const nsACString& aOrigin, nsresult IndexedDatabaseManager::AcquireExclusiveAccess( - const nsACString& aOrigin, + const nsACString& aPattern, IDBDatabase* aDatabase, AsyncConnectionHelper* aHelper, nsIRunnable* aRunnable, @@ -544,26 +794,26 @@ IndexedDatabaseManager::AcquireExclusiveAccess( // Find the right SynchronizedOp. SynchronizedOp* op = - FindSynchronizedOp(aOrigin, aDatabase ? aDatabase->Id() : nullptr); + FindSynchronizedOp(aPattern, aDatabase ? aDatabase->Id() : nullptr); NS_ASSERTION(op, "We didn't find a SynchronizedOp?"); NS_ASSERTION(!op->mHelper, "SynchronizedOp already has a helper?!?"); NS_ASSERTION(!op->mRunnable, "SynchronizedOp already has a runnable?!?"); - nsTArray* array; - mLiveDatabases.Get(aOrigin, &array); + DatabasePatternMatchArray matches; + matches.Find(mLiveDatabases, aPattern); // We need to wait for the databases to go away. // Hold on to all database objects that represent the same database file // (except the one that is requesting this version change). nsTArray > liveDatabases; - if (array) { + if (!matches.IsEmpty()) { if (aDatabase) { // Grab all databases that are not yet closed but whose database id match // the one we're looking for. - for (uint32_t index = 0; index < array->Length(); index++) { - IDBDatabase*& database = array->ElementAt(index); + for (uint32_t index = 0; index < matches.Length(); index++) { + IDBDatabase*& database = matches[index]; if (!database->IsClosed() && database != aDatabase && database->Id() == aDatabase->Id()) { @@ -574,7 +824,7 @@ IndexedDatabaseManager::AcquireExclusiveAccess( else { // We want *all* databases, even those that are closed, if we're going to // clear the origin. - liveDatabases.AppendElements(*array); + liveDatabases.AppendElements(matches); } } @@ -986,18 +1236,8 @@ IndexedDatabaseManager::GetASCIIOriginFromWindow(nsPIDOMWindow* aWindow, nsCOMPtr principal = sop->GetPrincipal(); NS_ENSURE_TRUE(principal, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); - if (nsContentUtils::IsSystemPrincipal(principal)) { - aASCIIOrigin.AssignLiteral("chrome"); - } - else { - nsresult rv = principal->GetExtendedOrigin(aASCIIOrigin); - NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); - - if (aASCIIOrigin.EqualsLiteral("null")) { - NS_WARNING("IndexedDB databases not allowed for this principal!"); - return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; - } - } + nsresult rv = GetASCIIOriginFromPrincipal(principal, aASCIIOrigin); + NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -1053,17 +1293,12 @@ IndexedDatabaseManager::AddFileManager(const nsACString& aOrigin, } void -IndexedDatabaseManager::InvalidateFileManagersForOrigin( - const nsACString& aOrigin) +IndexedDatabaseManager::InvalidateFileManagersForPattern( + const nsACString& aPattern) { - nsTArray >* array; - if (mFileManagers.Get(aOrigin, &array)) { - for (uint32_t i = 0; i < array->Length(); i++) { - nsRefPtr fileManager = array->ElementAt(i); - fileManager->Invalidate(); - } - mFileManagers.Remove(aOrigin); - } + NS_ASSERTION(!aPattern.IsEmpty(), "Empty pattern!"); + mFileManagers.Enumerate(InvalidateAndRemoveFileManagers, + const_cast(&aPattern)); } void @@ -1173,39 +1408,103 @@ IndexedDatabaseManager::RunSynchronizedOp(IDBDatabase* aDatabase, return NS_OK; } +IndexedDatabaseManager::SynchronizedOp* +IndexedDatabaseManager::FindSynchronizedOp(const nsACString& aPattern, + nsIAtom* aId) +{ + for (uint32_t index = 0; index < mSynchronizedOps.Length(); index++) { + const nsAutoPtr& currentOp = mSynchronizedOps[index]; + if (PatternMatchesOrigin(aPattern, currentOp->mOriginOrPattern) && + (!currentOp->mId || currentOp->mId == aId)) { + return currentOp; + } + } + + return nullptr; +} + +nsresult +IndexedDatabaseManager::ClearDatabasesForApp(uint32_t aAppId, bool aBrowserOnly) +{ + NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); + NS_ASSERTION(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID, + "Bad appId!"); + + // This only works from the main process. + NS_ENSURE_TRUE(IsMainProcess(), NS_ERROR_NOT_AVAILABLE); + + nsAutoCString pattern; + GetOriginPatternStringMaybeIgnoreBrowser(aAppId, aBrowserOnly, pattern); + + // If there is a pending or running clear operation for this app, return + // immediately. + if (IsClearOriginPending(pattern)) { + return NS_OK; + } + + OriginOrPatternString oops = OriginOrPatternString::FromPattern(pattern); + + // Queue up the origin clear runnable. + nsRefPtr runnable = new OriginClearRunnable(oops); + + nsresult rv = WaitForOpenAllowed(oops, nullptr, runnable); + NS_ENSURE_SUCCESS(rv, rv); + + runnable->AdvanceState(); + + // Give the runnable some help by invalidating any databases in the way. + DatabasePatternMatchArray matches; + matches.Find(mLiveDatabases, pattern); + + for (uint32_t index = 0; index < matches.Length(); index++) { + // We need to grab references here to prevent the database from dying while + // we invalidate it. + nsRefPtr database = matches[index]; + database->Invalidate(); + } + + return NS_OK; +} + NS_IMPL_ISUPPORTS2(IndexedDatabaseManager, nsIIndexedDatabaseManager, nsIObserver) NS_IMETHODIMP IndexedDatabaseManager::GetUsageForURI( nsIURI* aURI, - nsIIndexedDatabaseUsageCallback* aCallback) + nsIIndexedDatabaseUsageCallback* aCallback, + uint32_t aAppId, + bool aInMozBrowserOnly, + uint8_t aOptionalArgCount) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ENSURE_ARG_POINTER(aURI); NS_ENSURE_ARG_POINTER(aCallback); + // This only works from the main process. + NS_ENSURE_TRUE(IsMainProcess(), NS_ERROR_NOT_AVAILABLE); + + if (!aOptionalArgCount) { + aAppId = nsIScriptSecurityManager::NO_APP_ID; + } + // Figure out which origin we're dealing with. nsCString origin; - nsresult rv = nsContentUtils::GetASCIIOrigin(aURI, origin); + nsresult rv = GetASCIIOriginFromURI(aURI, aAppId, aInMozBrowserOnly, origin); NS_ENSURE_SUCCESS(rv, rv); + OriginOrPatternString oops = OriginOrPatternString::FromOrigin(origin); + nsRefPtr runnable = - new AsyncUsageRunnable(aURI, origin, aCallback); + new AsyncUsageRunnable(aAppId, aInMozBrowserOnly, oops, aURI, aCallback); nsRefPtr* newRunnable = mUsageRunnables.AppendElement(runnable); NS_ENSURE_TRUE(newRunnable, NS_ERROR_OUT_OF_MEMORY); - // Non-standard URIs can't create databases anyway so fire the callback - // immediately. - if (origin.EqualsLiteral("null")) { - return runnable->TakeShortcut(); - } - // Otherwise put the computation runnable in the queue. - rv = WaitForOpenAllowed(origin, nullptr, runnable); + rv = WaitForOpenAllowed(oops, nullptr, runnable); NS_ENSURE_SUCCESS(rv, rv); runnable->AdvanceState(); @@ -1216,77 +1515,95 @@ IndexedDatabaseManager::GetUsageForURI( NS_IMETHODIMP IndexedDatabaseManager::CancelGetUsageForURI( nsIURI* aURI, - nsIIndexedDatabaseUsageCallback* aCallback) + nsIIndexedDatabaseUsageCallback* aCallback, + uint32_t aAppId, + bool aInMozBrowserOnly, + uint8_t aOptionalArgCount) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ENSURE_ARG_POINTER(aURI); NS_ENSURE_ARG_POINTER(aCallback); + // This only works from the main process. + NS_ENSURE_TRUE(IsMainProcess(), NS_ERROR_NOT_AVAILABLE); + + if (!aOptionalArgCount) { + aAppId = nsIScriptSecurityManager::NO_APP_ID; + } + // See if one of our pending callbacks matches both the URI and the callback // given. Cancel an remove it if so. for (uint32_t index = 0; index < mUsageRunnables.Length(); index++) { nsRefPtr& runnable = mUsageRunnables[index]; - bool equals; - nsresult rv = runnable->mURI->Equals(aURI, &equals); - NS_ENSURE_SUCCESS(rv, rv); + if (runnable->mAppId == aAppId && + runnable->mInMozBrowserOnly == aInMozBrowserOnly) { + bool equals; + nsresult rv = runnable->mURI->Equals(aURI, &equals); + NS_ENSURE_SUCCESS(rv, rv); - if (equals && SameCOMIdentity(aCallback, runnable->mCallback)) { - runnable->Cancel(); - break; + if (equals && SameCOMIdentity(aCallback, runnable->mCallback)) { + runnable->Cancel(); + break; + } } } return NS_OK; } NS_IMETHODIMP -IndexedDatabaseManager::ClearDatabasesForURI(nsIURI* aURI) +IndexedDatabaseManager::ClearDatabasesForURI(nsIURI* aURI, + uint32_t aAppId, + bool aInMozBrowserOnly, + uint8_t aOptionalArgCount) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ENSURE_ARG_POINTER(aURI); + // This only works from the main process. + NS_ENSURE_TRUE(IsMainProcess(), NS_ERROR_NOT_AVAILABLE); + + if (!aOptionalArgCount) { + aAppId = nsIScriptSecurityManager::NO_APP_ID; + } + // Figure out which origin we're dealing with. nsCString origin; - nsresult rv = nsContentUtils::GetASCIIOrigin(aURI, origin); + nsresult rv = GetASCIIOriginFromURI(aURI, aAppId, aInMozBrowserOnly, origin); NS_ENSURE_SUCCESS(rv, rv); - // Non-standard URIs can't create databases anyway, so return immediately. - if (origin.EqualsLiteral("null")) { - return NS_OK; - } + nsAutoCString pattern; + GetOriginPatternString(aAppId, aInMozBrowserOnly, origin, pattern); // If there is a pending or running clear operation for this origin, return // immediately. - if (IsClearOriginPending(origin)) { + if (IsClearOriginPending(pattern)) { return NS_OK; } - // Queue up the origin clear runnable. - nsRefPtr runnable = new OriginClearRunnable(origin); + OriginOrPatternString oops = OriginOrPatternString::FromPattern(pattern); - rv = WaitForOpenAllowed(origin, nullptr, runnable); + // Queue up the origin clear runnable. + nsRefPtr runnable = new OriginClearRunnable(oops); + + rv = WaitForOpenAllowed(oops, nullptr, runnable); NS_ENSURE_SUCCESS(rv, rv); runnable->AdvanceState(); - // Give the runnable some help by invalidating any databases in the way. We - // need to grab references to any live databases here to prevent them from - // dying while we invalidate them. - nsTArray > liveDatabases; + // Give the runnable some help by invalidating any databases in the way. + DatabasePatternMatchArray matches; + matches.Find(mLiveDatabases, pattern); - nsTArray* array; - if (mLiveDatabases.Get(origin, &array)) { - liveDatabases.AppendElements(*array); + for (uint32_t index = 0; index < matches.Length(); index++) { + // We need to grab references to any live databases here to prevent them + // from dying while we invalidate them. + nsRefPtr database = matches[index]; + database->Invalidate(); } - for (uint32_t index = 0; index < liveDatabases.Length(); index++) { - liveDatabases[index]->Invalidate(); - } - - DatabaseInfo::RemoveAllForOrigin(origin); - // After everything has been invalidated the helper should be dispatched to // the end of the event queue. return NS_OK; @@ -1361,7 +1678,7 @@ IndexedDatabaseManager::Observe(nsISupports* aSubject, } } - mFileManagers.EnumerateRead(InvalidateAllFileManagers, nullptr); + mFileManagers.Enumerate(InvalidateAndRemoveFileManagers, nullptr); if (PR_ATOMIC_SET(&gClosed, 1)) { NS_ERROR("Close more than once?!"); @@ -1392,6 +1709,25 @@ IndexedDatabaseManager::Observe(nsISupports* aSubject, return NS_OK; } + if (!strcmp(aTopic, TOPIC_WEB_APP_CLEAR_DATA)) { + nsCOMPtr params = + do_QueryInterface(aSubject); + NS_ENSURE_TRUE(params, NS_ERROR_UNEXPECTED); + + uint32_t appId; + nsresult rv = params->GetAppId(&appId); + NS_ENSURE_SUCCESS(rv, rv); + + bool browserOnly; + rv = params->GetBrowserOnly(&browserOnly); + NS_ENSURE_SUCCESS(rv, rv); + + rv = ClearDatabasesForApp(appId, browserOnly); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; + } + NS_NOTREACHED("Unknown topic!"); return NS_ERROR_UNEXPECTED; } @@ -1408,16 +1744,75 @@ OriginClearRunnable::InvalidateOpenedDatabases( { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - OriginClearRunnable* self = static_cast(aClosure); - nsTArray > databases; databases.SwapElements(aDatabases); for (uint32_t index = 0; index < databases.Length(); index++) { databases[index]->Invalidate(); } +} - DatabaseInfo::RemoveAllForOrigin(self->mOrigin); +void +IndexedDatabaseManager:: +OriginClearRunnable::DeleteFiles(IndexedDatabaseManager* aManager) +{ + NS_ASSERTION(!NS_IsMainThread(), "Wrong thread!"); + NS_ASSERTION(aManager, "Don't pass me null!"); + + nsresult rv; + + nsCOMPtr directory = + do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv); + NS_ENSURE_SUCCESS_VOID(rv); + + rv = directory->InitWithPath(aManager->GetBaseDirectory()); + NS_ENSURE_SUCCESS_VOID(rv); + + nsCOMPtr entries; + rv = directory->GetDirectoryEntries(getter_AddRefs(entries)); + NS_ENSURE_SUCCESS_VOID(rv); + + if (!entries) { + return; + } + + nsCString originSanitized(mOriginOrPattern); + SanitizeOriginString(originSanitized); + + bool hasMore; + while (NS_SUCCEEDED((rv = entries->HasMoreElements(&hasMore))) && hasMore) { + nsCOMPtr entry; + rv = entries->GetNext(getter_AddRefs(entry)); + NS_ENSURE_SUCCESS_VOID(rv); + + nsCOMPtr file = do_QueryInterface(entry); + NS_ASSERTION(file, "Don't know what this is!"); + + bool isDirectory; + rv = file->IsDirectory(&isDirectory); + NS_ENSURE_SUCCESS_VOID(rv); + + if (!isDirectory) { + NS_WARNING("Something in the IndexedDB directory that doesn't belong!"); + continue; + } + + nsString leafName; + rv = file->GetLeafName(leafName); + NS_ENSURE_SUCCESS_VOID(rv); + + // Skip databases for other apps. + if (!PatternMatchesOrigin(originSanitized, + NS_ConvertUTF16toUTF8(leafName))) { + continue; + } + + if (NS_FAILED(file->Remove(true))) { + // This should never fail if we've closed all database connections + // correctly... + NS_ERROR("Failed to remove directory!"); + } + } } NS_IMETHODIMP @@ -1439,9 +1834,9 @@ IndexedDatabaseManager::OriginClearRunnable::Run() // Now we have to wait until the thread pool is done with all of the // databases we care about. - nsresult rv = - mgr->AcquireExclusiveAccess(mOrigin, this, InvalidateOpenedDatabases, - this); + nsresult rv = mgr->AcquireExclusiveAccess(mOriginOrPattern, this, + InvalidateOpenedDatabases, + nullptr); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1452,24 +1847,7 @@ IndexedDatabaseManager::OriginClearRunnable::Run() AdvanceState(); - // Remove the directory that contains all our databases. - nsCOMPtr directory; - nsresult rv = - mgr->GetDirectoryForOrigin(mOrigin, getter_AddRefs(directory)); - NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to get directory to remove!"); - - if (NS_SUCCEEDED(rv)) { - bool exists; - rv = directory->Exists(&exists); - NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), - "Failed to check that the directory exists!"); - - if (NS_SUCCEEDED(rv) && exists && NS_FAILED(directory->Remove(true))) { - // This should never fail if we've closed all database connections - // correctly... - NS_ERROR("Failed to remove directory!"); - } - } + DeleteFiles(mgr); // Now dispatch back to the main thread. if (NS_FAILED(NS_DispatchToMainThread(this, NS_DISPATCH_NORMAL))) { @@ -1483,10 +1861,10 @@ IndexedDatabaseManager::OriginClearRunnable::Run() case Complete: { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - mgr->InvalidateFileManagersForOrigin(mOrigin); + mgr->InvalidateFileManagersForPattern(mOriginOrPattern); // Tell the IndexedDatabaseManager that we're done. - mgr->AllowNextSynchronizedOp(mOrigin, nullptr); + mgr->AllowNextSynchronizedOp(mOriginOrPattern, nullptr); return NS_OK; } @@ -1501,19 +1879,24 @@ IndexedDatabaseManager::OriginClearRunnable::Run() } IndexedDatabaseManager::AsyncUsageRunnable::AsyncUsageRunnable( + uint32_t aAppId, + bool aInMozBrowserOnly, + const OriginOrPatternString& aOrigin, nsIURI* aURI, - const nsACString& aOrigin, nsIIndexedDatabaseUsageCallback* aCallback) : mURI(aURI), - mOrigin(aOrigin), mCallback(aCallback), mUsage(0), mFileUsage(0), + mAppId(aAppId), mCanceled(0), - mCallbackState(Pending) + mOrigin(aOrigin), + mCallbackState(Pending), + mInMozBrowserOnly(aInMozBrowserOnly) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ASSERTION(aURI, "Null pointer!"); + NS_ASSERTION(aOrigin.IsOrigin(), "Expect origin only here!"); NS_ASSERTION(!aOrigin.IsEmpty(), "Empty origin!"); NS_ASSERTION(aCallback, "Null pointer!"); } @@ -1612,7 +1995,8 @@ IndexedDatabaseManager::AsyncUsageRunnable::RunInternal() if (!mCanceled) { uint64_t usage = mUsage; IncrementUsage(&usage, mFileUsage); - mCallback->OnUsageResult(mURI, usage, mFileUsage); + mCallback->OnUsageResult(mURI, usage, mFileUsage, mAppId, + mInMozBrowserOnly); } // Clean up. @@ -1779,9 +2163,9 @@ IndexedDatabaseManager::WaitForLockedFilesToFinishRunnable::Run() } IndexedDatabaseManager:: -SynchronizedOp::SynchronizedOp(const nsACString& aOrigin, +SynchronizedOp::SynchronizedOp(const OriginOrPatternString& aOriginOrPattern, nsIAtom* aId) -: mOrigin(aOrigin), mId(aId) +: mOriginOrPattern(aOriginOrPattern), mId(aId) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); MOZ_COUNT_CTOR(IndexedDatabaseManager::SynchronizedOp); @@ -1794,24 +2178,42 @@ IndexedDatabaseManager::SynchronizedOp::~SynchronizedOp() } bool -IndexedDatabaseManager::SynchronizedOp::MustWaitFor(const SynchronizedOp& aRhs) - const +IndexedDatabaseManager:: +SynchronizedOp::MustWaitFor(const SynchronizedOp& aExistingOp) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); + bool match; + + if (aExistingOp.mOriginOrPattern.IsOrigin()) { + if (mOriginOrPattern.IsOrigin()) { + match = aExistingOp.mOriginOrPattern.Equals(mOriginOrPattern); + } + else { + match = PatternMatchesOrigin(mOriginOrPattern, aExistingOp.mOriginOrPattern); + } + } + else if (mOriginOrPattern.IsOrigin()) { + match = PatternMatchesOrigin(aExistingOp.mOriginOrPattern, mOriginOrPattern); + } + else { + match = PatternMatchesOrigin(mOriginOrPattern, aExistingOp.mOriginOrPattern) || + PatternMatchesOrigin(aExistingOp.mOriginOrPattern, mOriginOrPattern); + } + // If the origins don't match, the second can proceed. - if (!aRhs.mOrigin.Equals(mOrigin)) { + if (!match) { return false; } // If the origins and the ids match, the second must wait. - if (aRhs.mId == mId) { + if (aExistingOp.mId == mId) { return true; } // Waiting is required if either one corresponds to an origin clearing // (a null Id). - if (!aRhs.mId || !mId) { + if (!aExistingOp.mId || !mId) { return true; } diff --git a/dom/indexedDB/IndexedDatabaseManager.h b/dom/indexedDB/IndexedDatabaseManager.h index b31a5b312a5..8fe5b98aa3e 100644 --- a/dom/indexedDB/IndexedDatabaseManager.h +++ b/dom/indexedDB/IndexedDatabaseManager.h @@ -57,11 +57,11 @@ public: // Waits for databases to be cleared and for version change transactions to // complete before dispatching the given runnable. - nsresult WaitForOpenAllowed(const nsACString& aOrigin, + nsresult WaitForOpenAllowed(const OriginOrPatternString& aOriginOrPattern, nsIAtom* aId, nsIRunnable* aRunnable); - void AllowNextSynchronizedOp(const nsACString& aOrigin, + void AllowNextSynchronizedOp(const OriginOrPatternString& aOriginOrPattern, nsIAtom* aId); nsIThread* IOThread() @@ -169,7 +169,7 @@ public: const nsAString& aDatabaseName, FileManager* aFileManager); - void InvalidateFileManagersForOrigin(const nsACString& aOrigin); + void InvalidateFileManagersForPattern(const nsACString& aPattern); void InvalidateFileManager(const nsACString& aOrigin, const nsAString& aDatabaseName); @@ -200,7 +200,18 @@ public: const nsAString& aName); static nsresult - FireWindowOnError(nsPIDOMWindow* aOwner, nsEventChainPostVisitor& aVisitor); + FireWindowOnError(nsPIDOMWindow* aOwner, + nsEventChainPostVisitor& aVisitor); + + static bool + OriginMatchesApp(const nsACString& aOrigin, + uint32_t aAppId); + + static bool + OriginMatchesApp(const nsACString& aOrigin, + uint32_t aAppId, + bool aInMozBrowser); + private: IndexedDatabaseManager(); ~IndexedDatabaseManager(); @@ -225,6 +236,8 @@ private: // Called when a database has been closed. void OnDatabaseClosed(IDBDatabase* aDatabase); + nsresult ClearDatabasesForApp(uint32_t aAppId, bool aBrowserOnly); + // Responsible for clearing the database files for a particular origin on the // IO thread. Created when nsIIDBIndexedDatabaseManager::ClearDatabasesForURI // is called. Runs three times, first on the main thread, next on the IO @@ -253,8 +266,8 @@ private: NS_DECL_ISUPPORTS NS_DECL_NSIRUNNABLE - OriginClearRunnable(const nsACString& aOrigin) - : mOrigin(aOrigin), + OriginClearRunnable(const OriginOrPatternString& aOriginOrPattern) + : mOriginOrPattern(aOriginOrPattern), mCallbackState(Pending) { } @@ -279,8 +292,10 @@ private: nsTArray >& aDatabases, void* aClosure); + void DeleteFiles(IndexedDatabaseManager* aManager); + private: - nsCString mOrigin; + OriginOrPatternString mOriginOrPattern; CallbackState mCallbackState; }; @@ -311,12 +326,15 @@ private: // Running on the main thread after skipping the work Shortcut }; + public: NS_DECL_ISUPPORTS NS_DECL_NSIRUNNABLE - AsyncUsageRunnable(nsIURI* aURI, - const nsACString& aOrigin, + AsyncUsageRunnable(uint32_t aAppId, + bool aInMozBrowserOnly, + const OriginOrPatternString& aOrigin, + nsIURI* aURI, nsIIndexedDatabaseUsageCallback* aCallback); // Sets the canceled flag so that the callback is never called. @@ -349,13 +367,14 @@ private: uint64_t* aUsage); nsCOMPtr mURI; - nsCString mOrigin; - nsCOMPtr mCallback; uint64_t mUsage; uint64_t mFileUsage; + uint32_t mAppId; int32_t mCanceled; + OriginOrPatternString mOrigin; CallbackState mCallbackState; + bool mInMozBrowserOnly; }; // Called when AsyncUsageRunnable has finished its Run() method. @@ -366,16 +385,17 @@ private: // clearing dbs for an origin, etc). struct SynchronizedOp { - SynchronizedOp(const nsACString& aOrigin, nsIAtom* aId); + SynchronizedOp(const OriginOrPatternString& aOriginOrPattern, + nsIAtom* aId); ~SynchronizedOp(); - // Test whether the second SynchronizedOp needs to get behind this one. - bool MustWaitFor(const SynchronizedOp& aRhs) const; + // Test whether this SynchronizedOp needs to wait for the given op. + bool MustWaitFor(const SynchronizedOp& aOp); void DelayRunnable(nsIRunnable* aRunnable); void DispatchDelayedRunnables(); - const nsCString mOrigin; + const OriginOrPatternString mOriginOrPattern; nsCOMPtr mId; nsRefPtr mHelper; nsCOMPtr mRunnable; @@ -442,22 +462,12 @@ private: static nsresult RunSynchronizedOp(IDBDatabase* aDatabase, SynchronizedOp* aOp); - SynchronizedOp* FindSynchronizedOp(const nsACString& aOrigin, - nsIAtom* aId) - { - for (uint32_t index = 0; index < mSynchronizedOps.Length(); index++) { - const nsAutoPtr& currentOp = mSynchronizedOps[index]; - if (currentOp->mOrigin == aOrigin && - (!currentOp->mId || currentOp->mId == aId)) { - return currentOp; - } - } - return nullptr; - } + SynchronizedOp* FindSynchronizedOp(const nsACString& aPattern, + nsIAtom* aId); - bool IsClearOriginPending(const nsACString& aOrigin) + bool IsClearOriginPending(const nsACString& aPattern) { - return !!FindSynchronizedOp(aOrigin, nullptr); + return !!FindSynchronizedOp(aPattern, nullptr); } // Maintains a list of live databases per origin. diff --git a/dom/indexedDB/Makefile.in b/dom/indexedDB/Makefile.in index cb55f27bbd1..fef085894e3 100644 --- a/dom/indexedDB/Makefile.in +++ b/dom/indexedDB/Makefile.in @@ -66,12 +66,13 @@ EXPORTS_mozilla/dom/indexedDB = \ $(NULL) LOCAL_INCLUDES = \ - -I$(topsrcdir)/db/sqlite3/src \ - -I$(topsrcdir)/xpcom/build \ - -I$(topsrcdir)/dom/base \ - -I$(topsrcdir)/dom/src/storage \ + -I$(topsrcdir)/caps/include \ -I$(topsrcdir)/content/base/src \ -I$(topsrcdir)/content/events/src \ + -I$(topsrcdir)/db/sqlite3/src \ + -I$(topsrcdir)/dom/base \ + -I$(topsrcdir)/dom/src/storage \ + -I$(topsrcdir)/xpcom/build \ $(NULL) DEFINES += -D_IMPL_NS_LAYOUT diff --git a/dom/indexedDB/OpenDatabaseHelper.cpp b/dom/indexedDB/OpenDatabaseHelper.cpp index 8f5521819d2..3a524e98c21 100644 --- a/dom/indexedDB/OpenDatabaseHelper.cpp +++ b/dom/indexedDB/OpenDatabaseHelper.cpp @@ -2018,7 +2018,9 @@ OpenDatabaseHelper::Run() IndexedDatabaseManager* manager = IndexedDatabaseManager::Get(); NS_ASSERTION(manager, "This should never be null!"); - manager->AllowNextSynchronizedOp(mASCIIOrigin, mDatabaseId); + manager->AllowNextSynchronizedOp( + OriginOrPatternString::FromOrigin(mASCIIOrigin), + mDatabaseId); ReleaseMainThreadObjects(); diff --git a/dom/indexedDB/ipc/IndexedDBChild.cpp b/dom/indexedDB/ipc/IndexedDBChild.cpp index 34d6dcde60b..6bd8a8f4d24 100644 --- a/dom/indexedDB/ipc/IndexedDBChild.cpp +++ b/dom/indexedDB/ipc/IndexedDBChild.cpp @@ -434,6 +434,15 @@ IndexedDBDatabaseChild::RecvVersionChange(const uint64_t& aOldVersion, return true; } +bool +IndexedDBDatabaseChild::RecvInvalidate() +{ + if (mDatabase) { + mDatabase->Invalidate(); + } + return true; +} + bool IndexedDBDatabaseChild::RecvPIndexedDBTransactionConstructor( PIndexedDBTransactionChild* aActor, @@ -584,9 +593,30 @@ IndexedDBTransactionChild::ActorDestroy(ActorDestroyReason aWhy) } bool -IndexedDBTransactionChild::RecvComplete(const nsresult& aRv) +IndexedDBTransactionChild::RecvComplete(const CompleteParams& aParams) { - FireCompleteEvent(aRv); + MOZ_ASSERT(mTransaction); + MOZ_ASSERT(mStrongTransaction); + + nsresult resultCode; + + switch (aParams.type()) { + case CompleteParams::TCompleteResult: + resultCode = NS_OK; + break; + case CompleteParams::TAbortResult: + resultCode = aParams.get_AbortResult().errorCode(); + if (NS_SUCCEEDED(resultCode)) { + resultCode = NS_ERROR_DOM_INDEXEDDB_ABORT_ERR; + } + break; + + default: + MOZ_NOT_REACHED("Unknown union type!"); + return false; + } + + FireCompleteEvent(resultCode); return true; } diff --git a/dom/indexedDB/ipc/IndexedDBChild.h b/dom/indexedDB/ipc/IndexedDBChild.h index ce2ca59f325..38fd1ce4db1 100644 --- a/dom/indexedDB/ipc/IndexedDBChild.h +++ b/dom/indexedDB/ipc/IndexedDBChild.h @@ -119,6 +119,9 @@ protected: RecvVersionChange(const uint64_t& aOldVersion, const uint64_t& aNewVersion) MOZ_OVERRIDE; + virtual bool + RecvInvalidate() MOZ_OVERRIDE; + virtual bool RecvPIndexedDBTransactionConstructor(PIndexedDBTransactionChild* aActor, const TransactionParams& aParams) @@ -163,7 +166,7 @@ protected: ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE; virtual bool - RecvComplete(const nsresult& aRv) MOZ_OVERRIDE; + RecvComplete(const CompleteParams& aParams) MOZ_OVERRIDE; virtual PIndexedDBObjectStoreChild* AllocPIndexedDBObjectStore(const ObjectStoreConstructorParams& aParams) diff --git a/dom/indexedDB/ipc/IndexedDBParent.cpp b/dom/indexedDB/ipc/IndexedDBParent.cpp index 7594d702709..30b25b771ed 100644 --- a/dom/indexedDB/ipc/IndexedDBParent.cpp +++ b/dom/indexedDB/ipc/IndexedDBParent.cpp @@ -355,7 +355,11 @@ IndexedDBDatabaseParent::HandleRequestEvent(nsIDOMEvent* aEvent, } MOZ_ASSERT(!mDatabase || mDatabase == databaseConcrete); - mDatabase = databaseConcrete; + + if (!mDatabase) { + databaseConcrete->SetActor(this); + mDatabase = databaseConcrete; + } return NS_OK; } @@ -390,6 +394,7 @@ IndexedDBDatabaseParent::HandleRequestEvent(nsIDOMEvent* aEvent, return NS_ERROR_FAILURE; } + databaseConcrete->SetActor(this); mDatabase = databaseConcrete; return NS_OK; @@ -555,10 +560,10 @@ IndexedDBTransactionParent::HandleEvent(nsIDOMEvent* aEvent) nsresult rv = aEvent->GetType(type); NS_ENSURE_SUCCESS(rv, rv); - nsresult transactionResult; + CompleteParams params; if (type.EqualsLiteral(COMPLETE_EVT_STR)) { - transactionResult = NS_OK; + params = CompleteResult(); } else if (type.EqualsLiteral(ABORT_EVT_STR)) { #ifdef DEBUG @@ -573,15 +578,14 @@ IndexedDBTransactionParent::HandleEvent(nsIDOMEvent* aEvent) } } #endif - MOZ_ASSERT(NS_FAILED(mTransaction->GetAbortCode())); - transactionResult = mTransaction->GetAbortCode(); + params = AbortResult(mTransaction->GetAbortCode()); } else { NS_WARNING("Unknown message type!"); return NS_ERROR_UNEXPECTED; } - if (!SendComplete(transactionResult)) { + if (!SendComplete(params)) { return NS_ERROR_FAILURE; } diff --git a/dom/indexedDB/ipc/PIndexedDBDatabase.ipdl b/dom/indexedDB/ipc/PIndexedDBDatabase.ipdl index 25c2c2a8532..9efe393c7b7 100644 --- a/dom/indexedDB/ipc/PIndexedDBDatabase.ipdl +++ b/dom/indexedDB/ipc/PIndexedDBDatabase.ipdl @@ -58,6 +58,8 @@ child: VersionChange(uint64_t oldVersion, uint64_t newVersion); + Invalidate(); + both: PIndexedDBTransaction(TransactionParams params); }; diff --git a/dom/indexedDB/ipc/PIndexedDBTransaction.ipdl b/dom/indexedDB/ipc/PIndexedDBTransaction.ipdl index 3dc1b14497d..de1177204ca 100644 --- a/dom/indexedDB/ipc/PIndexedDBTransaction.ipdl +++ b/dom/indexedDB/ipc/PIndexedDBTransaction.ipdl @@ -31,6 +31,20 @@ union ObjectStoreConstructorParams GetObjectStoreParams; }; +struct CompleteResult +{ }; + +struct AbortResult +{ + nsresult errorCode; +}; + +union CompleteParams +{ + CompleteResult; + AbortResult; +}; + } // namespace ipc protocol PIndexedDBTransaction @@ -51,7 +65,7 @@ parent: DeleteObjectStore(nsString name); child: - Complete(nsresult rv); + Complete(CompleteParams params); }; } // namespace indexedDB diff --git a/dom/indexedDB/nsIIndexedDatabaseManager.idl b/dom/indexedDB/nsIIndexedDatabaseManager.idl index 58cb3f1ee90..fef40c7eb99 100644 --- a/dom/indexedDB/nsIIndexedDatabaseManager.idl +++ b/dom/indexedDB/nsIIndexedDatabaseManager.idl @@ -8,18 +8,17 @@ interface nsIURI; -[scriptable, function, uuid(ef1795ec-7050-4658-b80f-0e48cbe1d64b)] +[scriptable, function, uuid(38f15cc7-2df0-4a90-8b7f-1606b2243522)] interface nsIIndexedDatabaseUsageCallback : nsISupports { - /** - * - */ void onUsageResult(in nsIURI aURI, in unsigned long long aUsage, - in unsigned long long aFileUsage); + in unsigned long long aFileUsage, + in unsigned long aAppId, + in boolean aInMozBrowserOnly); }; -[scriptable, builtinclass, uuid(02256aa7-70d8-473f-bf3b-8cb35d28fd75)] +[scriptable, builtinclass, uuid(e5168115-baff-4559-887e-7c0405cc9e63)] interface nsIIndexedDatabaseManager : nsISupports { /** @@ -31,8 +30,11 @@ interface nsIIndexedDatabaseManager : nsISupports * @param aCallback * The callback that will be called when the usage is available. */ + [optional_argc] void getUsageForURI(in nsIURI aURI, - in nsIIndexedDatabaseUsageCallback aCallback); + in nsIIndexedDatabaseUsageCallback aCallback, + [optional] in unsigned long aAppId, + [optional] in boolean aInMozBrowserOnly); /** * Cancels an asynchronous usage check initiated by a previous call to @@ -43,9 +45,11 @@ interface nsIIndexedDatabaseManager : nsISupports * @param aCallback * The callback that will be called when the usage is available. */ + [optional_argc] void cancelGetUsageForURI(in nsIURI aURI, - in nsIIndexedDatabaseUsageCallback aCallback); - + in nsIIndexedDatabaseUsageCallback aCallback, + [optional] in unsigned long aAppId, + [optional] in boolean aInMozBrowserOnly); /** * Removes all databases stored for the given URI. The files may not be @@ -54,7 +58,10 @@ interface nsIIndexedDatabaseManager : nsISupports * @param aURI * The URI whose databases are to be cleared. */ - void clearDatabasesForURI(in nsIURI aURI); + [optional_argc] + void clearDatabasesForURI(in nsIURI aURI, + [optional] in unsigned long aAppId, + [optional] in boolean aInMozBrowserOnly); /** * Defines indexedDB and IDBKeyrange with its static functions on diff --git a/dom/indexedDB/test/Makefile.in b/dom/indexedDB/test/Makefile.in index 8e15a90d900..9c008e8cd8d 100644 --- a/dom/indexedDB/test/Makefile.in +++ b/dom/indexedDB/test/Makefile.in @@ -21,6 +21,8 @@ MOCHITEST_FILES = \ event_propagation_iframe.html \ exceptions_in_events_iframe.html \ file.js \ + file_app_isolation.html \ + file_app_isolation.js \ helpers.js \ leaving_page_iframe.html \ test_add_put.html \ @@ -100,12 +102,13 @@ MOCHITEST_FILES = \ test_setVersion_events.html \ test_setVersion_exclusion.html \ test_unique_index_update.html \ + test_webapp_clearBrowserData.html \ third_party_iframe1.html \ third_party_iframe2.html \ test_app_isolation_inproc.html \ test_app_isolation_oop.html \ - file_app_isolation.html \ - file_app_isolation.js \ + webapp_clearBrowserData_appFrame.html \ + webapp_clearBrowserData_browserFrame.html \ $(NULL) # test_writer_starvation.html disabled for infinite loops, bug 595368 diff --git a/dom/indexedDB/test/test_webapp_clearBrowserData.html b/dom/indexedDB/test/test_webapp_clearBrowserData.html new file mode 100644 index 00000000000..a8d492713ab --- /dev/null +++ b/dom/indexedDB/test/test_webapp_clearBrowserData.html @@ -0,0 +1,137 @@ + + + + Indexed Database Clear Browser Data Test + + + + + + + + + + + + diff --git a/dom/indexedDB/test/webapp_clearBrowserData_appFrame.html b/dom/indexedDB/test/webapp_clearBrowserData_appFrame.html new file mode 100644 index 00000000000..0223158f7b2 --- /dev/null +++ b/dom/indexedDB/test/webapp_clearBrowserData_appFrame.html @@ -0,0 +1,126 @@ + + + + Indexed Database Clear Browser Data Test + + + + + + + + + diff --git a/dom/indexedDB/test/webapp_clearBrowserData_browserFrame.html b/dom/indexedDB/test/webapp_clearBrowserData_browserFrame.html new file mode 100644 index 00000000000..ce8eb6417b2 --- /dev/null +++ b/dom/indexedDB/test/webapp_clearBrowserData_browserFrame.html @@ -0,0 +1,103 @@ + + + + Indexed Database Clear Browser Data Test + + + + + + + + + diff --git a/dom/interfaces/apps/mozIApplicationClearPrivateDataParams.idl b/dom/interfaces/apps/mozIApplicationClearPrivateDataParams.idl index 06b8e5b96c2..b468c9c371d 100644 --- a/dom/interfaces/apps/mozIApplicationClearPrivateDataParams.idl +++ b/dom/interfaces/apps/mozIApplicationClearPrivateDataParams.idl @@ -13,3 +13,7 @@ interface mozIApplicationClearPrivateDataParams : nsISupports readonly attribute unsigned long appId; readonly attribute boolean browserOnly; }; + +%{C++ +#define TOPIC_WEB_APP_CLEAR_DATA "webapps-clear-data" +%} diff --git a/dom/interfaces/events/Makefile.in b/dom/interfaces/events/Makefile.in index d364b2c3299..232af1e077b 100644 --- a/dom/interfaces/events/Makefile.in +++ b/dom/interfaces/events/Makefile.in @@ -57,7 +57,6 @@ XPIDLSRCS = \ nsIDOMCustomEvent.idl \ nsIDOMCompositionEvent.idl \ nsIDOMWheelEvent.idl \ - nsIWifiEventInits.idl \ $(NULL) include $(topsrcdir)/config/rules.mk diff --git a/dom/interfaces/events/nsIDOMEvent.idl b/dom/interfaces/events/nsIDOMEvent.idl index a641a51cd86..5ba17449e2b 100644 --- a/dom/interfaces/events/nsIDOMEvent.idl +++ b/dom/interfaces/events/nsIDOMEvent.idl @@ -329,9 +329,5 @@ NS_NewDOMSmsEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsresult NS_NewDOMMozSettingsEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent* aEvent); nsresult -NS_NewDOMMozWifiStatusChangeEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent* aEvent); -nsresult -NS_NewDOMMozWifiConnectionInfoEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent* aEvent); -nsresult NS_NewDOMMozApplicationEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent* aEvent); %} diff --git a/dom/interfaces/events/nsIWifiEventInits.idl b/dom/interfaces/events/nsIWifiEventInits.idl deleted file mode 100644 index 539e4c18ac8..00000000000 --- a/dom/interfaces/events/nsIWifiEventInits.idl +++ /dev/null @@ -1,24 +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 "nsIDOMEventTarget.idl" -#include "nsIDOMEvent.idl" - -interface nsIVariant; - -dictionary MozWifiStatusChangeEventInit : EventInit -{ - nsIVariant network; - DOMString status; -}; - -dictionary MozWifiConnectionInfoEventInit : EventInit -{ - nsIVariant network; - short signalStrength; - short relSignalStrength; - long linkSpeed; - DOMString ipAddress; -}; diff --git a/dom/ipc/TabParent.cpp b/dom/ipc/TabParent.cpp index 11db8f51b24..676c5bd9796 100644 --- a/dom/ipc/TabParent.cpp +++ b/dom/ipc/TabParent.cpp @@ -884,6 +884,23 @@ TabParent::RecvPIndexedDBConstructor(PIndexedDBParent* aActor, NS_RUNTIMEABORT("Not supported yet!"); } + nsresult rv; + + // XXXbent Need to make sure we have a whitelist for chrome databases! + + // Verify the appID in the origin first. + if (mApp && !aASCIIOrigin.EqualsLiteral("chrome")) { + uint32_t appId; + rv = mApp->GetLocalId(&appId); + NS_ENSURE_SUCCESS(rv, false); + + if (!IndexedDatabaseManager::OriginMatchesApp(aASCIIOrigin, appId)) { + NS_WARNING("App attempted to open databases that it does not have " + "permission to access!"); + return false; + } + } + nsCOMPtr node = do_QueryInterface(GetOwnerElement()); NS_ENSURE_TRUE(node, false); @@ -897,9 +914,8 @@ TabParent::RecvPIndexedDBConstructor(PIndexedDBParent* aActor, NS_ASSERTION(contentParent, "Null manager?!"); nsRefPtr factory; - nsresult rv = - IDBFactory::Create(window, aASCIIOrigin, contentParent, - getter_AddRefs(factory)); + rv = IDBFactory::Create(window, aASCIIOrigin, contentParent, + getter_AddRefs(factory)); NS_ENSURE_SUCCESS(rv, false); if (!factory) { diff --git a/dom/media/tests/crashtests/791330.html b/dom/media/tests/crashtests/791330.html new file mode 100644 index 00000000000..35df56ad347 --- /dev/null +++ b/dom/media/tests/crashtests/791330.html @@ -0,0 +1,29 @@ + + + + + + PeerConnection test - operate on closed connection + + + + + + diff --git a/dom/media/tests/crashtests/crashtests.list b/dom/media/tests/crashtests/crashtests.list index 3740dd98b78..9145a5915ea 100644 --- a/dom/media/tests/crashtests/crashtests.list +++ b/dom/media/tests/crashtests/crashtests.list @@ -1,3 +1,4 @@ pref(media.peerconnection.enabled,true) load 780790.html pref(media.peerconnection.enabled,true) load 791270.html pref(media.peerconnection.enabled,true) load 791278.html +pref(media.peerconnection.enabled,true) load 791330.html diff --git a/dom/permission/PermissionSettings.js b/dom/permission/PermissionSettings.js index 23b127852b2..29a3d4f64db 100644 --- a/dom/permission/PermissionSettings.js +++ b/dom/permission/PermissionSettings.js @@ -5,7 +5,7 @@ "use strict"; function debug(aMsg) { - // dump("-*- PermissionSettings.js: " + aMsg + "\n"); + //dump("-*- PermissionSettings.js: " + aMsg + "\n"); } const Cc = Components.classes; @@ -28,9 +28,20 @@ function PermissionSettings() debug("Constructor"); } -var permissionManager = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager); -var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager); -var appsService = Cc["@mozilla.org/AppsService;1"].getService(Ci.nsIAppsService); +XPCOMUtils.defineLazyServiceGetter(this, + "permissionManager", + "@mozilla.org/permissionmanager;1", + "nsIPermissionManager"); + +XPCOMUtils.defineLazyServiceGetter(this, + "secMan", + "@mozilla.org/scriptsecuritymanager;1", + "nsIScriptSecurityManager"); + +XPCOMUtils.defineLazyServiceGetter(this, + "appsService", + "@mozilla.org/AppsService;1", + "nsIAppsService"); PermissionSettings.prototype = { get: function get(aPermission, aManifestURL, aOrigin, aBrowserFlag) { diff --git a/dom/permission/PermissionSettings.jsm b/dom/permission/PermissionSettings.jsm index 87f8a5572c8..15c288b22c0 100644 --- a/dom/permission/PermissionSettings.jsm +++ b/dom/permission/PermissionSettings.jsm @@ -4,11 +4,9 @@ "use strict"; -let DEBUG = 0; -if (DEBUG) - debug = function (s) { dump("-*- PermissionSettings Module: " + s + "\n"); } -else - debug = function (s) {} +function debug(s) { + //dump("-*- PermissionSettings Module: " + s + "\n"); +} const Cu = Components.utils; const Cc = Components.classes; @@ -23,9 +21,20 @@ XPCOMUtils.defineLazyServiceGetter(this, "ppmm", "@mozilla.org/parentprocessmessagemanager;1", "nsIMessageListenerManager"); -var permissionManager = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager); -var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager); -var appsService = Cc["@mozilla.org/AppsService;1"].getService(Ci.nsIAppsService); +XPCOMUtils.defineLazyServiceGetter(this, + "permissionManager", + "@mozilla.org/permissionmanager;1", + "nsIPermissionManager"); + +XPCOMUtils.defineLazyServiceGetter(this, + "secMan", + "@mozilla.org/scriptsecuritymanager;1", + "nsIScriptSecurityManager"); + +XPCOMUtils.defineLazyServiceGetter(this, + "appsService", + "@mozilla.org/AppsService;1", + "nsIAppsService"); let PermissionSettingsModule = { init: function() { @@ -62,6 +71,29 @@ let PermissionSettingsModule = { permissionManager.addFromPrincipal(principal, aData.type, action); }, + getPermission: function getPermission(aPermission, aManifestURL, aOrigin, aBrowserFlag) { + debug("getPermission: " + aPermission + ", " + aManifestURL + ", " + aOrigin); + let uri = Services.io.newURI(aOrigin, null, null); + let appID = appsService.getAppLocalIdByManifestURL(aManifestURL); + let principal = secMan.getAppCodebasePrincipal(uri, appID, aBrowserFlag); + let result = permissionManager.testExactPermissionFromPrincipal(principal, aPermission); + + switch (result) + { + case Ci.nsIPermissionManager.UNKNOWN_ACTION: + return "unknown"; + case Ci.nsIPermissionManager.ALLOW_ACTION: + return "allow"; + case Ci.nsIPermissionManager.DENY_ACTION: + return "deny"; + case Ci.nsIPermissionManager.PROMPT_ACTION: + return "prompt"; + default: + dump("Unsupported PermissionSettings Action!\n"); + return "unknown"; + } + }, + observe: function(aSubject, aTopic, aData) { ppmm.removeMessageListener("PermissionSettings:AddPermission", this); Services.obs.removeObserver(this, "profile-before-change"); diff --git a/dom/src/storage/nsDOMStorage.cpp b/dom/src/storage/nsDOMStorage.cpp index 404ecee10b8..ab7ebbe31f0 100644 --- a/dom/src/storage/nsDOMStorage.cpp +++ b/dom/src/storage/nsDOMStorage.cpp @@ -331,7 +331,7 @@ nsDOMStorageManager::Observe(nsISupports *aSubject, rv = params->GetBrowserOnly(&browserOnly); NS_ENSURE_SUCCESS(rv, rv); - MOZ_ASSERT(appId != nsIScriptSecurityManager::NO_APP_ID); + MOZ_ASSERT(appId != nsIScriptSecurityManager::UNKNOWN_APP_ID); return DOMStorageImpl::gStorageDB->RemoveAllForApp(appId, browserOnly); } diff --git a/dom/src/storage/nsDOMStoragePersistentDB.cpp b/dom/src/storage/nsDOMStoragePersistentDB.cpp index e6041ed1ed0..162841cf0a8 100644 --- a/dom/src/storage/nsDOMStoragePersistentDB.cpp +++ b/dom/src/storage/nsDOMStoragePersistentDB.cpp @@ -21,6 +21,7 @@ #include "mozIStorageFunction.h" #include "nsNetUtil.h" #include "mozilla/Attributes.h" +#include "mozilla/Telemetry.h" #include "sampler.h" @@ -226,6 +227,8 @@ nsDOMStoragePersistentDB::EnsureLoadTemporaryTableForStorage(DOMStorageImpl* aSt if (!mTempTableLoads.Get(aStorage->GetScopeDBKey(), &timeStamp)) { nsresult rv; + Telemetry::AutoTimer timer; + rv = MaybeCommitInsertTransaction(); NS_ENSURE_SUCCESS(rv, rv); @@ -307,8 +310,23 @@ nsDOMStoragePersistentDB::FlushTemporaryTable(nsCStringHashKey::KeyType aKey, nsresult nsDOMStoragePersistentDB::FlushTemporaryTables(bool force) { - mozStorageTransaction trans(mConnection, false); + nsCOMPtr stmt = + mStatements.GetCachedStatement( + "SELECT COUNT(*) FROM webappsstore2_temp WHERE modified = 1" + ); + mozStorageStatementScoper scope(stmt); + TimeStamp startTime; + bool exists; + int32_t dirtyCount; + if (stmt && + NS_SUCCEEDED(stmt->ExecuteStep(&exists)) && exists && + NS_SUCCEEDED(stmt->GetInt32(0, &dirtyCount)) && dirtyCount > 0) { + // Time the operation if dirty entries will be flushed + startTime = TimeStamp::Now(); + } + + mozStorageTransaction trans(mConnection, false); nsresult rv; FlushTemporaryTableData data; @@ -325,6 +343,10 @@ nsDOMStoragePersistentDB::FlushTemporaryTables(bool force) rv = MaybeCommitInsertTransaction(); NS_ENSURE_SUCCESS(rv, rv); + if (!startTime.IsNull()) { + Telemetry::AutoTimer timer(startTime); + } + return NS_OK; } @@ -332,6 +354,7 @@ nsresult nsDOMStoragePersistentDB::GetAllKeys(DOMStorageImpl* aStorage, nsTHashtable* aKeys) { + Telemetry::AutoTimer timer; nsresult rv; rv = MaybeCommitInsertTransaction(); @@ -384,6 +407,7 @@ nsDOMStoragePersistentDB::GetKeyValue(DOMStorageImpl* aStorage, nsAString& aValue, bool* aSecure) { + Telemetry::AutoTimer timer; SAMPLE_LABEL("nsDOMStoragePersistentDB", "GetKeyValue"); nsresult rv; @@ -435,6 +459,8 @@ nsDOMStoragePersistentDB::SetKey(DOMStorageImpl* aStorage, const nsAString& aValue, bool aSecure) { + Telemetry::AutoTimer timer; + nsresult rv; rv = EnsureLoadTemporaryTableForStorage(aStorage); @@ -541,6 +567,7 @@ nsresult nsDOMStoragePersistentDB::RemoveKey(DOMStorageImpl* aStorage, const nsAString& aKey) { + Telemetry::AutoTimer timer; nsresult rv; rv = MaybeCommitInsertTransaction(); @@ -645,6 +672,7 @@ nsDOMStoragePersistentDB::RemoveOwner(const nsACString& aOwner) nsresult nsDOMStoragePersistentDB::RemoveAll() { + Telemetry::AutoTimer timer; nsresult rv; rv = MaybeCommitInsertTransaction(); @@ -726,6 +754,8 @@ nsDOMStoragePersistentDB::GetUsageInternal(const nsACString& aQuotaDBKey, return NS_OK; } + Telemetry::AutoTimer timer; + nsresult rv; rv = MaybeCommitInsertTransaction(); diff --git a/dom/system/gonk/RadioInterfaceLayer.js b/dom/system/gonk/RadioInterfaceLayer.js index 421d8d464fe..e3a2fb3dc5a 100644 --- a/dom/system/gonk/RadioInterfaceLayer.js +++ b/dom/system/gonk/RadioInterfaceLayer.js @@ -40,6 +40,7 @@ const kSmsSentObserverTopic = "sms-sent"; const kSmsDeliveredObserverTopic = "sms-delivered"; const kMozSettingsChangedObserverTopic = "mozsettings-changed"; const kSysMsgListenerReadyObserverTopic = "system-message-listener-ready"; +const kSysClockChangeObserverTopic = "system-clock-change"; const kTimeNitzAutomaticUpdateEnabled = "time.nitz.automatic-update.enabled"; const DOM_SMS_DELIVERY_RECEIVED = "received"; const DOM_SMS_DELIVERY_SENT = "sent"; @@ -274,6 +275,7 @@ function RadioInterfaceLayer() { Services.obs.addObserver(this, "xpcom-shutdown", false); Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false); Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false); + Services.obs.addObserver(this, kSysClockChangeObserverTopic, false); this._sentSmsEnvelopes = {}; @@ -1366,12 +1368,9 @@ RadioInterfaceLayer.prototype = { }, /** - * Handle the NITZ message. + * Set the NITZ message in our system time. */ - handleNitzTime: function handleNitzTime(message) { - if (!this._nitzAutomaticUpdateEnabled) { - return; - } + setNitzTime: function setNitzTime(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( @@ -1394,6 +1393,19 @@ RadioInterfaceLayer.prototype = { } }, + /** + * Handle the NITZ message. + */ + handleNitzTime: function handleNitzTime(message) { + // Cache the latest NITZ message whenever receiving it. + this._lastNitzMessage = message; + + // Set the received NITZ time if the setting is enabled. + if (this._nitzAutomaticUpdateEnabled) { + this.setNitzTime(message); + } + }, + handleICCInfoChange: function handleICCInfoChange(message) { let oldIcc = this.rilContext.icc; this.rilContext.icc = message; @@ -1418,7 +1430,7 @@ RadioInterfaceLayer.prototype = { handleUSSDReceived: function handleUSSDReceived(ussd) { debug("handleUSSDReceived " + JSON.stringify(ussd)); - this._sendMobileConnectionMessage("RIL:UssdReceived", ussd); + this._sendMobileConnectionMessage("RIL:USSDReceived", ussd); }, handleSendMMI: function handleSendMMI(message) { @@ -1472,6 +1484,12 @@ RadioInterfaceLayer.prototype = { ppmm = null; Services.obs.removeObserver(this, "xpcom-shutdown"); Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic); + Services.obs.removeObserver(this, kSysClockChangeObserverTopic); + break; + case kSysClockChangeObserverTopic: + if (this._lastNitzMessage) { + this._lastNitzMessage.receiveTimeInMS += parseInt(data, 10); + } break; } }, @@ -1504,6 +1522,10 @@ RadioInterfaceLayer.prototype = { // 'time.nitz.automatic-update.enabled' setting from the UI. _nitzAutomaticUpdateEnabled: 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, + // nsISettingsServiceCallback handle: function handle(aName, aResult) { switch(aName) { @@ -1559,6 +1581,11 @@ RadioInterfaceLayer.prototype = { break; case kTimeNitzAutomaticUpdateEnabled: this._nitzAutomaticUpdateEnabled = aResult; + + // Set the latest cached NITZ time if the setting is enabled. + if (this._nitzAutomaticUpdateEnabled && this._lastNitzMessage) { + this.setNitzTime(this._lastNitzMessage); + } break; }; }, diff --git a/dom/time/DateCacheCleaner.cpp b/dom/time/DateCacheCleaner.cpp index ccba359aa6f..fbdae8d18de 100644 --- a/dom/time/DateCacheCleaner.cpp +++ b/dom/time/DateCacheCleaner.cpp @@ -16,24 +16,20 @@ namespace mozilla { namespace dom { namespace time { -class DateCacheCleaner : public SystemTimeChangeObserver +class DateCacheCleaner : public SystemTimezoneChangeObserver { public: DateCacheCleaner() { - RegisterSystemTimeChangeObserver(this); + RegisterSystemTimezoneChangeObserver(this); } ~DateCacheCleaner() { - UnregisterSystemTimeChangeObserver(this); + UnregisterSystemTimezoneChangeObserver(this); } - void Notify(const SystemTimeChange& aReason) + void Notify(const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) { - if (aReason == SYS_TIME_CHANGE_CLOCK) { - return; - } - nsCOMPtr stack = do_GetService("@mozilla.org/js/xpc/ContextStack;1"); if (!stack) { diff --git a/dom/time/TimeChangeObserver.cpp b/dom/time/TimeChangeObserver.cpp index 27e2478da17..453dc86854e 100644 --- a/dom/time/TimeChangeObserver.cpp +++ b/dom/time/TimeChangeObserver.cpp @@ -9,9 +9,11 @@ #include "nsPIDOMWindow.h" #include "nsDOMEvent.h" #include "nsContentUtils.h" +#include "nsIObserverService.h" -using namespace mozilla::hal; using namespace mozilla; +using namespace mozilla::hal; +using namespace mozilla::services; StaticAutoPtr sObserver; @@ -27,11 +29,12 @@ nsSystemTimeChangeObserver* nsSystemTimeChangeObserver::GetInstance() nsSystemTimeChangeObserver::~nsSystemTimeChangeObserver() { mWindowListeners.Clear(); - UnregisterSystemTimeChangeObserver(this); + UnregisterSystemClockChangeObserver(this); + UnregisterSystemTimezoneChangeObserver(this); } void -nsSystemTimeChangeObserver::Notify(const SystemTimeChange& aReason) +nsSystemTimeChangeObserver::FireMozTimeChangeEvent() { //Copy mWindowListeners and iterate over windowListeners instead because //mWindowListeners may be modified while we loop. @@ -58,6 +61,28 @@ nsSystemTimeChangeObserver::Notify(const SystemTimeChange& aReason) } } +void +nsSystemTimeChangeObserver::Notify(const int64_t& aClockDeltaMS) +{ + // Notify observers that the system clock has been adjusted. + nsCOMPtr observerService = GetObserverService(); + if (observerService) { + nsString dataStr; + dataStr.AppendFloat(static_cast(aClockDeltaMS)); + observerService->NotifyObservers( + nullptr, "system-clock-change", dataStr.get()); + } + + FireMozTimeChangeEvent(); +} + +void +nsSystemTimeChangeObserver::Notify( + const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) +{ + FireMozTimeChangeEvent(); +} + nsresult nsSystemTimeChangeObserver::AddWindowListener(nsIDOMWindow* aWindow) { @@ -80,7 +105,8 @@ nsSystemTimeChangeObserver::AddWindowListenerImpl(nsIDOMWindow* aWindow) } if (mWindowListeners.Length() == 0) { - RegisterSystemTimeChangeObserver(sObserver); + RegisterSystemClockChangeObserver(sObserver); + RegisterSystemTimezoneChangeObserver(sObserver); } mWindowListeners.AppendElement(windowWeakRef); @@ -103,7 +129,8 @@ nsSystemTimeChangeObserver::RemoveWindowListenerImpl(nsIDOMWindow* aWindow) mWindowListeners.RemoveElement(NS_GetWeakReference(aWindow)); if (mWindowListeners.Length() == 0) { - UnregisterSystemTimeChangeObserver(sObserver); + UnregisterSystemClockChangeObserver(sObserver); + UnregisterSystemTimezoneChangeObserver(sObserver); } return NS_OK; diff --git a/dom/time/TimeChangeObserver.h b/dom/time/TimeChangeObserver.h index b94e2064437..91b6a6bc31f 100644 --- a/dom/time/TimeChangeObserver.h +++ b/dom/time/TimeChangeObserver.h @@ -12,14 +12,23 @@ #include "nsPIDOMWindow.h" #include "nsWeakPtr.h" -typedef mozilla::Observer SystemTimeChangeObserver; +typedef mozilla::Observer SystemClockChangeObserver; +typedef mozilla::Observer SystemTimezoneChangeObserver; -class nsSystemTimeChangeObserver : public SystemTimeChangeObserver +class nsSystemTimeChangeObserver : public SystemClockChangeObserver, + public SystemTimezoneChangeObserver { public: static nsSystemTimeChangeObserver* GetInstance(); virtual ~nsSystemTimeChangeObserver(); - void Notify(const mozilla::hal::SystemTimeChange& aReason); + + // Implementing hal::SystemClockChangeObserver::Notify() + void Notify(const int64_t& aClockDeltaMS); + + // Implementing hal::SystemTimezoneChangeObserver::Notify() + void Notify( + const mozilla::hal::SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo); + static nsresult AddWindowListener(nsIDOMWindow* aWindow); static nsresult RemoveWindowListener(nsIDOMWindow* aWindow); private: @@ -27,6 +36,7 @@ private: nsresult RemoveWindowListenerImpl(nsIDOMWindow* aWindow); nsSystemTimeChangeObserver() { }; nsTArray mWindowListeners; + void FireMozTimeChangeEvent(); }; #endif //_mozilla_time_change_observer_h_ diff --git a/dom/wifi/Makefile.in b/dom/wifi/Makefile.in index 0f09dcccaf5..2d0d871c2f9 100644 --- a/dom/wifi/Makefile.in +++ b/dom/wifi/Makefile.in @@ -19,6 +19,8 @@ include $(topsrcdir)/dom/dom-config.mk XPIDLSRCS = \ nsIWifi.idl \ + nsIDOMMozWifiStatusChangeEvent.idl \ + nsIDOMMozWifiConnectionInfoEvent.idl \ $(NULL) EXTRA_COMPONENTS = \ diff --git a/dom/wifi/nsIDOMMozWifiConnectionInfoEvent.idl b/dom/wifi/nsIDOMMozWifiConnectionInfoEvent.idl new file mode 100644 index 00000000000..f92b14b86da --- /dev/null +++ b/dom/wifi/nsIDOMMozWifiConnectionInfoEvent.idl @@ -0,0 +1,55 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsIDOMEvent.idl" + +interface nsIVariant; + +[scriptable, builtinclass, uuid(1717f9d9-5fd8-43d8-a098-55924c6d37de)] +interface nsIDOMMozWifiConnectionInfoEvent : nsIDOMEvent +{ + /** + * Network object with an SSID field. + */ + readonly attribute nsIVariant 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; + + [noscript] void initMozWifiConnectionInfoEvent(in DOMString aType, + in boolean aCanBubble, + in boolean aCancelable, + in nsIVariant aNetwork, + in short signalStrength, + in short relSignalStrength, + in long linkSpeed, + in DOMString ipAddress); +}; + +dictionary MozWifiConnectionInfoEventInit : EventInit +{ + nsIVariant network; + short signalStrength; + short relSignalStrength; + long linkSpeed; + DOMString ipAddress; +}; + diff --git a/dom/wifi/nsIDOMMozWifiStatusChangeEvent.idl b/dom/wifi/nsIDOMMozWifiStatusChangeEvent.idl new file mode 100644 index 00000000000..b7053c0a97d --- /dev/null +++ b/dom/wifi/nsIDOMMozWifiStatusChangeEvent.idl @@ -0,0 +1,35 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.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 "nsIDOMEvent.idl" + +interface nsIVariant; + +[scriptable, builtinclass, uuid(f3ef70b0-b2d3-4eb5-8ea4-008f8d330cd6)] +interface nsIDOMMozWifiStatusChangeEvent : nsIDOMEvent +{ + /** + * Network object with a SSID field describing the network affected by + * this change. This might be null. + */ + readonly attribute nsIVariant network; + + /** + * String describing the current status of the wifi manager. See above for + * the possible values. + */ + readonly attribute DOMString status; + + [noscript] void initMozWifiStatusChangeEvent(in DOMString aType, + in boolean aCanBubble, + in boolean aCancelable, + in nsIVariant aNetwork, + in DOMString aStatus); +}; + +dictionary MozWifiStatusChangeEventInit : EventInit +{ + nsIVariant network; + DOMString status; +}; diff --git a/dom/wifi/nsIWifi.idl b/dom/wifi/nsIWifi.idl index b6dffdb187f..b9082be4563 100644 --- a/dom/wifi/nsIWifi.idl +++ b/dom/wifi/nsIWifi.idl @@ -186,63 +186,3 @@ interface nsIDOMWifiManager : nsISupports attribute nsIDOMEventListener onenabled; attribute nsIDOMEventListener ondisabled; }; - -[scriptable, builtinclass, uuid(f3ef70b0-b2d3-4eb5-8ea4-008f8d330cd6)] -interface nsIDOMMozWifiStatusChangeEvent : nsIDOMEvent -{ - /** - * Network object with a SSID field describing the network affected by - * this change. This might be null. - */ - readonly attribute nsIVariant network; - - /** - * String describing the current status of the wifi manager. See above for - * the possible values. - */ - readonly attribute DOMString status; - - [noscript] void initMozWifiStatusChangeEvent(in DOMString aType, - in boolean aCanBubble, - in boolean aCancelable, - in nsIVariant aNetwork, - in DOMString status); -}; - -[scriptable, builtinclass, uuid(1717f9d9-5fd8-43d8-a098-55924c6d37de)] -interface nsIDOMMozWifiConnectionInfoEvent : nsIDOMEvent -{ - /** - * Network object with an SSID field. - */ - readonly attribute nsIVariant 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; - - [noscript] void initMozWifiConnectionInfoEvent(in DOMString aType, - in boolean aCanBubble, - in boolean aCancelable, - in nsIVariant aNetwork, - in short signalStrength, - in short relSignalStrength, - in long linkSpeed, - in DOMString ipAddress); -}; diff --git a/gfx/2d/DrawTargetCG.cpp b/gfx/2d/DrawTargetCG.cpp index 84c36e649ad..02dcaa12b02 100644 --- a/gfx/2d/DrawTargetCG.cpp +++ b/gfx/2d/DrawTargetCG.cpp @@ -701,9 +701,7 @@ DrawTargetCG::FillGlyphs(ScaledFont *aFont, const GlyphBuffer &aBuffer, const Pa CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform)); - ScaledFontMac* cgFont = static_cast(aFont); - CGContextSetFont(cg, cgFont->mFont); - CGContextSetFontSize(cg, cgFont->mSize); + ScaledFontMac* macFont = static_cast(aFont); //XXX: we should use a stack vector here when we have a class like that std::vector glyphs; @@ -729,14 +727,32 @@ DrawTargetCG::FillGlyphs(ScaledFont *aFont, const GlyphBuffer &aBuffer, const Pa //XXX: CGContextShowGlyphsAtPositions is 10.5+ for older versions use CGContextShowGlyphsWithAdvances if (isGradient(aPattern)) { CGContextSetTextDrawingMode(cg, kCGTextClip); - CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), aBuffer.mNumGlyphs); + if (ScaledFontMac::CTFontDrawGlyphsPtr != nullptr) { + ScaledFontMac::CTFontDrawGlyphsPtr(macFont->mCTFont, &glyphs.front(), + &positions.front(), + aBuffer.mNumGlyphs, cg); + } else { + CGContextSetFont(cg, macFont->mFont); + CGContextSetFontSize(cg, macFont->mSize); + CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), + aBuffer.mNumGlyphs); + } DrawGradient(cg, aPattern); } else { //XXX: with CoreGraphics we can stroke text directly instead of going // through GetPath. It would be nice to add support for using that CGContextSetTextDrawingMode(cg, kCGTextFill); SetFillFromPattern(cg, mColorSpace, aPattern); - CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), aBuffer.mNumGlyphs); + if (ScaledFontMac::CTFontDrawGlyphsPtr != nullptr) { + ScaledFontMac::CTFontDrawGlyphsPtr(macFont->mCTFont, &glyphs.front(), + &positions.front(), + aBuffer.mNumGlyphs, cg); + } else { + CGContextSetFont(cg, macFont->mFont); + CGContextSetFontSize(cg, macFont->mSize); + CGContextShowGlyphsAtPositions(cg, &glyphs.front(), &positions.front(), + aBuffer.mNumGlyphs); + } } fixer.Fix(mCg); diff --git a/gfx/2d/ScaledFontMac.cpp b/gfx/2d/ScaledFontMac.cpp index b65752a2e85..6add2e3a35c 100644 --- a/gfx/2d/ScaledFontMac.cpp +++ b/gfx/2d/ScaledFontMac.cpp @@ -12,6 +12,7 @@ #endif #include "DrawTargetCG.h" #include +#include // prototype for private API extern "C" { @@ -22,15 +23,33 @@ CGPathRef CGFontGetGlyphPath(CGFontRef fontRef, CGAffineTransform *textTransform namespace mozilla { namespace gfx { +ScaledFontMac::CTFontDrawGlyphsFuncT* ScaledFontMac::CTFontDrawGlyphsPtr = nullptr; +bool ScaledFontMac::sSymbolLookupDone = false; + ScaledFontMac::ScaledFontMac(CGFontRef aFont, Float aSize) : ScaledFontBase(aSize) { + if (!sSymbolLookupDone) { + CTFontDrawGlyphsPtr = + (CTFontDrawGlyphsFuncT*)dlsym(RTLD_DEFAULT, "CTFontDrawGlyphs"); + sSymbolLookupDone = true; + } + // XXX: should we be taking a reference mFont = CGFontRetain(aFont); + if (CTFontDrawGlyphsPtr != nullptr) { + // only create mCTFont if we're going to be using the CTFontDrawGlyphs API + mCTFont = CTFontCreateWithGraphicsFont(aFont, aSize, nullptr, nullptr); + } else { + mCTFont = nullptr; + } } ScaledFontMac::~ScaledFontMac() { + if (mCTFont) { + CFRelease(mCTFont); + } CGFontRelease(mFont); } @@ -38,9 +57,13 @@ ScaledFontMac::~ScaledFontMac() SkTypeface* ScaledFontMac::GetSkTypeface() { if (!mTypeface) { - CTFontRef fontFace = CTFontCreateWithGraphicsFont(mFont, mSize, nullptr, nullptr); - mTypeface = SkCreateTypefaceFromCTFont(fontFace); - CFRelease(fontFace); + if (mCTFont) { + mTypeface = SkCreateTypefaceFromCTFont(mCTFont); + } else { + CTFontRef fontFace = CTFontCreateWithGraphicsFont(mFont, mSize, nullptr, nullptr); + mTypeface = SkCreateTypefaceFromCTFont(fontFace); + CFRelease(fontFace); + } } return mTypeface; } diff --git a/gfx/2d/ScaledFontMac.h b/gfx/2d/ScaledFontMac.h index 55bd4d1136d..456919b3855 100644 --- a/gfx/2d/ScaledFontMac.h +++ b/gfx/2d/ScaledFontMac.h @@ -25,9 +25,23 @@ public: virtual SkTypeface* GetSkTypeface(); #endif virtual TemporaryRef GetPathForGlyphs(const GlyphBuffer &aBuffer, const DrawTarget *aTarget); + private: friend class DrawTargetCG; CGFontRef mFont; + CTFontRef mCTFont; // only created if CTFontDrawGlyphs is available, otherwise null + + typedef void (CTFontDrawGlyphsFuncT)(CTFontRef, + const CGGlyph[], const CGPoint[], + size_t, CGContextRef); + + static bool sSymbolLookupDone; + +public: + // function pointer for CTFontDrawGlyphs, if available; + // initialized the first time a ScaledFontMac is created, + // so it will be valid by the time DrawTargetCG wants to use it + static CTFontDrawGlyphsFuncT* CTFontDrawGlyphsPtr; }; } diff --git a/gfx/cairo/README b/gfx/cairo/README index 600e4b66178..ce204912605 100644 --- a/gfx/cairo/README +++ b/gfx/cairo/README @@ -216,6 +216,10 @@ pixman-16-bit-pipeline.patch: 16 bit pipeline for dithering pixman-dither.patch: Add dithering of 16 bit gradients +quartz-support-color-emoji-font.patch: support Apple Color Emoji font in cairo-quartz backend + +use-show-text-glyphs-if-glyph-path-fails.patch: fall back to show_text_glyphs even at huge sizes if scaled_font_glyph_path didn't work + ==== disable printing patch ==== disable-printing.patch: allows us to use NS_PRINTING to disable printing. diff --git a/gfx/cairo/cairo/src/cairo-gstate.c b/gfx/cairo/cairo/src/cairo-gstate.c index c04ac7cbe43..1f672242ad9 100644 --- a/gfx/cairo/cairo/src/cairo-gstate.c +++ b/gfx/cairo/cairo/src/cairo-gstate.c @@ -2007,13 +2007,24 @@ _cairo_gstate_show_text_glyphs (cairo_gstate_t *gstate, transformed_glyphs, num_glyphs, &path); - if (status == CAIRO_STATUS_SUCCESS) { + if (status == CAIRO_STATUS_SUCCESS && !_cairo_path_fixed_fill_is_empty (&path)) { status = _cairo_surface_fill (gstate->target, op, pattern, &path, CAIRO_FILL_RULE_WINDING, gstate->tolerance, gstate->scaled_font->options.antialias, _gstate_get_clip (gstate, &clip)); + } else { + /* if _cairo_scaled_font_glyph_path() failed, maybe the font doesn't support + * returning paths, so try the _cairo_surface_show_text_glyphs() option + */ + status = _cairo_surface_show_text_glyphs (gstate->target, op, pattern, + utf8, utf8_len, + transformed_glyphs, num_glyphs, + transformed_clusters, num_clusters, + cluster_flags, + gstate->scaled_font, + _gstate_get_clip (gstate, &clip)); } _cairo_path_fixed_fini (&path); diff --git a/gfx/cairo/cairo/src/cairo-quartz-font.c b/gfx/cairo/cairo/src/cairo-quartz-font.c index 2c7e017af03..c6b32a6317c 100644 --- a/gfx/cairo/cairo/src/cairo-quartz-font.c +++ b/gfx/cairo/cairo/src/cairo-quartz-font.c @@ -90,6 +90,10 @@ static int (*CGFontGetAscentPtr) (CGFontRef fontRef) = NULL; static int (*CGFontGetDescentPtr) (CGFontRef fontRef) = NULL; static int (*CGFontGetLeadingPtr) (CGFontRef fontRef) = NULL; +/* CTFontCreateWithGraphicsFont is not public until 10.5. */ +typedef const struct __CTFontDescriptor *CTFontDescriptorRef; +static CTFontRef (*CTFontCreateWithGraphicsFontPtr) (CGFontRef, CGFloat, const CGAffineTransform *, CTFontDescriptorRef) = NULL; + static cairo_bool_t _cairo_quartz_font_symbol_lookup_done = FALSE; static cairo_bool_t _cairo_quartz_font_symbols_present = FALSE; @@ -127,6 +131,8 @@ quartz_font_ensure_symbols(void) CGContextGetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextGetAllowsFontSmoothing"); CGContextSetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing"); + CTFontCreateWithGraphicsFontPtr = dlsym(RTLD_DEFAULT, "CTFontCreateWithGraphicsFont"); + if ((CGFontCreateWithFontNamePtr || CGFontCreateWithNamePtr) && CGFontGetGlyphBBoxesPtr && CGFontGetGlyphsForUnicharsPtr && @@ -150,6 +156,7 @@ struct _cairo_quartz_font_face { cairo_font_face_t base; CGFontRef cgFont; + CTFontRef ctFont; }; /* @@ -234,6 +241,10 @@ _cairo_quartz_font_face_destroy (void *abstract_face) { cairo_quartz_font_face_t *font_face = (cairo_quartz_font_face_t*) abstract_face; + if (font_face->ctFont) { + CFRelease (font_face->ctFont); + } + CGFontRelease (font_face->cgFont); } @@ -358,6 +369,12 @@ cairo_quartz_font_face_create_for_cgfont (CGFontRef font) font_face->cgFont = CGFontRetain (font); + if (CTFontCreateWithGraphicsFontPtr) { + font_face->ctFont = CTFontCreateWithGraphicsFontPtr (font, 1.0, NULL, NULL); + } else { + font_face->ctFont = NULL; + } + _cairo_font_face_init (&font_face->base, &_cairo_quartz_font_face_backend); return &font_face->base; @@ -777,6 +794,14 @@ _cairo_quartz_scaled_font_get_cg_font_ref (cairo_scaled_font_t *abstract_font) return ffont->cgFont; } +CTFontRef +_cairo_quartz_scaled_font_get_ct_font_ref (cairo_scaled_font_t *abstract_font) +{ + cairo_quartz_font_face_t *ffont = _cairo_quartz_scaled_to_face(abstract_font); + + return ffont->ctFont; +} + #ifndef __LP64__ /* * compat with old ATSUI backend diff --git a/gfx/cairo/cairo/src/cairo-quartz-private.h b/gfx/cairo/cairo/src/cairo-quartz-private.h index ca4b2170c33..1c8d496afee 100644 --- a/gfx/cairo/cairo/src/cairo-quartz-private.h +++ b/gfx/cairo/cairo/src/cairo-quartz-private.h @@ -50,6 +50,9 @@ typedef CGFloat cairo_quartz_float_t; typedef float cairo_quartz_float_t; #endif +/* define CTFontRef for pre-10.5 SDKs */ +typedef const struct __CTFont *CTFontRef; + typedef struct cairo_quartz_surface { cairo_surface_t base; @@ -104,6 +107,9 @@ _cairo_quartz_create_cgimage (cairo_format_t format, CGFontRef _cairo_quartz_scaled_font_get_cg_font_ref (cairo_scaled_font_t *sfont); +CTFontRef +_cairo_quartz_scaled_font_get_ct_font_ref (cairo_scaled_font_t *sfont); + #else # error Cairo was not compiled with support for the quartz backend diff --git a/gfx/cairo/cairo/src/cairo-quartz-surface.c b/gfx/cairo/cairo/src/cairo-quartz-surface.c index 2576cca3be8..0fa5f177afd 100644 --- a/gfx/cairo/cairo/src/cairo-quartz-surface.c +++ b/gfx/cairo/cairo/src/cairo-quartz-surface.c @@ -135,6 +135,9 @@ static bool (*CGContextGetAllowsFontSmoothingPtr) (CGContextRef) = NULL; static CGPathRef (*CGContextCopyPathPtr) (CGContextRef) = NULL; static CGFloat (*CGContextGetAlphaPtr) (CGContextRef) = NULL; +/* CTFontDrawGlyphs is not available until 10.7 */ +static void (*CTFontDrawGlyphsPtr) (CTFontRef, const CGGlyph[], const CGPoint[], size_t, CGContextRef) = NULL; + static SInt32 _cairo_quartz_osx_version = 0x0; static cairo_bool_t _cairo_quartz_symbol_lookup_done = FALSE; @@ -172,6 +175,8 @@ static void quartz_ensure_symbols(void) CGContextSetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing"); CGContextGetAlphaPtr = dlsym(RTLD_DEFAULT, "CGContextGetAlpha"); + CTFontDrawGlyphsPtr = dlsym(RTLD_DEFAULT, "CTFontDrawGlyphs"); + if (Gestalt(gestaltSystemVersion, &_cairo_quartz_osx_version) != noErr) { // assume 10.5 _cairo_quartz_osx_version = 0x1050; @@ -610,10 +615,13 @@ _cairo_quartz_cairo_matrix_to_quartz (const cairo_matrix_t *src, typedef struct { bool isClipping; CGGlyph *cg_glyphs; - CGSize *cg_advances; + union { + CGSize *cg_advances; + CGPoint *cg_positions; + } u; size_t nglyphs; CGAffineTransform textTransform; - CGFontRef font; + cairo_scaled_font_t *scaled_font; CGPoint origin; } unbounded_show_glyphs_t; @@ -691,12 +699,6 @@ _cairo_quartz_fixup_unbounded_operation (cairo_quartz_surface_t *surface, else CGContextEOFillPath (cgc); } else if (op->op == UNBOUNDED_SHOW_GLYPHS) { - CGContextSetFont (cgc, op->u.show_glyphs.font); - CGContextSetFontSize (cgc, 1.0); - CGContextSetTextMatrix (cgc, CGAffineTransformIdentity); - CGContextTranslateCTM (cgc, op->u.show_glyphs.origin.x, op->u.show_glyphs.origin.y); - CGContextConcatCTM (cgc, op->u.show_glyphs.textTransform); - if (op->u.show_glyphs.isClipping) { /* Note that the comment in show_glyphs about kCGTextClip * and the text transform still applies here; however, the @@ -705,12 +707,25 @@ _cairo_quartz_fixup_unbounded_operation (cairo_quartz_surface_t *surface, CGContextSetTextDrawingMode (cgc, kCGTextClip); CGContextSaveGState (cgc); } + CGContextTranslateCTM (cgc, op->u.show_glyphs.origin.x, op->u.show_glyphs.origin.y); + CGContextConcatCTM (cgc, op->u.show_glyphs.textTransform); + if (CTFontDrawGlyphsPtr) { + CTFontDrawGlyphsPtr (_cairo_quartz_scaled_font_get_ct_font_ref (op->u.show_glyphs.scaled_font), + op->u.show_glyphs.cg_glyphs, + op->u.show_glyphs.u.cg_positions, + op->u.show_glyphs.nglyphs, + cgc); + } else { + CGContextSetFont (cgc, _cairo_quartz_scaled_font_get_cg_font_ref (op->u.show_glyphs.scaled_font)); + CGContextSetFontSize (cgc, 1.0); + CGContextSetTextMatrix (cgc, CGAffineTransformIdentity); - CGContextShowGlyphsWithAdvances (cgc, - op->u.show_glyphs.cg_glyphs, - op->u.show_glyphs.cg_advances, - op->u.show_glyphs.nglyphs); + CGContextShowGlyphsWithAdvances (cgc, + op->u.show_glyphs.cg_glyphs, + op->u.show_glyphs.u.cg_advances, + op->u.show_glyphs.nglyphs); + } if (op->u.show_glyphs.isClipping) { CGContextClearRect (cgc, clipBoxRound); CGContextRestoreGState (cgc); @@ -2689,6 +2704,9 @@ _cairo_quartz_surface_show_glyphs_cg (void *abstract_surface, CGGlyph glyphs_static[STATIC_BUF_SIZE]; CGSize cg_advances_static[STATIC_BUF_SIZE]; CGGlyph *cg_glyphs = &glyphs_static[0]; + /* We'll use the cg_advances array for either advances or positions, + depending which API we're using to actually draw. The types involved + have the same size, so this is safe. */ CGSize *cg_advances = &cg_advances_static[0]; cairo_rectangle_int_t glyph_extents; @@ -2801,31 +2819,52 @@ _cairo_quartz_surface_show_glyphs_cg (void *abstract_surface, CGContextSetTextMatrix (state.context, CGAffineTransformIdentity); - /* Convert our glyph positions to glyph advances. We need n-1 advances, - * since the advance at index 0 is applied after glyph 0. */ - xprev = glyphs[0].x; - yprev = glyphs[0].y; - - cg_glyphs[0] = glyphs[0].index; - - for (i = 1; i < num_glyphs; i++) { - cairo_quartz_float_t xf = glyphs[i].x; - cairo_quartz_float_t yf = glyphs[i].y; - cg_glyphs[i] = glyphs[i].index; - cg_advances[i - 1] = CGSizeApplyAffineTransform(CGSizeMake (xf - xprev, yf - yprev), invTextTransform); - xprev = xf; - yprev = yf; - } - /* Translate to the first glyph's position before drawing */ ctm = CGContextGetCTM (state.context); CGContextTranslateCTM (state.context, glyphs[0].x, glyphs[0].y); CGContextConcatCTM (state.context, textTransform); - CGContextShowGlyphsWithAdvances (state.context, - cg_glyphs, - cg_advances, - num_glyphs); + if (CTFontDrawGlyphsPtr) { + /* If CTFontDrawGlyphs is available (i.e. OS X 10.7 or later), we want to use + * that in preference to CGContextShowGlyphsWithAdvances so that colored-bitmap + * fonts like Apple Color Emoji will render properly. + * For this, we need to convert our glyph positions to Core Graphics's CGPoint. + * We borrow the cg_advances array, as CGPoint and CGSize are the same size. */ + + CGPoint *cg_positions = (CGPoint*) cg_advances; + cairo_quartz_float_t origin_x = glyphs[0].x; + cairo_quartz_float_t origin_y = glyphs[0].y; + + for (i = 0; i < num_glyphs; i++) { + CGPoint pt = CGPointMake (glyphs[i].x - origin_x, glyphs[i].y - origin_y); + cg_positions[i] = CGPointApplyAffineTransform (pt, invTextTransform); + cg_glyphs[i] = glyphs[i].index; + } + + CTFontDrawGlyphsPtr (_cairo_quartz_scaled_font_get_ct_font_ref (scaled_font), + cg_glyphs, cg_positions, num_glyphs, state.context); + } else { + /* Convert our glyph positions to glyph advances. We need n-1 advances, + * since the advance at index 0 is applied after glyph 0. */ + xprev = glyphs[0].x; + yprev = glyphs[0].y; + + cg_glyphs[0] = glyphs[0].index; + + for (i = 1; i < num_glyphs; i++) { + cairo_quartz_float_t xf = glyphs[i].x; + cairo_quartz_float_t yf = glyphs[i].y; + cg_glyphs[i] = glyphs[i].index; + cg_advances[i - 1] = CGSizeApplyAffineTransform(CGSizeMake (xf - xprev, yf - yprev), invTextTransform); + xprev = xf; + yprev = yf; + } + + CGContextShowGlyphsWithAdvances (state.context, + cg_glyphs, + cg_advances, + num_glyphs); + } CGContextSetCTM (state.context, ctm); @@ -2852,10 +2891,17 @@ BAIL: ub.u.show_glyphs.isClipping = isClipping; ub.u.show_glyphs.cg_glyphs = cg_glyphs; - ub.u.show_glyphs.cg_advances = cg_advances; + if (CTFontDrawGlyphsPtr) { + /* we're using Core Text API: the cg_advances array was + reused (above) for glyph positions */ + CGPoint *cg_positions = (CGPoint*) cg_advances; + ub.u.show_glyphs.u.cg_positions = cg_positions; + } else { + ub.u.show_glyphs.u.cg_advances = cg_advances; + } ub.u.show_glyphs.nglyphs = num_glyphs; ub.u.show_glyphs.textTransform = textTransform; - ub.u.show_glyphs.font = cgfref; + ub.u.show_glyphs.scaled_font = scaled_font; ub.u.show_glyphs.origin = CGPointMake (glyphs[0].x, glyphs[0].y); _cairo_quartz_fixup_unbounded_operation (surface, &ub, scaled_font->options.antialias); diff --git a/gfx/cairo/quartz-support-color-emoji-font.patch b/gfx/cairo/quartz-support-color-emoji-font.patch new file mode 100644 index 00000000000..5fb88b27178 --- /dev/null +++ b/gfx/cairo/quartz-support-color-emoji-font.patch @@ -0,0 +1,432 @@ +From: Jonathan Kew +bug 715798 pt 1 - support Apple Color Emoji font in cairo-quartz backend. r=jrmuizel + +diff --git a/gfx/cairo/cairo/src/cairo-quartz-font.c b/gfx/cairo/cairo/src/cairo-quartz-font.c +--- a/gfx/cairo/cairo/src/cairo-quartz-font.c ++++ b/gfx/cairo/cairo/src/cairo-quartz-font.c +@@ -85,16 +85,20 @@ typedef struct { + int descent; + int leading; + } quartz_CGFontMetrics; + static quartz_CGFontMetrics* (*CGFontGetHMetricsPtr) (CGFontRef fontRef) = NULL; + static int (*CGFontGetAscentPtr) (CGFontRef fontRef) = NULL; + static int (*CGFontGetDescentPtr) (CGFontRef fontRef) = NULL; + static int (*CGFontGetLeadingPtr) (CGFontRef fontRef) = NULL; + ++/* CTFontCreateWithGraphicsFont is not public until 10.5. */ ++typedef const struct __CTFontDescriptor *CTFontDescriptorRef; ++static CTFontRef (*CTFontCreateWithGraphicsFontPtr) (CGFontRef, CGFloat, const CGAffineTransform *, CTFontDescriptorRef) = NULL; ++ + static cairo_bool_t _cairo_quartz_font_symbol_lookup_done = FALSE; + static cairo_bool_t _cairo_quartz_font_symbols_present = FALSE; + + static void + quartz_font_ensure_symbols(void) + { + if (_cairo_quartz_font_symbol_lookup_done) + return; +@@ -122,16 +126,18 @@ quartz_font_ensure_symbols(void) + CGFontGetHMetricsPtr = dlsym(RTLD_DEFAULT, "CGFontGetHMetrics"); + CGFontGetAscentPtr = dlsym(RTLD_DEFAULT, "CGFontGetAscent"); + CGFontGetDescentPtr = dlsym(RTLD_DEFAULT, "CGFontGetDescent"); + CGFontGetLeadingPtr = dlsym(RTLD_DEFAULT, "CGFontGetLeading"); + + CGContextGetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextGetAllowsFontSmoothing"); + CGContextSetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing"); + ++ CTFontCreateWithGraphicsFontPtr = dlsym(RTLD_DEFAULT, "CTFontCreateWithGraphicsFont"); ++ + if ((CGFontCreateWithFontNamePtr || CGFontCreateWithNamePtr) && + CGFontGetGlyphBBoxesPtr && + CGFontGetGlyphsForUnicharsPtr && + CGFontGetUnitsPerEmPtr && + CGFontGetGlyphAdvancesPtr && + CGFontGetGlyphPathPtr && + (CGFontGetHMetricsPtr || (CGFontGetAscentPtr && CGFontGetDescentPtr && CGFontGetLeadingPtr))) + _cairo_quartz_font_symbols_present = TRUE; +@@ -145,16 +151,17 @@ typedef struct _cairo_quartz_scaled_font + struct _cairo_quartz_scaled_font { + cairo_scaled_font_t base; + }; + + struct _cairo_quartz_font_face { + cairo_font_face_t base; + + CGFontRef cgFont; ++ CTFontRef ctFont; + }; + + /* + * font face backend + */ + + static cairo_status_t + _cairo_quartz_font_face_create_for_toy (cairo_toy_font_face_t *toy_face, +@@ -229,16 +236,20 @@ static cairo_status_t + return CAIRO_STATUS_SUCCESS; + } + + static void + _cairo_quartz_font_face_destroy (void *abstract_face) + { + cairo_quartz_font_face_t *font_face = (cairo_quartz_font_face_t*) abstract_face; + ++ if (font_face->ctFont) { ++ CFRelease (font_face->ctFont); ++ } ++ + CGFontRelease (font_face->cgFont); + } + + static const cairo_scaled_font_backend_t _cairo_quartz_scaled_font_backend; + + static cairo_status_t + _cairo_quartz_font_face_scaled_font_create (void *abstract_face, + const cairo_matrix_t *font_matrix, +@@ -353,16 +364,22 @@ cairo_quartz_font_face_create_for_cgfont + if (!font_face) { + cairo_status_t ignore_status; + ignore_status = _cairo_error (CAIRO_STATUS_NO_MEMORY); + return (cairo_font_face_t *)&_cairo_font_face_nil; + } + + font_face->cgFont = CGFontRetain (font); + ++ if (CTFontCreateWithGraphicsFontPtr) { ++ font_face->ctFont = CTFontCreateWithGraphicsFontPtr (font, 1.0, NULL, NULL); ++ } else { ++ font_face->ctFont = NULL; ++ } ++ + _cairo_font_face_init (&font_face->base, &_cairo_quartz_font_face_backend); + + return &font_face->base; + } + + /* + * scaled font backend + */ +@@ -772,16 +789,24 @@ static const cairo_scaled_font_backend_t + CGFontRef + _cairo_quartz_scaled_font_get_cg_font_ref (cairo_scaled_font_t *abstract_font) + { + cairo_quartz_font_face_t *ffont = _cairo_quartz_scaled_to_face(abstract_font); + + return ffont->cgFont; + } + ++CTFontRef ++_cairo_quartz_scaled_font_get_ct_font_ref (cairo_scaled_font_t *abstract_font) ++{ ++ cairo_quartz_font_face_t *ffont = _cairo_quartz_scaled_to_face(abstract_font); ++ ++ return ffont->ctFont; ++} ++ + #ifndef __LP64__ + /* + * compat with old ATSUI backend + */ + + /** + * cairo_quartz_font_face_create_for_atsu_font_id + * @font_id: an ATSUFontID for the font. +diff --git a/gfx/cairo/cairo/src/cairo-quartz-private.h b/gfx/cairo/cairo/src/cairo-quartz-private.h +--- a/gfx/cairo/cairo/src/cairo-quartz-private.h ++++ b/gfx/cairo/cairo/src/cairo-quartz-private.h +@@ -45,16 +45,19 @@ + #include "cairo-surface-clipper-private.h" + + #ifdef CGFLOAT_DEFINED + typedef CGFloat cairo_quartz_float_t; + #else + typedef float cairo_quartz_float_t; + #endif + ++/* define CTFontRef for pre-10.5 SDKs */ ++typedef const struct __CTFont *CTFontRef; ++ + typedef struct cairo_quartz_surface { + cairo_surface_t base; + + CGContextRef cgContext; + CGAffineTransform cgContextBaseCTM; + + void *imageData; + cairo_surface_t *imageSurfaceEquiv; +@@ -99,15 +102,18 @@ CGImageRef + cairo_bool_t interpolate, + CGColorSpaceRef colorSpaceOverride, + CGDataProviderReleaseDataCallback releaseCallback, + void *releaseInfo); + + CGFontRef + _cairo_quartz_scaled_font_get_cg_font_ref (cairo_scaled_font_t *sfont); + ++CTFontRef ++_cairo_quartz_scaled_font_get_ct_font_ref (cairo_scaled_font_t *sfont); ++ + #else + + # error Cairo was not compiled with support for the quartz backend + + #endif /* CAIRO_HAS_QUARTZ_SURFACE */ + + #endif /* CAIRO_QUARTZ_PRIVATE_H */ +diff --git a/gfx/cairo/cairo/src/cairo-quartz-surface.c b/gfx/cairo/cairo/src/cairo-quartz-surface.c +--- a/gfx/cairo/cairo/src/cairo-quartz-surface.c ++++ b/gfx/cairo/cairo/src/cairo-quartz-surface.c +@@ -130,16 +130,19 @@ static void (*CGContextClipToMaskPtr) (C + static void (*CGContextDrawTiledImagePtr) (CGContextRef, CGRect, CGImageRef) = NULL; + static unsigned int (*CGContextGetTypePtr) (CGContextRef) = NULL; + static void (*CGContextSetShouldAntialiasFontsPtr) (CGContextRef, bool) = NULL; + static void (*CGContextSetAllowsFontSmoothingPtr) (CGContextRef, bool) = NULL; + static bool (*CGContextGetAllowsFontSmoothingPtr) (CGContextRef) = NULL; + static CGPathRef (*CGContextCopyPathPtr) (CGContextRef) = NULL; + static CGFloat (*CGContextGetAlphaPtr) (CGContextRef) = NULL; + ++/* CTFontDrawGlyphs is not available until 10.7 */ ++static void (*CTFontDrawGlyphsPtr) (CTFontRef, const CGGlyph[], const CGPoint[], size_t, CGContextRef) = NULL; ++ + static SInt32 _cairo_quartz_osx_version = 0x0; + + static cairo_bool_t _cairo_quartz_symbol_lookup_done = FALSE; + + /* + * Utility functions + */ + +@@ -167,16 +170,18 @@ static void quartz_ensure_symbols(void) + CGContextDrawTiledImagePtr = dlsym(RTLD_DEFAULT, "CGContextDrawTiledImage"); + CGContextGetTypePtr = dlsym(RTLD_DEFAULT, "CGContextGetType"); + CGContextSetShouldAntialiasFontsPtr = dlsym(RTLD_DEFAULT, "CGContextSetShouldAntialiasFonts"); + CGContextCopyPathPtr = dlsym(RTLD_DEFAULT, "CGContextCopyPath"); + CGContextGetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextGetAllowsFontSmoothing"); + CGContextSetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing"); + CGContextGetAlphaPtr = dlsym(RTLD_DEFAULT, "CGContextGetAlpha"); + ++ CTFontDrawGlyphsPtr = dlsym(RTLD_DEFAULT, "CTFontDrawGlyphs"); ++ + if (Gestalt(gestaltSystemVersion, &_cairo_quartz_osx_version) != noErr) { + // assume 10.5 + _cairo_quartz_osx_version = 0x1050; + } + + _cairo_quartz_symbol_lookup_done = TRUE; + } + +@@ -605,20 +610,23 @@ static inline void + dst->d = src->yy; + dst->tx = src->x0; + dst->ty = src->y0; + } + + typedef struct { + bool isClipping; + CGGlyph *cg_glyphs; +- CGSize *cg_advances; ++ union { ++ CGSize *cg_advances; ++ CGPoint *cg_positions; ++ } u; + size_t nglyphs; + CGAffineTransform textTransform; +- CGFontRef font; ++ cairo_scaled_font_t *scaled_font; + CGPoint origin; + } unbounded_show_glyphs_t; + + typedef struct { + CGPathRef cgPath; + cairo_fill_rule_t fill_rule; + } unbounded_stroke_fill_t; + +@@ -686,36 +694,43 @@ static void + CGContextBeginPath (cgc); + CGContextAddPath (cgc, op->u.stroke_fill.cgPath); + + if (op->u.stroke_fill.fill_rule == CAIRO_FILL_RULE_WINDING) + CGContextFillPath (cgc); + else + CGContextEOFillPath (cgc); + } else if (op->op == UNBOUNDED_SHOW_GLYPHS) { +- CGContextSetFont (cgc, op->u.show_glyphs.font); +- CGContextSetFontSize (cgc, 1.0); +- CGContextSetTextMatrix (cgc, CGAffineTransformIdentity); +- CGContextTranslateCTM (cgc, op->u.show_glyphs.origin.x, op->u.show_glyphs.origin.y); +- CGContextConcatCTM (cgc, op->u.show_glyphs.textTransform); +- + if (op->u.show_glyphs.isClipping) { + /* Note that the comment in show_glyphs about kCGTextClip + * and the text transform still applies here; however, the + * cg_advances we have were already transformed, so we + * don't have to do anything. */ + CGContextSetTextDrawingMode (cgc, kCGTextClip); + CGContextSaveGState (cgc); + } +- +- CGContextShowGlyphsWithAdvances (cgc, +- op->u.show_glyphs.cg_glyphs, +- op->u.show_glyphs.cg_advances, +- op->u.show_glyphs.nglyphs); +- ++ CGContextTranslateCTM (cgc, op->u.show_glyphs.origin.x, op->u.show_glyphs.origin.y); ++ CGContextConcatCTM (cgc, op->u.show_glyphs.textTransform); ++ if (CTFontDrawGlyphsPtr) { ++ CTFontDrawGlyphsPtr (_cairo_quartz_scaled_font_get_ct_font_ref (op->u.show_glyphs.scaled_font), ++ op->u.show_glyphs.cg_glyphs, ++ op->u.show_glyphs.u.cg_positions, ++ op->u.show_glyphs.nglyphs, ++ cgc); ++ } else { ++ CGContextSetFont (cgc, _cairo_quartz_scaled_font_get_cg_font_ref (op->u.show_glyphs.scaled_font)); ++ CGContextSetFontSize (cgc, 1.0); ++ CGContextSetTextMatrix (cgc, CGAffineTransformIdentity); ++ ++ CGContextShowGlyphsWithAdvances (cgc, ++ op->u.show_glyphs.cg_glyphs, ++ op->u.show_glyphs.u.cg_advances, ++ op->u.show_glyphs.nglyphs); ++ ++ } + if (op->u.show_glyphs.isClipping) { + CGContextClearRect (cgc, clipBoxRound); + CGContextRestoreGState (cgc); + } + } else if (op->op == UNBOUNDED_MASK) { + CGAffineTransform ctm = CGContextGetCTM (cgc); + CGContextSaveGState (cgc); + CGContextConcatCTM (cgc, op->u.mask.maskTransform); +@@ -2684,16 +2699,19 @@ static cairo_int_status_t + cairo_clip_t *clip, + int *remaining_glyphs) + { + CGAffineTransform textTransform, ctm, invTextTransform; + #define STATIC_BUF_SIZE 64 + CGGlyph glyphs_static[STATIC_BUF_SIZE]; + CGSize cg_advances_static[STATIC_BUF_SIZE]; + CGGlyph *cg_glyphs = &glyphs_static[0]; ++ /* We'll use the cg_advances array for either advances or positions, ++ depending which API we're using to actually draw. The types involved ++ have the same size, so this is safe. */ + CGSize *cg_advances = &cg_advances_static[0]; + + cairo_rectangle_int_t glyph_extents; + cairo_quartz_surface_t *surface = (cairo_quartz_surface_t *) abstract_surface; + cairo_int_status_t rv = CAIRO_STATUS_SUCCESS; + cairo_quartz_drawing_state_t state; + cairo_quartz_float_t xprev, yprev; + int i; +@@ -2796,41 +2814,62 @@ static cairo_int_status_t + invTextTransform = CGAffineTransformMake (scaled_font->scale_inverse.xx, + -scaled_font->scale_inverse.yx, + scaled_font->scale_inverse.xy, + -scaled_font->scale_inverse.yy, + 0.0, 0.0); + + CGContextSetTextMatrix (state.context, CGAffineTransformIdentity); + +- /* Convert our glyph positions to glyph advances. We need n-1 advances, +- * since the advance at index 0 is applied after glyph 0. */ +- xprev = glyphs[0].x; +- yprev = glyphs[0].y; +- +- cg_glyphs[0] = glyphs[0].index; +- +- for (i = 1; i < num_glyphs; i++) { +- cairo_quartz_float_t xf = glyphs[i].x; +- cairo_quartz_float_t yf = glyphs[i].y; +- cg_glyphs[i] = glyphs[i].index; +- cg_advances[i - 1] = CGSizeApplyAffineTransform(CGSizeMake (xf - xprev, yf - yprev), invTextTransform); +- xprev = xf; +- yprev = yf; +- } +- + /* Translate to the first glyph's position before drawing */ + ctm = CGContextGetCTM (state.context); + CGContextTranslateCTM (state.context, glyphs[0].x, glyphs[0].y); + CGContextConcatCTM (state.context, textTransform); + +- CGContextShowGlyphsWithAdvances (state.context, +- cg_glyphs, +- cg_advances, +- num_glyphs); ++ if (CTFontDrawGlyphsPtr) { ++ /* If CTFontDrawGlyphs is available (i.e. OS X 10.7 or later), we want to use ++ * that in preference to CGContextShowGlyphsWithAdvances so that colored-bitmap ++ * fonts like Apple Color Emoji will render properly. ++ * For this, we need to convert our glyph positions to Core Graphics's CGPoint. ++ * We borrow the cg_advances array, as CGPoint and CGSize are the same size. */ ++ ++ CGPoint *cg_positions = (CGPoint*) cg_advances; ++ cairo_quartz_float_t origin_x = glyphs[0].x; ++ cairo_quartz_float_t origin_y = glyphs[0].y; ++ ++ for (i = 0; i < num_glyphs; i++) { ++ CGPoint pt = CGPointMake (glyphs[i].x - origin_x, glyphs[i].y - origin_y); ++ cg_positions[i] = CGPointApplyAffineTransform (pt, invTextTransform); ++ cg_glyphs[i] = glyphs[i].index; ++ } ++ ++ CTFontDrawGlyphsPtr (_cairo_quartz_scaled_font_get_ct_font_ref (scaled_font), ++ cg_glyphs, cg_positions, num_glyphs, state.context); ++ } else { ++ /* Convert our glyph positions to glyph advances. We need n-1 advances, ++ * since the advance at index 0 is applied after glyph 0. */ ++ xprev = glyphs[0].x; ++ yprev = glyphs[0].y; ++ ++ cg_glyphs[0] = glyphs[0].index; ++ ++ for (i = 1; i < num_glyphs; i++) { ++ cairo_quartz_float_t xf = glyphs[i].x; ++ cairo_quartz_float_t yf = glyphs[i].y; ++ cg_glyphs[i] = glyphs[i].index; ++ cg_advances[i - 1] = CGSizeApplyAffineTransform(CGSizeMake (xf - xprev, yf - yprev), invTextTransform); ++ xprev = xf; ++ yprev = yf; ++ } ++ ++ CGContextShowGlyphsWithAdvances (state.context, ++ cg_glyphs, ++ cg_advances, ++ num_glyphs); ++ } + + CGContextSetCTM (state.context, ctm); + + if (state.action == DO_IMAGE || state.action == DO_TILED_IMAGE || + state.action == DO_LAYER) { + _cairo_quartz_draw_image (&state, op); + } else if (state.action == DO_SHADING) { + CGContextConcatCTM (state.context, state.transform); +@@ -2847,20 +2886,27 @@ BAIL: + cgfref && + !_cairo_operator_bounded_by_mask (op)) + { + unbounded_op_data_t ub; + ub.op = UNBOUNDED_SHOW_GLYPHS; + + ub.u.show_glyphs.isClipping = isClipping; + ub.u.show_glyphs.cg_glyphs = cg_glyphs; +- ub.u.show_glyphs.cg_advances = cg_advances; ++ if (CTFontDrawGlyphsPtr) { ++ /* we're using Core Text API: the cg_advances array was ++ reused (above) for glyph positions */ ++ CGPoint *cg_positions = (CGPoint*) cg_advances; ++ ub.u.show_glyphs.u.cg_positions = cg_positions; ++ } else { ++ ub.u.show_glyphs.u.cg_advances = cg_advances; ++ } + ub.u.show_glyphs.nglyphs = num_glyphs; + ub.u.show_glyphs.textTransform = textTransform; +- ub.u.show_glyphs.font = cgfref; ++ ub.u.show_glyphs.scaled_font = scaled_font; + ub.u.show_glyphs.origin = CGPointMake (glyphs[0].x, glyphs[0].y); + + _cairo_quartz_fixup_unbounded_operation (surface, &ub, scaled_font->options.antialias); + } + + + if (cg_advances != &cg_advances_static[0]) { + free (cg_advances); diff --git a/gfx/cairo/use-show-text-glyphs-if-glyph-path-fails.patch b/gfx/cairo/use-show-text-glyphs-if-glyph-path-fails.patch new file mode 100644 index 00000000000..1670eaf7389 --- /dev/null +++ b/gfx/cairo/use-show-text-glyphs-if-glyph-path-fails.patch @@ -0,0 +1,42 @@ +From: Jonathan Kew +bug 715798 pt 2 - fall back to show_text_glyphs even at huge sizes if scaled_font_glyph_path didn't work. r=jrmuizel + +diff --git a/gfx/cairo/cairo/src/cairo-gstate.c b/gfx/cairo/cairo/src/cairo-gstate.c +--- a/gfx/cairo/cairo/src/cairo-gstate.c ++++ b/gfx/cairo/cairo/src/cairo-gstate.c +@@ -2002,23 +2002,34 @@ cairo_status_t + cairo_path_fixed_t path; + + _cairo_path_fixed_init (&path); + + status = _cairo_scaled_font_glyph_path (gstate->scaled_font, + transformed_glyphs, num_glyphs, + &path); + +- if (status == CAIRO_STATUS_SUCCESS) { ++ if (status == CAIRO_STATUS_SUCCESS && !_cairo_path_fixed_fill_is_empty (&path)) { + status = _cairo_surface_fill (gstate->target, op, pattern, + &path, + CAIRO_FILL_RULE_WINDING, + gstate->tolerance, + gstate->scaled_font->options.antialias, + _gstate_get_clip (gstate, &clip)); ++ } else { ++ /* if _cairo_scaled_font_glyph_path() failed, maybe the font doesn't support ++ * returning paths, so try the _cairo_surface_show_text_glyphs() option ++ */ ++ status = _cairo_surface_show_text_glyphs (gstate->target, op, pattern, ++ utf8, utf8_len, ++ transformed_glyphs, num_glyphs, ++ transformed_clusters, num_clusters, ++ cluster_flags, ++ gstate->scaled_font, ++ _gstate_get_clip (gstate, &clip)); + } + + _cairo_path_fixed_fini (&path); + } + + _cairo_clip_fini (&clip); + + CLEANUP_GLYPHS: diff --git a/gfx/layers/basic/BasicTiledThebesLayer.cpp b/gfx/layers/basic/BasicTiledThebesLayer.cpp index 3f4965ccc42..98ecfcbc49e 100644 --- a/gfx/layers/basic/BasicTiledThebesLayer.cpp +++ b/gfx/layers/basic/BasicTiledThebesLayer.cpp @@ -410,7 +410,10 @@ BasicTiledThebesLayer::PaintThebes(gfxContext* aContext, transform.Invert(); // Store the old valid region, then clear it before painting. + // We clip the old valid region to the visible region, as it only gets + // used to decide stale content (currently valid and previously visible) nsIntRegion oldValidRegion = mTiledBuffer.GetValidRegion(); + oldValidRegion.And(oldValidRegion, mVisibleRegion); mTiledBuffer.ClearPaintedRegion(); // Make sure that tiles that fall outside of the visible region are @@ -453,8 +456,14 @@ BasicTiledThebesLayer::PaintThebes(gfxContext* aContext, // Keep track of what we're about to refresh. mValidRegion.Or(mValidRegion, regionToPaint); + // mValidRegion would have been altered by InvalidateRegion, but we still + // want to display stale content until it gets progressively updated. + // Create a region that includes stale content. + nsIntRegion validOrStale; + validOrStale.Or(mValidRegion, oldValidRegion); + // Paint the computed region and subtract it from the invalid region. - mTiledBuffer.PaintThebes(this, mValidRegion, regionToPaint, aCallback, aCallbackData); + mTiledBuffer.PaintThebes(this, validOrStale, regionToPaint, aCallback, aCallbackData); invalidRegion.Sub(invalidRegion, regionToPaint); } while (repeat); } else { diff --git a/gfx/src/nsCoord.h b/gfx/src/nsCoord.h index e14286cc60a..3eb1da0c120 100644 --- a/gfx/src/nsCoord.h +++ b/gfx/src/nsCoord.h @@ -444,22 +444,6 @@ inline nscoord NSIntPixelsToAppUnits(int32_t aPixels, int32_t aAppUnitsPerPixel) { // The cast to nscoord makes sure we don't overflow if we ever change // nscoord to float -#ifndef NS_COORD_IS_FLOAT - const int pixels_MAX = nscoord_MAX / aAppUnitsPerPixel; - // Bounds-check before converting out of float, to avoid overflow - NS_WARN_IF_FALSE(aPixels <= pixels_MAX, - "Overflowed nscoord_MAX in conversion to nscoord"); - if (aPixels >= pixels_MAX) { - aPixels = pixels_MAX; - } else { - const int pixels_MIN = nscoord_MIN / aAppUnitsPerPixel; - NS_WARN_IF_FALSE(aPixels >= pixels_MIN, - "Overflowed nscoord_MIN in conversion to nscoord"); - if (aPixels <= pixels_MIN) { - aPixels = pixels_MIN; - } - } -#endif nscoord r = aPixels * (nscoord)aAppUnitsPerPixel; VERIFY_COORD(r); return r; diff --git a/hal/Hal.cpp b/hal/Hal.cpp index e08206a9db7..e52104fe5f0 100644 --- a/hal/Hal.cpp +++ b/hal/Hal.cpp @@ -405,52 +405,86 @@ void SetScreenBrightness(double brightness) PROXY_IF_SANDBOXED(SetScreenBrightness(clamped(brightness, 0.0, 1.0))); } -bool SetLight(LightType light, const hal::LightConfiguration& aConfig) +bool SetLight(LightType light, const LightConfiguration& aConfig) { AssertMainThread(); RETURN_PROXY_IF_SANDBOXED(SetLight(light, aConfig), false); } -bool GetLight(LightType light, hal::LightConfiguration* aConfig) +bool GetLight(LightType light, LightConfiguration* aConfig) { AssertMainThread(); RETURN_PROXY_IF_SANDBOXED(GetLight(light, aConfig), false); } -class SystemTimeObserversManager : public ObserversManager +class SystemClockChangeObserversManager : public ObserversManager { protected: void EnableNotifications() { - PROXY_IF_SANDBOXED(EnableSystemTimeChangeNotifications()); + PROXY_IF_SANDBOXED(EnableSystemClockChangeNotifications()); } void DisableNotifications() { - PROXY_IF_SANDBOXED(DisableSystemTimeChangeNotifications()); + PROXY_IF_SANDBOXED(DisableSystemClockChangeNotifications()); } }; -static SystemTimeObserversManager sSystemTimeObservers; +static SystemClockChangeObserversManager sSystemClockChangeObservers; void -RegisterSystemTimeChangeObserver(SystemTimeObserver *aObserver) +RegisterSystemClockChangeObserver(SystemClockChangeObserver* aObserver) { AssertMainThread(); - sSystemTimeObservers.AddObserver(aObserver); + sSystemClockChangeObservers.AddObserver(aObserver); } void -UnregisterSystemTimeChangeObserver(SystemTimeObserver *aObserver) +UnregisterSystemClockChangeObserver(SystemClockChangeObserver* aObserver) { AssertMainThread(); - sSystemTimeObservers.RemoveObserver(aObserver); + sSystemClockChangeObservers.RemoveObserver(aObserver); } void -NotifySystemTimeChange(const hal::SystemTimeChange& aReason) +NotifySystemClockChange(const int64_t& aClockDeltaMS) { - sSystemTimeObservers.BroadcastInformation(aReason); + sSystemClockChangeObservers.BroadcastInformation(aClockDeltaMS); } - + +class SystemTimezoneChangeObserversManager : public ObserversManager +{ +protected: + void EnableNotifications() { + PROXY_IF_SANDBOXED(EnableSystemTimezoneChangeNotifications()); + } + + void DisableNotifications() { + PROXY_IF_SANDBOXED(DisableSystemTimezoneChangeNotifications()); + } +}; + +static SystemTimezoneChangeObserversManager sSystemTimezoneChangeObservers; + +void +RegisterSystemTimezoneChangeObserver(SystemTimezoneChangeObserver* aObserver) +{ + AssertMainThread(); + sSystemTimezoneChangeObservers.AddObserver(aObserver); +} + +void +UnregisterSystemTimezoneChangeObserver(SystemTimezoneChangeObserver* aObserver) +{ + AssertMainThread(); + sSystemTimezoneChangeObservers.RemoveObserver(aObserver); +} + +void +NotifySystemTimezoneChange(const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) +{ + sSystemTimezoneChangeObservers.BroadcastInformation(aSystemTimezoneChangeInfo); +} + void AdjustSystemClock(int64_t aDeltaMilliseconds) { @@ -607,8 +641,8 @@ UnregisterWakeLockObserver(WakeLockObserver* aObserver) void ModifyWakeLock(const nsAString &aTopic, - hal::WakeLockControl aLockAdjust, - hal::WakeLockControl aHiddenAdjust) + WakeLockControl aLockAdjust, + WakeLockControl aHiddenAdjust) { AssertMainThread(); PROXY_IF_SANDBOXED(ModifyWakeLock(aTopic, aLockAdjust, aHiddenAdjust)); @@ -671,18 +705,18 @@ UnlockScreenOrientation() } void -EnableSwitchNotifications(hal::SwitchDevice aDevice) { +EnableSwitchNotifications(SwitchDevice aDevice) { AssertMainThread(); PROXY_IF_SANDBOXED(EnableSwitchNotifications(aDevice)); } void -DisableSwitchNotifications(hal::SwitchDevice aDevice) { +DisableSwitchNotifications(SwitchDevice aDevice) { AssertMainThread(); PROXY_IF_SANDBOXED(DisableSwitchNotifications(aDevice)); } -hal::SwitchState GetCurrentSwitchState(hal::SwitchDevice aDevice) +SwitchState GetCurrentSwitchState(SwitchDevice aDevice) { AssertMainThread(); RETURN_PROXY_IF_SANDBOXED(GetCurrentSwitchState(aDevice), SWITCH_STATE_UNKNOWN); @@ -693,7 +727,7 @@ typedef mozilla::ObserverList SwitchObserverList; static SwitchObserverList *sSwitchObserverLists = NULL; static SwitchObserverList& -GetSwitchObserverList(hal::SwitchDevice aDevice) { +GetSwitchObserverList(SwitchDevice aDevice) { MOZ_ASSERT(0 <= aDevice && aDevice < NUM_SWITCH_DEVICE); if (sSwitchObserverLists == NULL) { sSwitchObserverLists = new SwitchObserverList[NUM_SWITCH_DEVICE]; @@ -714,7 +748,7 @@ ReleaseObserversIfNeeded() { } void -RegisterSwitchObserver(hal::SwitchDevice aDevice, hal::SwitchObserver *aObserver) +RegisterSwitchObserver(SwitchDevice aDevice, SwitchObserver *aObserver) { AssertMainThread(); SwitchObserverList& observer = GetSwitchObserverList(aDevice); @@ -725,7 +759,7 @@ RegisterSwitchObserver(hal::SwitchDevice aDevice, hal::SwitchObserver *aObserver } void -UnregisterSwitchObserver(hal::SwitchDevice aDevice, hal::SwitchObserver *aObserver) +UnregisterSwitchObserver(SwitchDevice aDevice, SwitchObserver *aObserver) { AssertMainThread(); @@ -743,7 +777,7 @@ UnregisterSwitchObserver(hal::SwitchDevice aDevice, hal::SwitchObserver *aObserv } void -NotifySwitchChange(const hal::SwitchEvent& aEvent) +NotifySwitchChange(const SwitchEvent& aEvent) { // When callback this notification, main thread may call unregister function // first. We should check if this pointer is valid. diff --git a/hal/Hal.h b/hal/Hal.h index 2dd7ca7286b..103ee5b9411 100644 --- a/hal/Hal.h +++ b/hal/Hal.h @@ -50,7 +50,8 @@ class WindowIdentifier; extern PRLogModuleInfo *sHalLog; #define HAL_LOG(msg) PR_LOG(mozilla::hal::sHalLog, PR_LOG_DEBUG, msg) -typedef Observer SystemTimeObserver; +typedef Observer SystemClockChangeObserver; +typedef Observer SystemTimezoneChangeObserver; } // namespace hal @@ -258,22 +259,45 @@ void SetTimezone(const nsCString& aTimezoneSpec); nsCString GetTimezone(); /** - * Register observer for system time changed notification. + * Register observer for system clock changed notification. * @param aObserver The observer that should be added. */ -void RegisterSystemTimeChangeObserver(hal::SystemTimeObserver* aObserver); +void RegisterSystemClockChangeObserver( + hal::SystemClockChangeObserver* aObserver); /** - * Unregister the observer for system time changed. + * Unregister the observer for system clock changed. * @param aObserver The observer that should be removed. */ -void UnregisterSystemTimeChangeObserver(hal::SystemTimeObserver* aObserver); +void UnregisterSystemClockChangeObserver( + hal::SystemClockChangeObserver* aObserver); /** - * Notify of a change in the system cloeck or time zone. - * @param aReason + * Notify of a change in the system clock. + * @param aClockDeltaMS */ -void NotifySystemTimeChange(const hal::SystemTimeChange& aReason); +void NotifySystemClockChange(const int64_t& aClockDeltaMS); + +/** + * Register observer for system timezone changed notification. + * @param aObserver The observer that should be added. + */ +void RegisterSystemTimezoneChangeObserver( + hal::SystemTimezoneChangeObserver* aObserver); + +/** + * Unregister the observer for system timezone changed. + * @param aObserver The observer that should be removed. + */ +void UnregisterSystemTimezoneChangeObserver( + hal::SystemTimezoneChangeObserver* aObserver); + +/** + * Notify of a change in the system timezone. + * @param aSystemTimezoneChangeInfo + */ +void NotifySystemTimezoneChange( + const hal::SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo); /** * Reboot the device. diff --git a/hal/HalInternal.h b/hal/HalInternal.h index 71a1315f01a..e42672e0e08 100644 --- a/hal/HalInternal.h +++ b/hal/HalInternal.h @@ -75,14 +75,24 @@ bool EnableAlarm(); void DisableAlarm(); /** - * Enable system time change notifications from the backend. + * Enable system clock change notifications from the backend. */ -void EnableSystemTimeChangeNotifications(); +void EnableSystemClockChangeNotifications(); /** - * Disable system time change notifications from the backend. + * Disable system clock change notifications from the backend. */ -void DisableSystemTimeChangeNotifications(); +void DisableSystemClockChangeNotifications(); + +/** + * Enable system timezone change notifications from the backend. + */ +void EnableSystemTimezoneChangeNotifications(); + +/** + * Disable system timezone change notifications from the backend. + */ +void DisableSystemTimezoneChangeNotifications(); bool IsHalChildLive(); } // namespace MOZ_HAL_NAMESPACE diff --git a/hal/HalTypes.h b/hal/HalTypes.h index 70368cb4092..0a3d25293fe 100644 --- a/hal/HalTypes.h +++ b/hal/HalTypes.h @@ -84,13 +84,6 @@ enum WakeLockControl { NUM_WAKE_LOCK }; -enum SystemTimeChange { - SYS_TIME_CHANGE_UNKNOWN = -1, - SYS_TIME_CHANGE_CLOCK, - SYS_TIME_CHANGE_TZ, - SYS_TIME_CHANGE_GUARD -}; - class FMRadioOperationInformation; enum FMRadioOperation { @@ -167,7 +160,6 @@ enum FMRadioCountry { }; typedef Observer FMRadioObserver; -typedef Observer SystemTimeChangeObserver; } // namespace hal } // namespace mozilla @@ -250,16 +242,6 @@ struct ParamTraits: mozilla::hal::NUM_PROCESS_PRIORITY> { }; -/** - * SystemTimeChange serializer. - */ -template <> -struct ParamTraits - : public EnumSerializer -{}; - /** * Serializer for FMRadioOperation */ diff --git a/hal/fallback/FallbackTime.cpp b/hal/fallback/FallbackTime.cpp index 8f65d6680ab..ac9d8eb24dd 100644 --- a/hal/fallback/FallbackTime.cpp +++ b/hal/fallback/FallbackTime.cpp @@ -25,13 +25,24 @@ GetTimezone() } void -EnableSystemTimeChangeNotifications() +EnableSystemClockChangeNotifications() { } void -DisableSystemTimeChangeNotifications() +DisableSystemClockChangeNotifications() { } + +void +EnableSystemTimezoneChangeNotifications() +{ +} + +void +DisableSystemTimezoneChangeNotifications() +{ +} + } // namespace hal_impl } // namespace mozilla diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index 12a333f61ae..a60ce417457 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -83,6 +83,13 @@ #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; @@ -250,6 +257,26 @@ public: { 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. + + hal::LightConfiguration aConfig(hal::eHalLightID_Battery, + hal::eHalLightMode_User, + hal::eHalLightFlash_None, + 0, + 0, + color); + hal_impl::SetLight(hal::eHalLightID_Battery, aConfig); + hal::NotifyBatteryChange(info); return NS_OK; } @@ -643,7 +670,21 @@ AdjustSystemClock(int64_t aDeltaMilliseconds) return; } - hal::NotifySystemTimeChange(hal::SYS_TIME_CHANGE_CLOCK); + hal::NotifySystemClockChange(aDeltaMilliseconds); +} + +static 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); } void @@ -653,11 +694,15 @@ SetTimezone(const nsCString& aTimezoneSpec) 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(); - hal::NotifySystemTimeChange(hal::SYS_TIME_CHANGE_TZ); + int32_t newTimezoneOffsetMinutes = GetTimezoneOffset(); + hal::NotifySystemTimezoneChange( + hal::SystemTimezoneChangeInformation( + oldTimezoneOffsetMinutes, newTimezoneOffsetMinutes)); } nsCString @@ -669,12 +714,22 @@ GetTimezone() } void -EnableSystemTimeChangeNotifications() +EnableSystemClockChangeNotifications() { } void -DisableSystemTimeChangeNotifications() +DisableSystemClockChangeNotifications() +{ +} + +void +EnableSystemTimezoneChangeNotifications() +{ +} + +void +DisableSystemTimezoneChangeNotifications() { } diff --git a/hal/sandbox/PHal.ipdl b/hal/sandbox/PHal.ipdl index 3c8bfbf4b9b..3c8dd12159d 100644 --- a/hal/sandbox/PHal.ipdl +++ b/hal/sandbox/PHal.ipdl @@ -24,7 +24,6 @@ using mozilla::hal::SwitchDevice; using mozilla::hal::ProcessPriority; using nsIntRect; using PRTime; -using mozilla::hal::SystemTimeChange; using mozilla::hal::FMRadioCountry; using mozilla::hal::FMRadioOperation; using mozilla::hal::FMRadioOperationStatus; @@ -92,6 +91,13 @@ struct FMRadioSettings { uint32_t preEmphasis; }; +struct SystemTimezoneChangeInformation { + // These timezone offsets are relative to UTC in minutes and + // have already taken daylight saving time (DST) into account. + int32_t oldTimezoneOffsetMinutes; + int32_t newTimezoneOffsetMinutes; +}; + } // namespace hal namespace hal_sandbox { @@ -105,7 +111,8 @@ child: NotifyWakeLockChange(WakeLockInformation aWakeLockInfo); NotifyScreenConfigurationChange(ScreenConfiguration aScreenOrientation); NotifySwitchChange(SwitchEvent aEvent); - NotifySystemTimeChange(SystemTimeChange aReason); + NotifySystemClockChange(int64_t aClockDeltaMS); + NotifySystemTimezoneChange(SystemTimezoneChangeInformation aSystemTimezoneChangeInfo); NotifyFMRadioStatus(FMRadioOperationInformation aInfo); parent: @@ -135,8 +142,10 @@ parent: SetTimezone(nsCString aTimezoneSpec); sync GetTimezone() returns (nsCString aTimezoneSpec); - EnableSystemTimeChangeNotifications(); - DisableSystemTimeChangeNotifications(); + EnableSystemClockChangeNotifications(); + DisableSystemClockChangeNotifications(); + EnableSystemTimezoneChangeNotifications(); + DisableSystemTimezoneChangeNotifications(); sync SetLight(LightType light, LightConfiguration aConfig) returns (bool status); diff --git a/hal/sandbox/SandboxHal.cpp b/hal/sandbox/SandboxHal.cpp index 8276c26ce7b..fa2adaa9f40 100644 --- a/hal/sandbox/SandboxHal.cpp +++ b/hal/sandbox/SandboxHal.cpp @@ -212,15 +212,27 @@ GetTimezone() } void -EnableSystemTimeChangeNotifications() +EnableSystemClockChangeNotifications() { - Hal()->SendEnableSystemTimeChangeNotifications(); + Hal()->SendEnableSystemClockChangeNotifications(); } void -DisableSystemTimeChangeNotifications() +DisableSystemClockChangeNotifications() { - Hal()->SendDisableSystemTimeChangeNotifications(); + Hal()->SendDisableSystemClockChangeNotifications(); +} + +void +EnableSystemTimezoneChangeNotifications() +{ + Hal()->SendEnableSystemTimezoneChangeNotifications(); +} + +void +DisableSystemTimezoneChangeNotifications() +{ + Hal()->SendDisableSystemTimezoneChangeNotifications(); } void @@ -394,7 +406,8 @@ class HalParent : public PHalParent , public WakeLockObserver , public ScreenConfigurationObserver , public SwitchObserver - , public SystemTimeObserver + , public SystemClockChangeObserver + , public SystemTimezoneChangeObserver { public: virtual void @@ -410,7 +423,8 @@ public: hal::UnregisterSensorObserver(SensorType(sensor), this); } hal::UnregisterWakeLockObserver(this); - hal::UnregisterSystemTimeChangeObserver(this); + hal::UnregisterSystemClockChangeObserver(this); + hal::UnregisterSystemTimezoneChangeObserver(this); } virtual bool @@ -643,16 +657,30 @@ public: } virtual bool - RecvEnableSystemTimeChangeNotifications() MOZ_OVERRIDE + RecvEnableSystemClockChangeNotifications() MOZ_OVERRIDE { - hal::RegisterSystemTimeChangeObserver(this); + hal::RegisterSystemClockChangeObserver(this); return true; } virtual bool - RecvDisableSystemTimeChangeNotifications() MOZ_OVERRIDE + RecvDisableSystemClockChangeNotifications() MOZ_OVERRIDE { - hal::UnregisterSystemTimeChangeObserver(this); + hal::UnregisterSystemClockChangeObserver(this); + return true; + } + + virtual bool + RecvEnableSystemTimezoneChangeNotifications() MOZ_OVERRIDE + { + hal::RegisterSystemTimezoneChangeObserver(this); + return true; + } + + virtual bool + RecvDisableSystemTimezoneChangeNotifications() MOZ_OVERRIDE + { + hal::UnregisterSystemTimezoneChangeObserver(this); return true; } @@ -749,9 +777,14 @@ public: return true; } - void Notify(const SystemTimeChange& aReason) + void Notify(const int64_t& aClockDeltaMS) { - unused << SendNotifySystemTimeChange(aReason); + unused << SendNotifySystemClockChange(aClockDeltaMS); + } + + void Notify(const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) + { + unused << SendNotifySystemTimezoneChange(aSystemTimezoneChangeInfo); } virtual bool @@ -902,8 +935,15 @@ public: } virtual bool - RecvNotifySystemTimeChange(const SystemTimeChange& aReason) { - hal::NotifySystemTimeChange(aReason); + RecvNotifySystemClockChange(const int64_t& aClockDeltaMS) { + hal::NotifySystemClockChange(aClockDeltaMS); + return true; + } + + virtual bool + RecvNotifySystemTimezoneChange( + const SystemTimezoneChangeInformation& aSystemTimezoneChangeInfo) { + hal::NotifySystemTimezoneChange(aSystemTimezoneChangeInfo); return true; } diff --git a/intl/unicharutil/util/nsUnicharUtils.cpp b/intl/unicharutil/util/nsUnicharUtils.cpp index 25f81965228..ce6d89105ac 100644 --- a/intl/unicharutil/util/nsUnicharUtils.cpp +++ b/intl/unicharutil/util/nsUnicharUtils.cpp @@ -36,7 +36,7 @@ static const uint8_t gASCIIToLower [128] = { // We want ToLowerCase(uint32_t) and ToLowerCaseASCII(uint32_t) to be fast // when they're called from within the case-insensitive comparators, so we // define inlined versions. -static NS_ALWAYS_INLINE uint32_t +static MOZ_ALWAYS_INLINE uint32_t ToLowerCase_inline(uint32_t aChar) { if (IS_ASCII(aChar)) { @@ -46,7 +46,7 @@ ToLowerCase_inline(uint32_t aChar) return mozilla::unicode::GetLowercase(aChar); } -static NS_ALWAYS_INLINE uint32_t +static MOZ_ALWAYS_INLINE uint32_t ToLowerCaseASCII_inline(const uint32_t aChar) { if (IS_ASCII(aChar)) { @@ -271,7 +271,7 @@ CaseInsensitiveCompare(const PRUnichar *a, // the end of the string (as marked by aEnd), returns -1 and does not set // aNext. Note that this function doesn't check that aStr < aEnd -- it assumes // you've done that already. -static NS_ALWAYS_INLINE uint32_t +static MOZ_ALWAYS_INLINE uint32_t GetLowerUTF8Codepoint(const char* aStr, const char* aEnd, const char **aNext) { // Convert to unsigned char so that stuffing chars into PRUint32s doesn't diff --git a/js/src/jit-test/tests/jaeger/bug781859-1.js b/js/src/jit-test/tests/jaeger/bug781859-1.js new file mode 100644 index 00000000000..7a28c02b77e --- /dev/null +++ b/js/src/jit-test/tests/jaeger/bug781859-1.js @@ -0,0 +1,25 @@ +// |jit-test| error:ReferenceError +function e() { + try {} catch (e) { + return (actual = "FAIL"); + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + a.x + } + while (t) continue; +} +e(); diff --git a/js/src/jit-test/tests/jaeger/bug781859-2.js b/js/src/jit-test/tests/jaeger/bug781859-2.js new file mode 100644 index 00000000000..42640ef07b7 --- /dev/null +++ b/js/src/jit-test/tests/jaeger/bug781859-2.js @@ -0,0 +1,9 @@ +mjitChunkLimit(42); +Function("\ + switch (/x/) {\ + case 8:\ + break;\ + t(function(){})\ + }\ + while (false)(function(){})\ +")() diff --git a/js/src/jit-test/tests/jaeger/bug781859-3.js b/js/src/jit-test/tests/jaeger/bug781859-3.js new file mode 100644 index 00000000000..08cf1559e89 --- /dev/null +++ b/js/src/jit-test/tests/jaeger/bug781859-3.js @@ -0,0 +1,10 @@ +mjitChunkLimit(10); +function e() { + try { + var t = undefined; + } catch (e) { } + while (t) + continue; +} +for (var i = 0; i < 20; i++) + e(); diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp index 9103fc6292b..8d88a38ddc2 100644 --- a/js/src/jsgc.cpp +++ b/js/src/jsgc.cpp @@ -2603,7 +2603,7 @@ MarkRuntime(JSTracer *trc, bool useSavedRoots = false) mjit::ExpandInlineFrames(c); #endif - rt->stackSpace.markAndClobber(trc); + rt->stackSpace.mark(trc); rt->debugScopes->mark(trc); #ifdef JS_ION @@ -3851,13 +3851,6 @@ BeginSweepPhase(JSRuntime *rt) { gcstats::AutoPhase ap(rt->gcStats, gcstats::PHASE_SWEEP_COMPARTMENTS); - /* - * Eliminate any garbage values from the VM stack that may have been - * left by the JIT in between incremental GC slices. We need to do this - * before discarding analysis data during JSCompartment::sweep. - */ - rt->stackSpace.markAndClobber(NULL); - bool releaseTypes = ReleaseObservedTypes(rt); for (CompartmentsIter c(rt); !c.done(); c.next()) { gcstats::AutoSCC scc(rt->gcStats, partition.getSCC(c)); diff --git a/js/src/jsinfer.cpp b/js/src/jsinfer.cpp index faaca69fbfb..0d0924463e3 100644 --- a/js/src/jsinfer.cpp +++ b/js/src/jsinfer.cpp @@ -748,12 +748,7 @@ void StackTypeSet::addPropagateThis(JSContext *cx, HandleScript script, jsbytecode *pc, Type type, StackTypeSet *types) { - /* Don't add constraints when the call will be 'new' (see addCallProperty). */ - jsbytecode *callpc = script->analysis()->getCallPC(pc); - if (JSOp(*callpc) == JSOP_NEW) - return; - - add(cx, cx->analysisLifoAlloc().new_(script, callpc, type, types)); + add(cx, cx->analysisLifoAlloc().new_(script, pc, type, types)); } /* Subset constraint which filters out primitive types. */ @@ -1207,7 +1202,6 @@ TypeConstraintCallProp::newType(JSContext *cx, TypeSet *source, Type typ return; if (!types->hasPropagatedProperty()) object->getFromPrototypes(cx, id, types); - /* Bypass addPropagateThis, we already have the callpc. */ if (access == PROPERTY_READ) { types->add(cx, cx->typeLifoAlloc().new_( script_, callpc, type, (StackTypeSet *) NULL)); @@ -3579,16 +3573,6 @@ GetInitializerType(JSContext *cx, HandleScript script, jsbytecode *pc) return TypeScript::InitObject(cx, script, pc, key); } -static inline Type -GetCalleeThisType(jsbytecode *pc) -{ - pc += GetBytecodeLength(pc); - if (*pc == JSOP_UNDEFINED) - return Type::UndefinedType(); - JS_ASSERT(*pc == JSOP_IMPLICITTHIS); - return Type::UnknownType(); -} - /* Analyze type information for a single bytecode. */ bool ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferenceState &state) @@ -3823,9 +3807,6 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen PropertyAccess(cx, script, pc, global, seen, id); else PropertyAccess(cx, script, pc, global, seen, id); - - if (op == JSOP_CALLGNAME) - pushed[0].addPropagateThis(cx, script, pc, GetCalleeThisType(pc)); break; } @@ -3836,8 +3817,6 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen StackTypeSet *seen = bytecodeTypes(pc); addTypeBarrier(cx, pc, seen, Type::UnknownType()); seen->addSubset(cx, &pushed[0]); - if (op == JSOP_CALLNAME || op == JSOP_CALLINTRINSIC) - pushed[0].addPropagateThis(cx, script, pc, GetCalleeThisType(pc)); break; } @@ -3885,8 +3864,6 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen /* Local 'let' variable. Punt on types for these, for now. */ pushed[0].addType(cx, Type::UnknownType()); } - if (op == JSOP_CALLARG || op == JSOP_CALLLOCAL) - pushed[0].addPropagateThis(cx, script, pc, Type::UndefinedType()); break; } @@ -3917,8 +3894,6 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen * variable. Instead, we monitor/barrier all reads unconditionally. */ bytecodeTypes(pc)->addSubset(cx, &pushed[0]); - if (op == JSOP_CALLALIASEDVAR) - pushed[0].addPropagateThis(cx, script, pc, Type::UnknownType()); break; case JSOP_SETALIASEDVAR: @@ -4035,8 +4010,6 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen } seen->addSubset(cx, &pushed[0]); - if (op == JSOP_CALLELEM) - pushed[0].addPropagateThis(cx, script, pc, Type::UndefinedType(), poppedTypes(pc, 1)); break; } @@ -4133,7 +4106,24 @@ ScriptAnalysis::analyzeTypesBytecode(JSContext *cx, unsigned offset, TypeInferen if (op == JSOP_FUNCALL || op == JSOP_FUNAPPLY) cx->compartment->types.monitorBytecode(cx, script, pc - script_->code); - poppedTypes(pc, argCount + 1)->addCall(cx, callsite); + StackTypeSet *calleeTypes = poppedTypes(pc, argCount + 1); + + /* + * Propagate possible 'this' types to the callee except when the call + * came through JSOP_CALLPROP (which uses TypeConstraintCallProperty) + * or for JSOP_NEW (where the callee will construct the 'this' object). + */ + SSAValue calleeValue = poppedValue(pc, argCount + 1); + if (*pc != JSOP_NEW && + (calleeValue.kind() != SSAValue::PUSHED || + script->code[calleeValue.pushedOffset()] != JSOP_CALLPROP)) + { + HandleScript script_ = script; + calleeTypes->add(cx, cx->analysisLifoAlloc().new_ + (script_, pc, Type::UndefinedType(), callsite->thisTypes)); + } + + calleeTypes->addCall(cx, callsite); break; } diff --git a/js/src/methodjit/Compiler.cpp b/js/src/methodjit/Compiler.cpp index f80051f98cb..2d502f2b968 100644 --- a/js/src/methodjit/Compiler.cpp +++ b/js/src/methodjit/Compiler.cpp @@ -704,7 +704,7 @@ MakeJITScript(JSContext *cx, JSScript *script) Bytecode *code = analysis->maybeCode(offset); if (!code) - continue; + op = JSOP_NOP; /* Ignore edges from unreachable opcodes. */ /* Whether this should be the last opcode in the chunk. */ bool finishChunk = false; @@ -1292,17 +1292,7 @@ mjit::Compiler::markUndefinedLocal(uint32_t offset, uint32_t i) uint32_t depth = ssa.getFrame(a->inlineIndex).depth; uint32_t slot = LocalSlot(script_, i); Address local(JSFrameReg, sizeof(StackFrame) + (depth + i) * sizeof(Value)); - if (!cx->typeInferenceEnabled() || !analysis->trackSlot(slot)) { - masm.storeValue(UndefinedValue(), local); - } else { - Lifetime *lifetime = analysis->liveness(slot).live(offset); - if (lifetime) - masm.storeValue(UndefinedValue(), local); -#ifdef DEBUG - else - masm.storeValue(ObjectValueCrashOnTouch(), local); -#endif - } + masm.storeValue(UndefinedValue(), local); } void diff --git a/js/src/methodjit/FrameState-inl.h b/js/src/methodjit/FrameState-inl.h index a5440d28806..a12867a47e3 100644 --- a/js/src/methodjit/FrameState-inl.h +++ b/js/src/methodjit/FrameState-inl.h @@ -938,8 +938,6 @@ FrameState::fakeSync(FrameEntry *fe) */ if (!fe->data.synced()) fe->data.sync(); - if (!fe->type.synced()) - fe->type.sync(); } inline void diff --git a/js/src/methodjit/FrameState.cpp b/js/src/methodjit/FrameState.cpp index 0cf8c829e21..13874681e71 100644 --- a/js/src/methodjit/FrameState.cpp +++ b/js/src/methodjit/FrameState.cpp @@ -312,11 +312,11 @@ FrameState::bestEvictReg(uint32_t mask, bool includePinned) const */ Lifetime *lifetime = variableLive(fe, a->PC); + /* Evict variables whose value is no longer live. */ if (!lifetime) { - JS_ASSERT(isConstructorThis(fe)); fallback = reg; fallbackOffset = a->script->length; - JaegerSpew(JSpew_Regalloc, " %s is 'this' in a constructor\n", reg.name()); + JaegerSpew(JSpew_Regalloc, " %s is dead\n", reg.name()); continue; } @@ -353,6 +353,21 @@ FrameState::bestEvictReg(uint32_t mask, bool includePinned) const return fallback; } +/* + * Whether we can pretend the payload for a given entry is synced provided that + * the value in the entry is dead. The contents of dead variables can still be + * observed during stack scanning, so the payloads of values which might hold + * objects or strings must be preserved. + */ +static inline bool +CanFakeSync(FrameEntry *fe) +{ + return fe->isNotType(JSVAL_TYPE_OBJECT) + && fe->isNotType(JSVAL_TYPE_STRING) + && fe->isNotType(JSVAL_TYPE_DOUBLE) + && fe->isNotType(JSVAL_TYPE_MAGIC); +} + void FrameState::evictDeadEntries(bool includePinned) { @@ -374,25 +389,17 @@ FrameState::evictDeadEntries(bool includePinned) } Lifetime *lifetime = variableLive(fe, a->PC); - if (lifetime) + if (lifetime || !CanFakeSync(fe)) continue; - /* - * If we are about to fake sync for an entry with known type, reset - * that type. We don't want to regard it as correctly synced later. - */ - if (!fe->type.synced() && fe->isTypeKnown()) - fe->type.setMemory(); + JS_ASSERT(regstate(reg).type() == RematInfo::DATA); /* * Mark the entry as synced to avoid emitting a store, we don't need * to keep this value around. */ fakeSync(fe); - if (regstate(reg).type() == RematInfo::DATA) - fe->data.setMemory(); - else - fe->type.setMemory(); + fe->data.setMemory(); forgetReg(reg); } } @@ -719,7 +726,7 @@ FrameState::syncForAllocation(RegisterAllocation *alloc, bool inlineReturn, Uses /* Force syncs for locals which are dead at the current PC. */ if (isLocal(fe) && !fe->copied && !a->analysis->slotEscapes(entrySlot(fe))) { Lifetime *lifetime = a->analysis->liveness(entrySlot(fe)).live(a->PC - a->script->code); - if (!lifetime) + if (!lifetime && CanFakeSync(fe)) fakeSync(fe); } @@ -729,7 +736,7 @@ FrameState::syncForAllocation(RegisterAllocation *alloc, bool inlineReturn, Uses !a->parent->analysis->slotEscapes(frameSlot(a->parent, fe))) { const LifetimeVariable &var = a->parent->analysis->liveness(frameSlot(a->parent, fe)); Lifetime *lifetime = var.live(a->parent->PC - a->parent->script->code); - if (!lifetime) + if (!lifetime && CanFakeSync(fe)) fakeSync(fe); } diff --git a/js/src/vm/Stack.cpp b/js/src/vm/Stack.cpp index 29cd9d27d21..a3f4693dec4 100644 --- a/js/src/vm/Stack.cpp +++ b/js/src/vm/Stack.cpp @@ -633,81 +633,14 @@ StackSpace::containingSegment(const StackFrame *target) const } void -StackSpace::markAndClobberFrame(JSTracer *trc, StackFrame *fp, Value *slotsEnd, jsbytecode *pc) +StackSpace::markFrame(JSTracer *trc, StackFrame *fp, Value *slotsEnd) { - AutoAssertNoGC nogc; Value *slotsBegin = fp->slots(); - - /* If it's a scripted frame, we should have a pc. */ - JS_ASSERT(pc); - - RawScript script = fp->script(); - if (!script->hasAnalysis() || !script->analysis()->ranLifetimes()) { - if (trc) - gc::MarkValueRootRange(trc, slotsBegin, slotsEnd, "vm_stack"); - return; - } - - /* - * If the JIT ran a lifetime analysis, then it may have left garbage in the - * slots considered not live. We need to avoid marking them. Additionally, - * in case the analysis information is thrown out later, we overwrite these - * dead slots with valid values so that future GCs won't crash. Analysis - * results are thrown away during the sweeping phase, so we always have at - * least one GC to do this. - */ - JSRuntime *rt = script->compartment()->rt; - analyze::AutoEnterAnalysis aea(script->compartment()); - analyze::ScriptAnalysis *analysis = script->analysis(); - uint32_t offset = pc - script->code; - Value *fixedEnd = slotsBegin + script->nfixed; - for (Value *vp = slotsBegin; vp < fixedEnd; vp++) { - uint32_t slot = analyze::LocalSlot(script, vp - slotsBegin); - - /* Will this slot be synced by the JIT? */ - if (!analysis->trackSlot(slot) || analysis->liveness(slot).live(offset)) { - if (trc) - gc::MarkValueRoot(trc, vp, "vm_stack"); - } else if (!trc || script->compartment()->isDiscardingJitCode(trc)) { - /* - * If we're throwing away analysis information, we need to replace - * non-live Values with ones that can safely be marked in later - * collections. - */ - if (vp->isDouble()) { - *vp = DoubleValue(0.0); - } else { - /* - * It's possible that *vp may not be a valid Value. For example, - * it may be tagged as a NullValue but the low bits may be - * nonzero so that isNull() returns false. This can cause - * problems later on when marking the value. Extracting the type - * in this way and then overwriting the value circumvents the - * problem. - */ - JSValueType type = vp->extractNonDoubleType(); - if (type == JSVAL_TYPE_INT32) - *vp = Int32Value(0); - else if (type == JSVAL_TYPE_UNDEFINED) - *vp = UndefinedValue(); - else if (type == JSVAL_TYPE_BOOLEAN) - *vp = BooleanValue(false); - else if (type == JSVAL_TYPE_STRING) - *vp = StringValue(rt->atomState.null); - else if (type == JSVAL_TYPE_NULL) - *vp = NullValue(); - else if (type == JSVAL_TYPE_OBJECT) - *vp = ObjectValue(fp->scopeChain()->global()); - } - } - } - - if (trc) - gc::MarkValueRootRange(trc, fixedEnd, slotsEnd, "vm_stack"); + gc::MarkValueRootRange(trc, slotsBegin, slotsEnd, "vm_stack"); } void -StackSpace::markAndClobber(JSTracer *trc) +StackSpace::mark(JSTracer *trc) { /* NB: this depends on the continuity of segments in memory. */ Value *nextSegEnd = firstUnused(); @@ -726,18 +659,16 @@ StackSpace::markAndClobber(JSTracer *trc) jsbytecode *pc = seg->maybepc(); for (StackFrame *fp = seg->maybefp(); (Value *)fp > (Value *)seg; fp = fp->prev()) { /* Mark from fp->slots() to slotsEnd. */ - markAndClobberFrame(trc, fp, slotsEnd, pc); + markFrame(trc, fp, slotsEnd); - if (trc) - fp->mark(trc); + fp->mark(trc); slotsEnd = (Value *)fp; InlinedSite *site; pc = fp->prevpc(&site); JS_ASSERT_IF(fp->prev(), !site); } - if (trc) - gc::MarkValueRootRange(trc, seg->slotsBegin(), slotsEnd, "vm_stack"); + gc::MarkValueRootRange(trc, seg->slotsBegin(), slotsEnd, "vm_stack"); nextSegEnd = (Value *)seg; } } diff --git a/js/src/vm/Stack.h b/js/src/vm/Stack.h index 84c0d4f5a87..3e2de022403 100644 --- a/js/src/vm/Stack.h +++ b/js/src/vm/Stack.h @@ -1382,7 +1382,7 @@ class StackSpace return (Value *)fp >= base_ && (Value *)fp <= trustedEnd_; } - void markAndClobberFrame(JSTracer *trc, StackFrame *fp, Value *slotsEnd, jsbytecode *pc); + void markFrame(JSTracer *trc, StackFrame *fp, Value *slotsEnd); public: StackSpace(); @@ -1435,7 +1435,7 @@ class StackSpace bool tryBumpLimit(JSContext *cx, Value *from, unsigned nvals, Value **limit); /* Called during GC: mark segments, frames, and slots under firstUnused. */ - void markAndClobber(JSTracer *trc); + void mark(JSTracer *trc); /* Called during GC: sets active flag on compartments with active frames. */ void markActiveCompartments(); diff --git a/js/xpconnect/src/dictionary_helper_gen.conf b/js/xpconnect/src/dictionary_helper_gen.conf index 46b87df4e5d..49be56f73b6 100644 --- a/js/xpconnect/src/dictionary_helper_gen.conf +++ b/js/xpconnect/src/dictionary_helper_gen.conf @@ -11,8 +11,6 @@ dictionaries = [ [ 'IDBObjectStoreParameters', 'nsIIDBDatabase.idl' ], [ 'IDBIndexParameters', 'nsIIDBObjectStore.idl' ], [ 'MutationObserverInit', 'nsIDOMMutationObserver.idl' ], - [ 'WifiConnectionInfoEventInit', 'nsIWifiEventInits.idl' ], - [ 'WifiStatusChangeEventInit', 'nsIWifiEventInits.idl' ], [ 'GeoPositionOptions', 'nsIDOMGeoGeolocation.idl' ], [ 'DOMFileMetadataParameters', 'nsIDOMLockedFile.idl' ], [ 'XMLHttpRequestParameters', 'nsIXMLHttpRequest.idl' ], diff --git a/js/xpconnect/src/event_impl_gen.conf.in b/js/xpconnect/src/event_impl_gen.conf.in index 903f686daa2..87059a732a8 100644 --- a/js/xpconnect/src/event_impl_gen.conf.in +++ b/js/xpconnect/src/event_impl_gen.conf.in @@ -28,6 +28,8 @@ simple_events = [ #endif #ifdef MOZ_B2G_RIL 'ICCCardLockErrorEvent', + 'MozWifiStatusChangeEvent', + 'MozWifiConnectionInfoEvent', #endif 'DeviceStorageChangeEvent', 'PopupBlockedEvent' diff --git a/layout/base/FrameLayerBuilder.cpp b/layout/base/FrameLayerBuilder.cpp index 0f03311fcc1..e84277debc0 100644 --- a/layout/base/FrameLayerBuilder.cpp +++ b/layout/base/FrameLayerBuilder.cpp @@ -1943,8 +1943,7 @@ PaintInactiveLayer(nsDisplayListBuilder* aBuilder, if (builder) { builder->DidEndTransaction(); } - - basic->SetUserData(&gLayerManagerLayerBuilder, NULL); + #ifdef MOZ_DUMP_PAINTING if (gfxUtils::sDumpPainting) { DumpPaintedImage(aItem, surf); @@ -2340,7 +2339,7 @@ FrameLayerBuilder::AddThebesDisplayItem(ThebesLayer* aLayer, if (!tempManager) { tempManager = new BasicLayerManager(); } - + // We need to grab these before calling AddLayerDisplayItem because it will overwrite them. nsRegion clip; FrameLayerBuilder::Clip* oldClip = nullptr; @@ -2423,7 +2422,7 @@ FrameLayerBuilder::AddThebesDisplayItem(ThebesLayer* aLayer, ClippedDisplayItem* cdi = entry->mItems.AppendElement(ClippedDisplayItem(aItem, aClip, mContainerLayerGeneration)); - cdi->mInactiveLayer = tempManager; + cdi->mInactiveLayerManager = tempManager; } } @@ -2484,11 +2483,11 @@ FrameLayerBuilder::StoreDataForFrame(nsIFrame* aFrame, FrameLayerBuilder::ClippedDisplayItem::~ClippedDisplayItem() { - if (mInactiveLayer) { + if (mInactiveLayerManager) { // We always start a transaction during layer construction for all inactive // layers, but we don't necessarily call EndTransaction during painting. // If the transaaction is still open, end it to avoid assertions. - BasicLayerManager* basic = static_cast(mInactiveLayer.get()); + BasicLayerManager* basic = static_cast(mInactiveLayerManager.get()); if (basic->InTransaction()) { basic->EndTransaction(nullptr, nullptr); } @@ -3111,6 +3110,7 @@ FrameLayerBuilder::DrawThebesLayer(ThebesLayer* aLayer, (aCallbackData); FrameLayerBuilder *layerBuilder = aLayer->Manager()->GetLayerBuilder(); + NS_ASSERTION(layerBuilder, "Unexpectedly null layer builder!"); if (layerBuilder->CheckDOMModified()) return; @@ -3238,8 +3238,8 @@ FrameLayerBuilder::DrawThebesLayer(ThebesLayer* aLayer, } } - if (cdi->mInactiveLayer) { - PaintInactiveLayer(builder, cdi->mInactiveLayer, cdi->mItem, aContext, rc); + if (cdi->mInactiveLayerManager) { + PaintInactiveLayer(builder, cdi->mInactiveLayerManager, cdi->mItem, aContext, rc); } else { nsIFrame* frame = cdi->mItem->GetUnderlyingFrame(); if (frame) { diff --git a/layout/base/FrameLayerBuilder.h b/layout/base/FrameLayerBuilder.h index 19fe1f1bfcf..feaa8979956 100644 --- a/layout/base/FrameLayerBuilder.h +++ b/layout/base/FrameLayerBuilder.h @@ -609,7 +609,7 @@ protected: * layer, then this stores the layer manager being * used for the inactive transaction. */ - nsRefPtr mInactiveLayer; + nsRefPtr mInactiveLayerManager; Clip mClip; uint32_t mContainerLayerGeneration; diff --git a/layout/base/nsDisplayList.cpp b/layout/base/nsDisplayList.cpp index 1e33cde9833..2ca93d961d2 100644 --- a/layout/base/nsDisplayList.cpp +++ b/layout/base/nsDisplayList.cpp @@ -1014,6 +1014,9 @@ void nsDisplayList::PaintForFrame(nsDisplayListBuilder* aBuilder, layerManager = new BasicLayerManager(); } + // Store the existing layer builder to reinstate it on return. + FrameLayerBuilder *oldBuilder = layerManager->GetLayerBuilder(); + FrameLayerBuilder *layerBuilder = new FrameLayerBuilder(); layerBuilder->Init(aBuilder, layerManager); @@ -1050,13 +1053,13 @@ void nsDisplayList::PaintForFrame(nsDisplayListBuilder* aBuilder, nsRefPtr root = layerBuilder-> BuildContainerLayerFor(aBuilder, layerManager, aForFrame, nullptr, *this, containerParameters, nullptr); - + if (widgetTransaction) { aForFrame->ClearInvalidationStateBits(); } if (!root) { - layerManager->RemoveUserData(&gLayerManagerLayerBuilder); + layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder); return; } // Root is being scaled up by the X/Y resolution. Scale it back down. @@ -1135,7 +1138,7 @@ void nsDisplayList::PaintForFrame(nsDisplayListBuilder* aBuilder, } nsCSSRendering::DidPaint(); - layerManager->RemoveUserData(&gLayerManagerLayerBuilder); + layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder); } uint32_t nsDisplayList::Count() const { diff --git a/layout/build/nsLayoutModule.cpp b/layout/build/nsLayoutModule.cpp index 03d12f78e33..5c18ecb43ff 100644 --- a/layout/build/nsLayoutModule.cpp +++ b/layout/build/nsLayoutModule.cpp @@ -91,6 +91,7 @@ #include "nsDOMStorage.h" #include "nsJSON.h" #include "mozilla/dom/indexedDB/IndexedDatabaseManager.h" +#include "mozIApplicationClearPrivateDataParams.h" #include "mozilla/dom/DOMRequest.h" #include "mozilla/OSFileConstants.h" #include "mozilla/dom/Activity.h" @@ -1296,6 +1297,7 @@ static const mozilla::Module::CategoryEntry kLayoutCategories[] = { { "net-channel-event-sinks", "CSPService", CSPSERVICE_CONTRACTID }, { JAVASCRIPT_GLOBAL_STATIC_NAMESET_CATEGORY, "PrivilegeManager", NS_SECURITYNAMESET_CONTRACTID }, { "app-startup", "Script Security Manager", "service," NS_SCRIPTSECURITYMANAGER_CONTRACTID }, + { TOPIC_WEB_APP_CLEAR_DATA, "IndexedDatabaseManager", "service," INDEXEDDB_MANAGER_CONTRACTID }, #ifdef MOZ_WIDGET_GONK { "app-startup", "Volume Service", "service," NS_VOLUMESERVICE_CONTRACTID }, #endif diff --git a/layout/reftests/canvas/reftest.list b/layout/reftests/canvas/reftest.list index b00520a9483..8f69a1755fa 100644 --- a/layout/reftests/canvas/reftest.list +++ b/layout/reftests/canvas/reftest.list @@ -49,6 +49,9 @@ fails-if(Android) != text-font-lang.html text-font-lang-notref.html == strokeText-path.html strokeText-path-ref.html +# check that emoji character renders as something non-blank (for Apple Color Emoji font, bug 715798) +random-if(!cocoaWidget) fails-if(OSX==10.6) random-if(OSX==10.7) != text-emoji.html text-emoji-notref.html + # azure quartz uses CGDrawLinearGradient instead of DrawShading # so we have less control over degenerate behaviour as tested by this # test diff --git a/layout/reftests/canvas/text-emoji-notref.html b/layout/reftests/canvas/text-emoji-notref.html new file mode 100644 index 00000000000..493bd1d269a --- /dev/null +++ b/layout/reftests/canvas/text-emoji-notref.html @@ -0,0 +1,28 @@ + + + +Test for Unicode emoji in canvas + + + + +
+ + +
+ + + diff --git a/layout/reftests/canvas/text-emoji.html b/layout/reftests/canvas/text-emoji.html new file mode 100644 index 00000000000..21ce9a7086a --- /dev/null +++ b/layout/reftests/canvas/text-emoji.html @@ -0,0 +1,28 @@ + + + +Test for Unicode emoji in canvas + + + + +
+ + +
+ + + diff --git a/layout/reftests/text/emoji-01-notref.html b/layout/reftests/text/emoji-01-notref.html new file mode 100644 index 00000000000..8c5c479705b --- /dev/null +++ b/layout/reftests/text/emoji-01-notref.html @@ -0,0 +1,19 @@ + + + + +Check that emoji char renders something visible (bug 715798, bug 779042) + + + +
+U+1F603: +
+ + diff --git a/layout/reftests/text/emoji-01.html b/layout/reftests/text/emoji-01.html new file mode 100644 index 00000000000..53082b913d8 --- /dev/null +++ b/layout/reftests/text/emoji-01.html @@ -0,0 +1,19 @@ + + + + +Check that emoji char renders something visible (bug 715798, bug 779042) + + + +
+U+1F603: 😃 +
+ + diff --git a/layout/reftests/text/emoji-02-notref.html b/layout/reftests/text/emoji-02-notref.html new file mode 100644 index 00000000000..e9fc9fe6b0f --- /dev/null +++ b/layout/reftests/text/emoji-02-notref.html @@ -0,0 +1,19 @@ + + + + +Check that HUGE emoji char renders something visible (bug 715798, bug 779042) + + + +
+U+1F633:   +
+ + diff --git a/layout/reftests/text/emoji-02.html b/layout/reftests/text/emoji-02.html new file mode 100644 index 00000000000..389d338e272 --- /dev/null +++ b/layout/reftests/text/emoji-02.html @@ -0,0 +1,19 @@ + + + + +Check that HUGE emoji char renders something visible (bug 715798, bug 779042) + + + +
+U+1F633: 😳 +
+ + diff --git a/layout/reftests/text/reftest.list b/layout/reftests/text/reftest.list index bc6f01eb134..1203fed6a3d 100644 --- a/layout/reftests/text/reftest.list +++ b/layout/reftests/text/reftest.list @@ -162,6 +162,11 @@ fails-if(!cocoaWidget) HTTP(..) != arabic-fallback-4.html arabic-fallback-4-notr == 745555-1.html 745555-1-ref.html == 745555-2.html 745555-2-ref.html +# ensure emoji chars don't render blank (bug 715798, bug 779042); +# should at least render hexboxes if there's no font support +!= emoji-01.html emoji-01-notref.html +!= emoji-02.html emoji-02-notref.html + # tests to compare graphite to opentype (will trivially pass when graphite not enabled) HTTP(..) == graphite-05-ot-only.html graphite-05-ref.html HTTP(..) != graphite-05-ot-only.html graphite-05-fail.html diff --git a/layout/style/nsRuleNode.cpp b/layout/style/nsRuleNode.cpp index e847c861f79..3fbe864ceba 100644 --- a/layout/style/nsRuleNode.cpp +++ b/layout/style/nsRuleNode.cpp @@ -3003,8 +3003,9 @@ nsRuleNode::SetFont(nsPresContext* aPresContext, nsStyleContext* aContext, gfxFontStyle fontStyle; LookAndFeel::FontID fontID = (LookAndFeel::FontID)systemFontValue->GetIntValue(); - float devPerCSS = (float)nsPresContext::AppUnitsPerCSSPixel() / - aPresContext->AppUnitsPerDevPixel(); + float devPerCSS = + (float)nsPresContext::AppUnitsPerCSSPixel() / + aPresContext->DeviceContext()->UnscaledAppUnitsPerDevPixel(); if (LookAndFeel::GetFont(fontID, systemFont.name, fontStyle, devPerCSS)) { systemFont.style = fontStyle.style; systemFont.systemFont = fontStyle.systemFont; diff --git a/layout/xul/base/public/nsIPopupBoxObject.idl b/layout/xul/base/public/nsIPopupBoxObject.idl index d5caae959bd..f4548629963 100644 --- a/layout/xul/base/public/nsIPopupBoxObject.idl +++ b/layout/xul/base/public/nsIPopupBoxObject.idl @@ -10,7 +10,7 @@ interface nsIDOMNode; interface nsIDOMEvent; interface nsIDOMClientRect; -[scriptable, uuid(6AD1B199-95D3-448B-98D7-896BCE3A1DCD)] +[scriptable, uuid(ACCEA57B-C3D8-4B6E-9101-90F04EE9DEA0)] interface nsIPopupBoxObject : nsISupports { /** @@ -151,11 +151,21 @@ interface nsIPopupBoxObject : nsISupports */ readonly attribute nsIDOMElement anchorNode; - /* + /** * Retrieve the screen rectangle of the popup, including the area occupied by * any titlebar or borders present. */ nsIDOMClientRect getOuterScreenRect(); + + /** + * Move an open popup to the given anchor position. The arguments have the same + * meaning as the corresponding argument to openPopup. This method has no effect + * on popups that are not open. + */ + void moveToAnchor(in nsIDOMElement anchorElement, + in AString position, + in long x, in long y, + in boolean attributesOverride); }; %{C++ diff --git a/layout/xul/base/src/nsMenuPopupFrame.cpp b/layout/xul/base/src/nsMenuPopupFrame.cpp index 81e2f93a0bb..90abb3842aa 100644 --- a/layout/xul/base/src/nsMenuPopupFrame.cpp +++ b/layout/xul/base/src/nsMenuPopupFrame.cpp @@ -1867,6 +1867,23 @@ nsMenuPopupFrame::MoveTo(int32_t aLeft, int32_t aTop, bool aUpdateAttrs) } } +void +nsMenuPopupFrame::MoveToAnchor(nsIContent* aAnchorContent, + const nsAString& aPosition, + int32_t aXPos, int32_t aYPos, + bool aAttributesOverride) +{ + NS_ASSERTION(mPopupState == ePopupOpenAndVisible, "popup must be open to move it"); + + InitializePopup(aAnchorContent, mTriggerContent, aPosition, + aXPos, aYPos, aAttributesOverride); + // InitializePopup changed the state so reset it. + mPopupState = ePopupOpenAndVisible; + + // Pass false here so that flipping and adjusting to fit on the screen happen. + SetPopupPosition(nullptr, false); +} + bool nsMenuPopupFrame::GetAutoPosition() { diff --git a/layout/xul/base/src/nsMenuPopupFrame.h b/layout/xul/base/src/nsMenuPopupFrame.h index 3115ea8bf9f..148969cd231 100644 --- a/layout/xul/base/src/nsMenuPopupFrame.h +++ b/layout/xul/base/src/nsMenuPopupFrame.h @@ -269,6 +269,11 @@ public: // The frame may be destroyed by this method. void MoveTo(int32_t aLeft, int32_t aTop, bool aUpdateAttrs); + void MoveToAnchor(nsIContent* aAnchorContent, + const nsAString& aPosition, + int32_t aXPos, int32_t aYPos, + bool aAttributesOverride); + bool GetAutoPosition(); void SetAutoPosition(bool aShouldAutoPosition); void SetConsumeRollupEvent(uint32_t aConsumeMode); diff --git a/layout/xul/base/src/nsPopupBoxObject.cpp b/layout/xul/base/src/nsPopupBoxObject.cpp index a93cda97a4f..51fea38f32f 100644 --- a/layout/xul/base/src/nsPopupBoxObject.cpp +++ b/layout/xul/base/src/nsPopupBoxObject.cpp @@ -107,7 +107,7 @@ nsPopupBoxObject::OpenPopupAtScreen(int32_t aXPos, int32_t aYPos, NS_IMETHODIMP nsPopupBoxObject::MoveTo(int32_t aLeft, int32_t aTop) { - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; if (menuPopupFrame) { menuPopupFrame->MoveTo(aLeft, aTop, true); } @@ -115,6 +115,25 @@ nsPopupBoxObject::MoveTo(int32_t aLeft, int32_t aTop) return NS_OK; } +NS_IMETHODIMP +nsPopupBoxObject::MoveToAnchor(nsIDOMElement* aAnchorElement, + const nsAString& aPosition, + int32_t aXPos, int32_t aYPos, + bool aAttributesOverride) +{ + nsXULPopupManager* pm = nsXULPopupManager::GetInstance(); + if (pm && mContent) { + nsCOMPtr anchorContent(do_QueryInterface(aAnchorElement)); + + nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(mContent->GetPrimaryFrame()); + if (menuPopupFrame && menuPopupFrame->PopupState() == ePopupOpenAndVisible) { + menuPopupFrame->MoveToAnchor(anchorContent, aPosition, aXPos, aYPos, aAttributesOverride); + } + } + + return NS_OK; +} + NS_IMETHODIMP nsPopupBoxObject::SizeTo(int32_t aWidth, int32_t aHeight) { @@ -135,7 +154,9 @@ nsPopupBoxObject::SizeTo(int32_t aWidth, int32_t aHeight) NS_IMETHODIMP nsPopupBoxObject::GetAutoPosition(bool* aShouldAutoPosition) { - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + *aShouldAutoPosition = true; + + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; if (menuPopupFrame) { *aShouldAutoPosition = menuPopupFrame->GetAutoPosition(); } @@ -146,7 +167,7 @@ nsPopupBoxObject::GetAutoPosition(bool* aShouldAutoPosition) NS_IMETHODIMP nsPopupBoxObject::SetAutoPosition(bool aShouldAutoPosition) { - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; if (menuPopupFrame) { menuPopupFrame->SetAutoPosition(aShouldAutoPosition); } @@ -194,7 +215,7 @@ nsPopupBoxObject::GetPopupState(nsAString& aState) // set this here in case there's no frame for the popup aState.AssignLiteral("closed"); - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; if (menuPopupFrame) { switch (menuPopupFrame->PopupState()) { case ePopupShowing: @@ -224,7 +245,7 @@ nsPopupBoxObject::GetTriggerNode(nsIDOMNode** aTriggerNode) { *aTriggerNode = nullptr; - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; nsIContent* triggerContent = nsMenuPopupFrame::GetTriggerContent(menuPopupFrame); if (triggerContent) CallQueryInterface(triggerContent, aTriggerNode); @@ -237,7 +258,7 @@ nsPopupBoxObject::GetAnchorNode(nsIDOMElement** aAnchor) { *aAnchor = nullptr; - nsMenuPopupFrame *menuPopupFrame = do_QueryFrame(GetFrame(false)); + nsMenuPopupFrame *menuPopupFrame = mContent ? do_QueryFrame(mContent->GetPrimaryFrame()) : nullptr; if (!menuPopupFrame) return NS_OK; diff --git a/media/webrtc/signaling/include/CC_Call.h b/media/webrtc/signaling/include/CC_Call.h index 8078558d612..90171d798c7 100644 --- a/media/webrtc/signaling/include/CC_Call.h +++ b/media/webrtc/signaling/include/CC_Call.h @@ -270,7 +270,7 @@ namespace CSF virtual void createOffer (const cc_media_constraints_t* constraints) = 0; - virtual void createAnswer(const cc_media_constraints_t* constraints, const std::string & offersdp) = 0; + virtual void createAnswer(const cc_media_constraints_t* constraints) = 0; virtual void setLocalDescription(cc_jsep_action_t action, const std::string & sdp) = 0; diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp index ec871597949..727ee7332ef 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp @@ -80,18 +80,24 @@ void MediaConstraints::buildArray(cc_media_constraints_t** constraintarray) { short i = 0; std::string tmpStr; *constraintarray = (cc_media_constraints_t*) cpr_malloc(sizeof(cc_media_constraints_t)); + int tmpStrAllocLength; (*constraintarray)->constraints = (cc_media_constraint_t**) cpr_malloc(mConstraints.size() * sizeof(cc_media_constraint_t)); for (constraints_map::iterator it = mConstraints.begin(); it != mConstraints.end(); ++it) { (*constraintarray)->constraints[i] = (cc_media_constraint_t*) cpr_malloc(sizeof(cc_media_constraint_t)); + tmpStr = it->first; - (*constraintarray)->constraints[i]->name = (char*) cpr_malloc(tmpStr.size()); - sstrncpy((*constraintarray)->constraints[i]->name, tmpStr.c_str(), tmpStr.size()+1); + tmpStrAllocLength = tmpStr.size() + 1; + (*constraintarray)->constraints[i]->name = (char*) cpr_malloc(tmpStrAllocLength); + sstrncpy((*constraintarray)->constraints[i]->name, tmpStr.c_str(), tmpStrAllocLength); + tmpStr = it->second.value; - (*constraintarray)->constraints[i]->value = (char*) cpr_malloc(tmpStr.size()); - sstrncpy((*constraintarray)->constraints[i]->value, tmpStr.c_str(), tmpStr.size()+1); + tmpStrAllocLength = tmpStr.size() + 1; + (*constraintarray)->constraints[i]->value = (char*) cpr_malloc(tmpStrAllocLength); + sstrncpy((*constraintarray)->constraints[i]->value, tmpStr.c_str(), tmpStrAllocLength); + (*constraintarray)->constraints[i]->mandatory = it->second.mandatory; i++; } @@ -752,26 +758,28 @@ PeerConnectionImpl::CreateOffer(MediaConstraints& constraints) { /* * the Constraints UI IDL work is being done. The CreateAnswer below is the one * currently called by the signaling unit tests. + * + * The aOffer parameter needs to be removed here and in the PeerConnection IDL */ + NS_IMETHODIMP PeerConnectionImpl::CreateAnswer(const char* constraints, const char* aOffer) { MOZ_ASSERT(constraints); - MOZ_ASSERT(aOffer); CheckIceState(); mRole = kRoleAnswerer; // TODO(ekr@rtfm.com): Interrogate SIPCC here? MediaConstraints aconstraints; - CreateAnswer(aconstraints, aOffer); + CreateAnswer(aconstraints); return NS_OK; } NS_IMETHODIMP -PeerConnectionImpl::CreateAnswer(MediaConstraints& constraints, const char* offer) { +PeerConnectionImpl::CreateAnswer(MediaConstraints& constraints) { cc_media_constraints_t* cc_constraints = nullptr; constraints.buildArray(&cc_constraints); - mCall->createAnswer(cc_constraints, offer); + mCall->createAnswer(cc_constraints); return NS_OK; } diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h index aab6d246464..5b0bab82b35 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h @@ -398,7 +398,7 @@ public: NS_IMETHODIMP CreateOffer(MediaConstraints& constraints); - NS_IMETHODIMP CreateAnswer(MediaConstraints& constraints, const char* offer); + NS_IMETHODIMP CreateAnswer(MediaConstraints& constraints); private: PeerConnectionImpl(const PeerConnectionImpl&rhs); diff --git a/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c b/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c index 866ee4c8f54..529affa0726 100644 --- a/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c +++ b/media/webrtc/signaling/src/sipcc/core/ccapp/cc_call_feature.c @@ -147,7 +147,6 @@ cc_return_t cc_invokeFeatureSDPMode(cc_call_handle_t call_handle, group_cc_featu case CC_FEATURE_CONF: case CC_FEATURE_XFER: case CC_FEATURE_HOLD: - case CC_FEATURE_CREATEANSWER: case CC_FEATURE_SETLOCALDESC: case CC_FEATURE_SETREMOTEDESC: case CC_FEATURE_SETPEERCONNECTION: @@ -304,12 +303,12 @@ cc_return_t CC_CallFeature_CreateOffer(cc_call_handle_t call_handle, const cc_me 0, 0, NO_STREAM, 0, constraints, NULL, NULL); } -cc_return_t CC_CallFeature_CreateAnswer(cc_call_handle_t call_handle, const cc_media_constraints_t *constraints, string_t sdp) { +cc_return_t CC_CallFeature_CreateAnswer(cc_call_handle_t call_handle, const cc_media_constraints_t *constraints) { CCAPP_DEBUG(DEB_L_C_F_PREFIX, DEB_L_C_F_PREFIX_ARGS(SIP_CC_PROV, GET_CALL_ID(call_handle), GET_LINE_ID(call_handle), __FUNCTION__)); return cc_invokeFeatureSDPMode(call_handle, CC_FEATURE_CREATEANSWER, JSEP_NO_ACTION, - 0, 0, NO_STREAM, 0, constraints, sdp, NULL); + 0, 0, NO_STREAM, 0, constraints, NULL, NULL); } cc_return_t CC_CallFeature_SetLocalDescription(cc_call_handle_t call_handle, cc_jsep_action_t action, string_t sdp) { diff --git a/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call.c b/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call.c index 6c41ecbc5d9..8af71980338 100644 --- a/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call.c +++ b/media/webrtc/signaling/src/sipcc/core/ccapp/ccapi_call.c @@ -94,8 +94,8 @@ cc_return_t CCAPI_CreateOffer(cc_call_handle_t handle, const cc_media_constraint return CC_CallFeature_CreateOffer(handle, constraints); } -cc_return_t CCAPI_CreateAnswer(cc_call_handle_t handle, const cc_media_constraints_t *constraints, cc_string_t offersdp) { - return CC_CallFeature_CreateAnswer(handle, constraints, offersdp); +cc_return_t CCAPI_CreateAnswer(cc_call_handle_t handle, const cc_media_constraints_t *constraints) { + return CC_CallFeature_CreateAnswer(handle, constraints); } cc_return_t CCAPI_SetLocalDescription(cc_call_handle_t handle, cc_jsep_action_t action, cc_string_t sdp) { diff --git a/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c b/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c index 6bb304f04fe..1ab223d2358 100644 --- a/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c +++ b/media/webrtc/signaling/src/sipcc/core/gsm/gsm_sdp.c @@ -1587,9 +1587,8 @@ gsmsdp_set_dtls_fingerprint_attribute (sdp_attr_e sdp_attr, uint16_t level, void sdp_result_e result; char hash_and_fingerprint[FSMDEF_MAX_DIGEST_ALG_LEN + FSMDEF_MAX_DIGEST_LEN + 2]; - sstrncpy(hash_and_fingerprint, (cc_string_t)hash_func, FSMDEF_MAX_DIGEST_ALG_LEN); - sstrncat(hash_and_fingerprint, (cc_string_t)" ", sizeof(hash_and_fingerprint) - strlen(hash_and_fingerprint) - 1); - sstrncat(hash_and_fingerprint, (cc_string_t)fingerprint, FSMDEF_MAX_DIGEST_LEN); + snprintf(hash_and_fingerprint, sizeof(hash_and_fingerprint), + "%s %s", hash_func, fingerprint); result = sdp_add_new_attr(sdp_p, level, 0, sdp_attr, &a_instance); if (result != SDP_SUCCESS) { diff --git a/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h b/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h index 38cb3cd47af..e1fbb26f21e 100644 --- a/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h +++ b/media/webrtc/signaling/src/sipcc/include/cc_call_feature.h @@ -153,7 +153,7 @@ cc_return_t CC_CallFeature_dial(cc_call_handle_t call_handle, cc_sdp_direction_t cc_return_t CC_CallFeature_CreateOffer(cc_call_handle_t call_handle, const cc_media_constraints_t *constraints); -cc_return_t CC_CallFeature_CreateAnswer(cc_call_handle_t call_handle, const cc_media_constraints_t *constraints, const char* sdp); +cc_return_t CC_CallFeature_CreateAnswer(cc_call_handle_t call_handle, const cc_media_constraints_t *constraints); cc_return_t CC_CallFeature_SetLocalDescription(cc_call_handle_t call_handle, cc_jsep_action_t action, const char* sdp); diff --git a/media/webrtc/signaling/src/sipcc/include/ccapi_call.h b/media/webrtc/signaling/src/sipcc/include/ccapi_call.h index 37d08f71ebb..764838d4747 100644 --- a/media/webrtc/signaling/src/sipcc/include/ccapi_call.h +++ b/media/webrtc/signaling/src/sipcc/include/ccapi_call.h @@ -50,7 +50,7 @@ cc_return_t CCAPI_Call_originateCall(cc_call_handle_t handle, cc_sdp_direction_t cc_return_t CCAPI_CreateOffer(cc_call_handle_t handle, const cc_media_constraints_t *constraints); -cc_return_t CCAPI_CreateAnswer(cc_call_handle_t handle, const cc_media_constraints_t *constraints, cc_string_t offersdp); +cc_return_t CCAPI_CreateAnswer(cc_call_handle_t handle, const cc_media_constraints_t *constraints); cc_return_t CCAPI_SetLocalDescription(cc_call_handle_t handle, cc_jsep_action_t action, cc_string_t sdp); diff --git a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.cpp b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.cpp index d133f3fd384..6bd90351295 100644 --- a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.cpp +++ b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.cpp @@ -534,8 +534,9 @@ void CC_SIPCCCall::createOffer (const cc_media_constraints_t *constraints) { /* * This method works asynchronously, there is onCallEvent with the resulting SDP */ -void CC_SIPCCCall::createAnswer (const cc_media_constraints_t *constraints, const std::string & offersdp) { - CCAPI_CreateAnswer(callHandle, constraints, offersdp.c_str()); +void CC_SIPCCCall::createAnswer (const cc_media_constraints_t *constraints) { + CCAPI_CreateAnswer(callHandle, constraints); + } void CC_SIPCCCall::setLocalDescription(cc_jsep_action_t action, const std::string & sdp) { diff --git a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.h b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.h index 17adcce8174..aaa7b1c2438 100644 --- a/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.h +++ b/media/webrtc/signaling/src/softphonewrapper/CC_SIPCCCall.h @@ -111,7 +111,7 @@ namespace CSF virtual bool setVolume(int volume); virtual void originateP2PCall (cc_sdp_direction_t video_pref, const std::string & digits, const std::string & ip); virtual void createOffer(const cc_media_constraints_t *constraints); - virtual void createAnswer(const cc_media_constraints_t *constraints, const std::string & offersdp); + virtual void createAnswer(const cc_media_constraints_t *constraints); virtual void setLocalDescription(cc_jsep_action_t action, const std::string & sdp); virtual void setRemoteDescription(cc_jsep_action_t action, const std::string & sdp); virtual void setPeerConnection(const std::string& handle); diff --git a/media/webrtc/signaling/test/signaling_unittests.cpp b/media/webrtc/signaling/test/signaling_unittests.cpp index 6ab6066a168..ba14d4a9841 100644 --- a/media/webrtc/signaling/test/signaling_unittests.cpp +++ b/media/webrtc/signaling/test/signaling_unittests.cpp @@ -524,7 +524,7 @@ class SignalingAgent { ASSERT_TRUE_WAIT(pObserver->state == TestObserver::stateError, kDefaultTimeout); } - void CreateAnswer(sipcc::MediaConstraints& constraints, std::string offer, bool audio, bool video) { + void CreateAnswer(sipcc::MediaConstraints& constraints, bool audio, bool video) { // Create a media stream as if it came from GUM nsRefPtr domMediaStream = new nsDOMMediaStream(); @@ -544,7 +544,7 @@ class SignalingAgent { pc->AddStream(domMediaStream); pObserver->state = TestObserver::stateNoResponse; - ASSERT_EQ(pc->CreateAnswer(constraints, offer.c_str()), NS_OK); + ASSERT_EQ(pc->CreateAnswer(constraints, NS_OK); ASSERT_TRUE_WAIT(pObserver->state == TestObserver::stateSuccess, kDefaultTimeout); SDPSanityCheck(pObserver->lastString, audio, video, false); answer_ = pObserver->lastString; @@ -680,7 +680,7 @@ public: a1_.CreateOffer(aconstraints, audio, video); a1_.SetLocal(TestObserver::OFFER, a1_.offer()); a2_.SetRemote(TestObserver::OFFER, a1_.offer()); - a2_.CreateAnswer(bconstraints, a1_.offer(), audio, video); + a2_.CreateAnswer(bconstraints, audio, video); if(true == finishAfterAnswer) { a2_.SetLocal(TestObserver::ANSWER, a2_.answer()); a1_.SetRemote(TestObserver::ANSWER, a2_.answer()); @@ -694,7 +694,7 @@ public: a1_.CreateOffer(aconstraints, true, true); a1_.SetLocal(TestObserver::OFFER, a1_.offer()); a2_.SetRemote(TestObserver::OFFER, a1_.offer()); - a2_.CreateAnswer(bconstraints, a1_.offer(), true, true); + a2_.CreateAnswer(bconstraints, true, true); a2_.SetLocal(TestObserver::ANSWER, a2_.answer()); ParsedSDP sdpWrapper(a2_.answer()); sdpWrapper.ReplaceLine("m=audio", "m=audio 65375 RTP/SAVPF 109 8 101\r\n"); @@ -710,7 +710,7 @@ public: a1_.SetLocal(TestObserver::OFFER, a1_.offer()); ParsedSDP a1_offer(a1_.offer()); a2_.SetRemote(TestObserver::OFFER, a1_offer.sdp_without_ice_); - a2_.CreateAnswer(bconstraints, a1_offer.sdp_without_ice_, true, true); + a2_.CreateAnswer(bconstraints, true, true); a2_.SetLocal(TestObserver::ANSWER, a2_.answer()); ParsedSDP a2_answer(a2_.answer()); a1_.SetRemote(TestObserver::ANSWER, a2_answer.sdp_without_ice_); diff --git a/mobile/android/app/mobile.js b/mobile/android/app/mobile.js index 069d24f47cb..6d9cc57905a 100644 --- a/mobile/android/app/mobile.js +++ b/mobile/android/app/mobile.js @@ -343,7 +343,7 @@ pref("gfx.displayport.strategy_vb.danger_y_incr", -1); // additional danger zone // prediction bias strategy options pref("gfx.displayport.strategy_pb.threshold", -1); // velocity threshold in inches/frame -pref("gfx.java.screenshot.enabled", true); +pref("gfx.java.screenshot.enabled", false); // don't allow JS to move and resize existing windows pref("dom.disable_window_move_resize", true); @@ -522,7 +522,7 @@ pref("ui.dragThresholdY", 25); pref("layers.acceleration.disabled", false); pref("layers.offmainthreadcomposition.enabled", true); pref("layers.async-video.enabled", true); -pref("layers.progressive-paint", false); +pref("layers.progressive-paint", true); pref("notification.feature.enabled", true); @@ -632,8 +632,6 @@ pref("ui.scrolling.min_scrollable_distance", -1); // Enable accessibility mode if platform accessibility is enabled. pref("accessibility.accessfu.activate", 2); -// Enable explore by touch if it is enabled in the platform -pref("accessibility.accessfu.explorebytouch", 2); // Mobile manages state by autodetection pref("network.manage-offline-status", true); diff --git a/mobile/android/base/GeckoApp.java b/mobile/android/base/GeckoApp.java index 6376165eb60..03c36421f49 100644 --- a/mobile/android/base/GeckoApp.java +++ b/mobile/android/base/GeckoApp.java @@ -297,8 +297,6 @@ abstract public class GeckoApp } } - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - start of getPluginDirectories"); - ArrayList directories = new ArrayList(); PackageManager pm = mAppContext.getPackageManager(); List plugins = pm.queryIntentServices(new Intent(PLUGIN_ACTION), @@ -315,7 +313,7 @@ abstract public class GeckoApp // retrieve the plugin's service information ServiceInfo serviceInfo = info.serviceInfo; if (serviceInfo == null) { - Log.w(LOGTAG, "Ignore bad plugin"); + Log.w(LOGTAG, "Ignoring bad plugin."); continue; } @@ -327,10 +325,8 @@ abstract public class GeckoApp continue; } - Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName); - - // retrieve information from the plugin's manifest + // Retrieve information from the plugin's manifest. PackageInfo pkgInfo; try { pkgInfo = pm.getPackageInfo(serviceInfo.packageName, @@ -340,8 +336,9 @@ abstract public class GeckoApp Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName); continue; } + if (pkgInfo == null) { - Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Could not load package information."); + Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Could not load package information."); continue; } @@ -355,6 +352,7 @@ abstract public class GeckoApp final int appFlags = pkgInfo.applicationInfo.flags; final int updatedSystemFlags = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; + // preloaded system app with no user updates if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) { directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName; @@ -363,7 +361,7 @@ abstract public class GeckoApp // check if the plugin has the required permissions String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { - Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission."); + Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Does not have required permission."); continue; } boolean permissionOk = false; @@ -374,20 +372,20 @@ abstract public class GeckoApp } } if (!permissionOk) { - Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2)."); + Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2)."); continue; } // check to ensure the plugin is properly signed Signature signatures[] = pkgInfo.signatures; if (signatures == null) { - Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed."); + Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Not signed."); continue; } // determine the type of plugin from the manifest if (serviceInfo.metaData == null) { - Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined"); + Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no defined type."); continue; } @@ -422,9 +420,7 @@ abstract public class GeckoApp } } - String [] result = directories.toArray(new String[directories.size()]); - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - end of getPluginDirectories"); - return result; + return directories.toArray(new String[directories.size()]); } String getPluginPackage(String pluginLib) { @@ -699,8 +695,6 @@ abstract public class GeckoApp protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - Log.i(LOGTAG, "onSaveInstanceState"); - if (outState == null) outState = new Bundle(); @@ -745,7 +739,7 @@ abstract public class GeckoApp try { if (bitmap == null) { if (compressed == null) { - Log.e(LOGTAG, "processThumbnail: one of bitmap or compressed must be non-null!"); + Log.w(LOGTAG, "processThumbnail: one of bitmap or compressed must be non-null!"); return; } bitmap = BitmapFactory.decodeByteArray(compressed, 0, compressed.length); @@ -797,7 +791,7 @@ abstract public class GeckoApp args.put("url", url); args.put("faviconUrl", faviconUrl); } catch (JSONException e) { - Log.e(LOGTAG, "error building json arguments"); + Log.w(LOGTAG, "Error building JSON favicon arguments.", e); } } @@ -826,9 +820,11 @@ abstract public class GeckoApp getFavicons().clearFavicons(); } + /** + * This function might perform synchronous IO. Don't call it + * from the main thread. + */ public StartupMode getStartupMode() { - // This function might touch the disk and should not - // be called from UI's main thread. synchronized(this) { if (mStartupMode != null) @@ -908,7 +904,6 @@ abstract public class GeckoApp } public void handleMessage(String event, JSONObject message) { - Log.i(LOGTAG, "Got message: " + event); try { if (event.equals("Toast:Show")) { final String msg = message.getString("message"); @@ -948,7 +943,7 @@ abstract public class GeckoApp } else if (event.equals("log")) { // generic log listener final String msg = message.getString("msg"); - Log.i(LOGTAG, "Log: " + msg); + Log.d(LOGTAG, "Log: " + msg); } else if (event.equals("Content:SecurityChange")) { final int tabId = message.getInt("tabID"); final JSONObject identity = message.getJSONObject("identity"); @@ -967,14 +962,14 @@ abstract public class GeckoApp final String uri = message.getString("uri"); final boolean success = message.getBoolean("success"); int state = message.getInt("state"); - Log.i(LOGTAG, "State - " + state); + Log.d(LOGTAG, "State - " + state); if ((state & GeckoAppShell.WPL_STATE_IS_NETWORK) != 0) { if ((state & GeckoAppShell.WPL_STATE_START) != 0) { - Log.i(LOGTAG, "Got a document start"); + Log.d(LOGTAG, "Got a document start event."); final boolean showProgress = message.getBoolean("showProgress"); handleDocumentStart(tabId, showProgress, uri); } else if ((state & GeckoAppShell.WPL_STATE_STOP) != 0) { - Log.i(LOGTAG, "Got a document stop"); + Log.d(LOGTAG, "Got a document stop event."); handleDocumentStop(tabId, success); } } @@ -1109,7 +1104,6 @@ abstract public class GeckoApp } public String getResponse() { - Log.i(LOGTAG, "Return " + mCurrentResponse); String res = mCurrentResponse; mCurrentResponse = ""; return res; @@ -1141,12 +1135,11 @@ abstract public class GeckoApp boolean[] states = new boolean[aPermissions.length()]; for (int i = 0; i < aPermissions.length(); i++) { try { - items[i] = aPermissions.getJSONObject(i). - getString("setting"); - // Make all the items checked by default + items[i] = aPermissions.getJSONObject(i).getString("setting"); + // Make all the items checked by default. states[i] = true; } catch (JSONException e) { - Log.i(LOGTAG, "JSONException", e); + Log.w(LOGTAG, "Exception populating settings items.", e); } } builder.setMultiChoiceItems(items, states, new DialogInterface.OnMultiChoiceClickListener(){ @@ -1498,7 +1491,6 @@ abstract public class GeckoApp } mMainHandler = new Handler(); - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - onCreate"); LayoutInflater.from(this).setFactory(GeckoViewsFactory.getInstance()); @@ -1519,12 +1511,10 @@ abstract public class GeckoApp // we were in the background, or a more harsh kill while we were // active if (savedInstanceState != null) { - Log.i(LOGTAG, "Restoring from OOM"); mRestoreMode = GeckoAppShell.RESTORE_OOM; boolean wasInBackground = savedInstanceState.getBoolean(SAVED_STATE_IN_BACKGROUND, false); - Log.i(LOGTAG, "Was in background: " + wasInBackground); // Don't log OOM-kills if only one activity was destroyed. (For example // from "Don't keep activities" on ICS) @@ -1543,7 +1533,6 @@ abstract public class GeckoApp boolean wasOOM = prefs.getBoolean(PREFS_OOM_EXCEPTION, false); boolean wasStopped = prefs.getBoolean(PREFS_WAS_STOPPED, true); if (wasOOM || !wasStopped) { - Log.i(LOGTAG, "Crashed due to OOM last run"); Telemetry.HistogramAdd("FENNEC_WAS_KILLED", 1); } SharedPreferences.Editor editor = prefs.edit(); @@ -1607,7 +1596,6 @@ abstract public class GeckoApp } if (mRestoreMode == GeckoAppShell.RESTORE_NONE && getProfile().shouldRestoreSession()) { - Log.i(LOGTAG, "Restoring crash"); mRestoreMode = GeckoAppShell.RESTORE_CRASH; } @@ -1663,12 +1651,10 @@ abstract public class GeckoApp checkAndSetLaunchState(LaunchState.Launching, LaunchState.WaitForDebugger)) { mMainHandler.postDelayed(new Runnable() { public void run() { - Log.i(LOGTAG, "Launching from debug intent after 5s wait"); setLaunchState(LaunchState.Launching); sGeckoThread.start(); } }, 1000 * 5 /* 5 seconds */); - Log.i(LOGTAG, "Intent : ACTION_DEBUG - waiting 5s before launching"); } if (cameraView == null) { @@ -1685,8 +1671,6 @@ abstract public class GeckoApp mPluginContainer = (AbsoluteLayout) findViewById(R.id.plugin_container); mFormAssistPopup = (FormAssistPopup) findViewById(R.id.form_assist_popup); - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - UI almost up"); - //register for events registerEventListener("DOMContentLoaded"); registerEventListener("DOMTitleChanged"); @@ -1752,7 +1736,6 @@ abstract public class GeckoApp GeckoAppShell.getHandler().postDelayed(new Runnable() { public void run() { - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - pre checkLaunchState"); // Sync settings need Gecko to be loaded, so // no hurry in starting this. checkMigrateSync(); @@ -1760,7 +1743,6 @@ abstract public class GeckoApp // Kick off our background service to fetch product announcements. // We do this by invoking the broadcast receiver, which uses the // system alarm infrastructure to perform tasks at intervals. - Log.d(LOGTAG, "Broadcasting announcements pref."); GeckoPreferences.broadcastAnnouncementsPref(GeckoApp.mAppContext); /* @@ -1887,7 +1869,7 @@ abstract public class GeckoApp mIntent.putExtra("prefetched", 1); } } catch (IOException ioe) { - Log.i(LOGTAG, "exception trying to pre-fetch redirected url", ioe); + Log.w(LOGTAG, "Exception trying to pre-fetch redirected URL.", ioe); mIntent.putExtra("prefetched", 1); } } @@ -1921,8 +1903,6 @@ abstract public class GeckoApp @Override protected void onNewIntent(Intent intent) { - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - onNewIntent"); - if (checkLaunchState(LaunchState.GeckoExiting)) { // We're exiting and shouldn't try to do anything else just incase // we're hung for some reason we'll force the process to exit @@ -1962,7 +1942,6 @@ abstract public class GeckoApp final String action = intent.getAction(); if (Intent.ACTION_MAIN.equals(action)) { - Log.i(LOGTAG, "Intent : ACTION_MAIN"); GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent("")); } else if (ACTION_LOAD.equals(action)) { @@ -2029,8 +2008,6 @@ abstract public class GeckoApp @Override public void onResume() { - Log.i(LOGTAG, "resume"); - // After an onPause, the activity is back in the foreground. // Undo whatever we did in onPause. super.onResume(); @@ -2071,7 +2048,6 @@ abstract public class GeckoApp @Override public void onStop() { - Log.i(LOGTAG, "stop"); // We're about to be stopped, potentially in preparation for // being destroyed. We're killable after this point -- as I // understand it, in extreme cases the process can be terminated @@ -2090,8 +2066,6 @@ abstract public class GeckoApp @Override public void onPause() { - Log.i(LOGTAG, "pause"); - // In some way it's sad that Android will trigger StrictMode warnings // here as the whole point is to save to disk while the activity is not // interacting with the user. @@ -2116,8 +2090,6 @@ abstract public class GeckoApp @Override public void onRestart() { - Log.i(LOGTAG, "restart"); - GeckoBackgroundThread.getHandler().post(new Runnable() { public void run() { SharedPreferences prefs = @@ -2134,9 +2106,6 @@ abstract public class GeckoApp @Override public void onStart() { - Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - onStart"); - - Log.i(LOGTAG, "start"); GeckoAppShell.sendEventToGecko(GeckoEvent.createStartEvent(isApplicationInBackground())); super.onStart(); } @@ -2144,8 +2113,6 @@ abstract public class GeckoApp @Override public void onDestroy() { - Log.i(LOGTAG, "destroy"); - // Tell Gecko to shutting down; we'll end up calling System.exit() // in onXreExit. if (isFinishing()) @@ -2256,10 +2223,7 @@ abstract public class GeckoApp @Override - public void onConfigurationChanged(Configuration newConfig) - { - Log.i(LOGTAG, "configuration changed"); - + public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mOrientation != newConfig.orientation) { @@ -2299,7 +2263,7 @@ abstract public class GeckoApp } public void doRestart(String action) { - Log.i(LOGTAG, "doRestart(\"" + action + "\")"); + Log.d(LOGTAG, "doRestart(\"" + action + "\")"); try { Intent intent = new Intent(action); intent.setClassName(getPackageName(), @@ -2307,11 +2271,11 @@ abstract public class GeckoApp /* TODO: addEnvToIntent(intent); */ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); - Log.i(LOGTAG, intent.toString()); + Log.d(LOGTAG, "Restart intent: " + intent.toString()); GeckoAppShell.killAnyZombies(); startActivity(intent); } catch (Exception e) { - Log.e(LOGTAG, "error doing restart", e); + Log.e(LOGTAG, "Error effecting restart.", e); } finish(); // Give the restart process time to start before we die @@ -2324,15 +2288,12 @@ abstract public class GeckoApp private void checkMigrateProfile() { final File profileDir = getProfile().getDir(); - final long currentTime = SystemClock.uptimeMillis(); if (profileDir != null) { final GeckoApp app = GeckoApp.mAppContext; GeckoAppShell.getHandler().post(new Runnable() { public void run() { - Log.i(LOGTAG, "Checking profile migration in: " + profileDir.getAbsolutePath()); - ProfileMigrator profileMigrator = new ProfileMigrator(app); // Do a migration run on the first start after an upgrade. @@ -2340,13 +2301,20 @@ abstract public class GeckoApp !profileMigrator.hasMigrationRun()) { // Show the "Setting up Fennec" screen if this takes // a while. - final SetupScreen setupScreen = new SetupScreen(app); + + // Create a "final" holder for the setup screen so that we can + // create it in startCallback and still find a reference to it + // in stopCallback. (We must create it on the UI thread to fix + // bug 788216). Note that synchronization is not a problem here + // since it is only ever touched on the UI thread. + final SetupScreen[] setupScreenHolder = new SetupScreen[1]; final Runnable startCallback = new Runnable() { public void run() { GeckoApp.mAppContext.runOnUiThread(new Runnable() { public void run() { - setupScreen.show(); + setupScreenHolder[0] = new SetupScreen(app); + setupScreenHolder[0].show(); } }); } @@ -2356,7 +2324,12 @@ abstract public class GeckoApp public void run() { GeckoApp.mAppContext.runOnUiThread(new Runnable() { public void run() { - setupScreen.dismiss(); + SetupScreen screen = setupScreenHolder[0]; + // screen will never be null if this code runs, but + // stranger things have happened... + if (screen != null) { + screen.dismiss(); + } } }); } @@ -2365,10 +2338,6 @@ abstract public class GeckoApp profileMigrator.setLongOperationCallbacks(startCallback, stopCallback); profileMigrator.launchPlaces(profileDir); - - long timeDiff = SystemClock.uptimeMillis() - currentTime; - Log.i(LOGTAG, "Profile migration took " + timeDiff + " ms"); - finishProfileMigration(); } }} @@ -2385,7 +2354,6 @@ abstract public class GeckoApp final GeckoApp app = GeckoApp.mAppContext; ProfileMigrator profileMigrator = new ProfileMigrator(app); if (!profileMigrator.hasSyncMigrated()) { - Log.i(LOGTAG, "Checking Sync settings in: " + profileDir.getAbsolutePath()); profileMigrator.launchSyncPrefs(); } } @@ -2508,18 +2476,17 @@ abstract public class GeckoApp public AbsoluteLayout getPluginContainer() { return mPluginContainer; } - // accelerometer - public void onAccuracyChanged(Sensor sensor, int accuracy) {} + // Accelerometer. + public void onAccuracyChanged(Sensor sensor, int accuracy) { + } - public void onSensorChanged(SensorEvent event) - { + public void onSensorChanged(SensorEvent event) { GeckoAppShell.sendEventToGecko(GeckoEvent.createSensorEvent(event)); } - // geolocation - public void onLocationChanged(Location location) - { - Log.w(LOGTAG, "onLocationChanged "+location); + // Geolocation. + public void onLocationChanged(Location location) { + // No logging here: user-identifying information. GeckoAppShell.sendEventToGecko(GeckoEvent.createLocationEvent(location)); } diff --git a/mobile/android/chrome/content/browser.js b/mobile/android/chrome/content/browser.js index dbaf5033417..a188c6645c3 100644 --- a/mobile/android/chrome/content/browser.js +++ b/mobile/android/chrome/content/browser.js @@ -3589,13 +3589,19 @@ var BrowserEventHandler = { }, handleEvent: function(aEvent) { - if (aEvent.type && (aEvent.type === "MozMagnifyGesture" || - aEvent.type === "MozMagnifyGestureUpdate" || - aEvent.type === "MozMagnifyGestureStart")) { - this.observe(this, aEvent.type, JSON.stringify({x: aEvent.screenX, y: aEvent.screenY})); - return; + switch (aEvent.type) { + case 'touchstart': + this._handleTouchStart(aEvent); + break; + case 'MozMagnifyGesture': + case 'MozMagnifyGestureUpdate': + case 'MozMagnifyGestureStart': + this.observe(this, aEvent.type, JSON.stringify({x: aEvent.screenX, y: aEvent.screenY})); + break; } + }, + _handleTouchStart: function(aEvent) { if (!BrowserApp.isBrowserContentDocumentDisplayed() || aEvent.touches.length > 1 || aEvent.defaultPrevented) return; @@ -3790,43 +3796,50 @@ var BrowserEventHandler = { if (!element) { this._zoomOut(); } else { - const margin = 15; - let rect = ElementTouchHelper.getBoundingContentRect(element); + this._zoomToElement(element, data.y); + } + }, - let viewport = BrowserApp.selectedTab.getViewport(); - let bRect = new Rect(Math.max(viewport.cssPageLeft, rect.x - margin), - rect.y, - rect.w + 2 * margin, - rect.h); - // constrict the rect to the screen's right edge - bRect.width = Math.min(bRect.width, viewport.cssPageRight - bRect.x); + /* Zoom to an element, optionally keeping a particular part of it + * in view if it is really tall. + */ + _zoomToElement: function(aElement, aClickY = -1) { + const margin = 15; + let rect = ElementTouchHelper.getBoundingContentRect(aElement); - // if the rect is already taking up most of the visible area and is stretching the - // width of the page, then we want to zoom out instead. - if (this._isRectZoomedIn(bRect, viewport)) { - this._zoomOut(); - return; - } + let viewport = BrowserApp.selectedTab.getViewport(); + let bRect = new Rect(Math.max(viewport.cssPageLeft, rect.x - margin), + rect.y, + rect.w + 2 * margin, + rect.h); + // constrict the rect to the screen's right edge + bRect.width = Math.min(bRect.width, viewport.cssPageRight - bRect.x); - rect.type = "Browser:ZoomToRect"; - rect.x = bRect.x; - rect.y = bRect.y; - rect.w = bRect.width; - rect.h = Math.min(bRect.width * viewport.cssHeight / viewport.cssWidth, bRect.height); + // if the rect is already taking up most of the visible area and is stretching the + // width of the page, then we want to zoom out instead. + if (this._isRectZoomedIn(bRect, viewport)) { + this._zoomOut(); + return; + } - // if the block we're zooming to is really tall, and the user double-tapped - // more than a screenful of height from the top of it, then adjust the y-coordinate - // so that we center the actual point the user double-tapped upon. this prevents - // flying to the top of a page when double-tapping to zoom in (bug 761721). + rect.type = "Browser:ZoomToRect"; + rect.x = bRect.x; + rect.y = bRect.y; + rect.w = bRect.width; + rect.h = Math.min(bRect.width * viewport.cssHeight / viewport.cssWidth, bRect.height); + + if (aClickY >= 0) { + // if the block we're zooming to is really tall, and we want to keep a particular + // part of it in view, then adjust the y-coordinate of the target rect accordingly. // the 1.2 multiplier is just a little fuzz to compensate for bRect including horizontal // margins but not vertical ones. - let cssTapY = viewport.cssY + data.y; + let cssTapY = viewport.cssY + aClickY; if ((bRect.height > rect.h) && (cssTapY > rect.y + (rect.h * 1.2))) { rect.y = cssTapY - (rect.h / 2); } - - sendMessageToJava({ gecko: rect }); } + + sendMessageToJava({ gecko: rect }); }, _zoomInAndSnapToElement: function(aX, aY, aElement) { diff --git a/netwerk/base/public/nsNetUtil.h b/netwerk/base/public/nsNetUtil.h index d4778fbdf09..d4f8ad36430 100644 --- a/netwerk/base/public/nsNetUtil.h +++ b/netwerk/base/public/nsNetUtil.h @@ -1336,8 +1336,6 @@ NS_GetAppInfo(nsIChannel *aChannel, uint32_t *aAppID, bool *aIsInBrowserElement) return true; } -#define TOPIC_WEB_APP_CLEAR_DATA "webapps-clear-data" - /** * Gets appId and browserOnly parameters from the TOPIC_WEB_APP_CLEAR_DATA * nsIObserverService notification. Used when clearing user data or @@ -1359,10 +1357,9 @@ NS_GetAppInfoFromClearDataNotification(nsISupports *aSubject, uint32_t appId; rv = clearParams->GetAppId(&appId); MOZ_ASSERT(NS_SUCCEEDED(rv)); - MOZ_ASSERT(appId != NECKO_NO_APP_ID); MOZ_ASSERT(appId != NECKO_UNKNOWN_APP_ID); NS_ENSURE_SUCCESS(rv, rv); - if (appId == NECKO_NO_APP_ID || appId == NECKO_UNKNOWN_APP_ID) { + if (appId == NECKO_UNKNOWN_APP_ID) { return NS_ERROR_UNEXPECTED; } diff --git a/netwerk/cookie/nsCookieService.cpp b/netwerk/cookie/nsCookieService.cpp index 8aed1db5e77..c5c2156d7e2 100644 --- a/netwerk/cookie/nsCookieService.cpp +++ b/netwerk/cookie/nsCookieService.cpp @@ -3816,8 +3816,7 @@ nsCookieService::GetCookiesForApp(uint32_t aAppId, bool aOnlyBrowserElement, return NS_ERROR_NOT_AVAILABLE; } - NS_ENSURE_TRUE(aAppId != NECKO_NO_APP_ID && aAppId != NECKO_UNKNOWN_APP_ID, - NS_ERROR_INVALID_ARG); + NS_ENSURE_TRUE(aAppId != NECKO_UNKNOWN_APP_ID, NS_ERROR_INVALID_ARG); GetCookiesForAppStruct data(aAppId, aOnlyBrowserElement); mDBState->hostTable.EnumerateEntries(GetCookiesForApp, &data); diff --git a/security/manager/boot/src/nsBOOTModule.cpp b/security/manager/boot/src/nsBOOTModule.cpp index 059606341c7..b48253746ee 100644 --- a/security/manager/boot/src/nsBOOTModule.cpp +++ b/security/manager/boot/src/nsBOOTModule.cpp @@ -21,11 +21,11 @@ NS_DEFINE_NAMED_CID(NS_SECURE_BROWSER_UI_CID); NS_DEFINE_NAMED_CID(NS_STRICT_TRANSPORT_SECURITY_CID); static const mozilla::Module::CIDEntry kBOOTCIDs[] = { - { &kNS_ENTROPYCOLLECTOR_CID, false, nullptr, nsEntropyCollectorConstructor }, - { &kNS_SECURITYWARNINGDIALOGS_CID, false, nullptr, nsSecurityWarningDialogsConstructor }, - { &kNS_SECURE_BROWSER_UI_CID, false, nullptr, nsSecureBrowserUIImplConstructor }, - { &kNS_STRICT_TRANSPORT_SECURITY_CID, false, nullptr, nsStrictTransportSecurityServiceConstructor }, - { nullptr } + { &kNS_ENTROPYCOLLECTOR_CID, false, NULL, nsEntropyCollectorConstructor }, + { &kNS_SECURITYWARNINGDIALOGS_CID, false, NULL, nsSecurityWarningDialogsConstructor }, + { &kNS_SECURE_BROWSER_UI_CID, false, NULL, nsSecureBrowserUIImplConstructor }, + { &kNS_STRICT_TRANSPORT_SECURITY_CID, false, NULL, nsStrictTransportSecurityServiceConstructor }, + { NULL } }; static const mozilla::Module::ContractIDEntry kBOOTContracts[] = { @@ -33,7 +33,7 @@ static const mozilla::Module::ContractIDEntry kBOOTContracts[] = { { NS_SECURITYWARNINGDIALOGS_CONTRACTID, &kNS_SECURITYWARNINGDIALOGS_CID }, { NS_SECURE_BROWSER_UI_CONTRACTID, &kNS_SECURE_BROWSER_UI_CID }, { NS_STSSERVICE_CONTRACTID, &kNS_STRICT_TRANSPORT_SECURITY_CID }, - { nullptr } + { NULL } }; static const mozilla::Module kBootModule = { diff --git a/security/manager/boot/src/nsEntropyCollector.cpp b/security/manager/boot/src/nsEntropyCollector.cpp index 419954f93d2..c39c4a37507 100644 --- a/security/manager/boot/src/nsEntropyCollector.cpp +++ b/security/manager/boot/src/nsEntropyCollector.cpp @@ -5,6 +5,7 @@ #include "prlog.h" #include "nsEntropyCollector.h" +#include "nsMemory.h" #include "nsAlgorithm.h" nsEntropyCollector::nsEntropyCollector() diff --git a/security/manager/boot/src/nsSecurityWarningDialogs.cpp b/security/manager/boot/src/nsSecurityWarningDialogs.cpp index ac1ffa1b75d..3df006b36b1 100644 --- a/security/manager/boot/src/nsSecurityWarningDialogs.cpp +++ b/security/manager/boot/src/nsSecurityWarningDialogs.cpp @@ -15,6 +15,7 @@ #include "nsIPrefService.h" #include "nsIPrefBranch.h" #include "nsThreadUtils.h" +#include "nsAutoPtr.h" #include "mozilla/Telemetry.h" #include "nsISecurityUITelemetry.h" @@ -263,7 +264,7 @@ nsSecurityWarningDialogs::ConfirmDialog(nsIInterfaceRequestor *ctx, const char * // prefName, showAgainName are null if there is no preference for this dialog bool prefValue = true; - if (prefName) { + if (prefName != nullptr) { rv = mPrefBranch->GetBoolPref(prefName, &prefValue); if (NS_FAILED(rv)) prefValue = true; } @@ -297,7 +298,7 @@ nsSecurityWarningDialogs::ConfirmDialog(nsIInterfaceRequestor *ctx, const char * getter_Copies(windowTitle)); mStringBundle->GetStringFromName(messageName, getter_Copies(message)); - if (showAgainName) { + if (showAgainName != nullptr) { mStringBundle->GetStringFromName(showAgainName, getter_Copies(alertMe)); } @@ -338,7 +339,7 @@ nsSecurityWarningDialogs::ConfirmDialog(nsIInterfaceRequestor *ctx, const char * mozilla::Telemetry::Accumulate(mozilla::Telemetry::SECURITY_UI, aBucket + 1); } - if (!prefValue && prefName) { + if (!prefValue && prefName != nullptr) { mPrefBranch->SetBoolPref(prefName, false); } else if (prefValue && showOnce) { mPrefBranch->SetBoolPref(showOncePref.get(), false); diff --git a/security/manager/pki/src/nsPKIModule.cpp b/security/manager/pki/src/nsPKIModule.cpp index 61ef325bb4c..ed57a11dfb2 100644 --- a/security/manager/pki/src/nsPKIModule.cpp +++ b/security/manager/pki/src/nsPKIModule.cpp @@ -24,11 +24,11 @@ NS_DEFINE_NAMED_CID(NS_FORMSIGNINGDIALOG_CID); static const mozilla::Module::CIDEntry kPKICIDs[] = { - { &kNS_NSSDIALOGS_CID, false, nullptr, nsNSSDialogsConstructor }, - { &kNS_NSSASN1OUTINER_CID, false, nullptr, nsNSSASN1TreeConstructor }, - { &kNS_PKIPARAMBLOCK_CID, false, nullptr, nsPKIParamBlockConstructor }, - { &kNS_FORMSIGNINGDIALOG_CID, false, nullptr, nsFormSigningDialogConstructor }, - { nullptr } + { &kNS_NSSDIALOGS_CID, false, NULL, nsNSSDialogsConstructor }, + { &kNS_NSSASN1OUTINER_CID, false, NULL, nsNSSASN1TreeConstructor }, + { &kNS_PKIPARAMBLOCK_CID, false, NULL, nsPKIParamBlockConstructor }, + { &kNS_FORMSIGNINGDIALOG_CID, false, NULL, nsFormSigningDialogConstructor }, + { NULL } }; static const mozilla::Module::ContractIDEntry kPKIContracts[] = { @@ -43,7 +43,7 @@ static const mozilla::Module::ContractIDEntry kPKIContracts[] = { { NS_ASN1TREE_CONTRACTID, &kNS_NSSASN1OUTINER_CID }, { NS_PKIPARAMBLOCK_CONTRACTID, &kNS_PKIPARAMBLOCK_CID }, { NS_FORMSIGNINGDIALOG_CONTRACTID, &kNS_FORMSIGNINGDIALOG_CID }, - { nullptr } + { NULL } }; static const mozilla::Module kPKIModule = { diff --git a/security/manager/pki/src/nsPKIParamBlock.cpp b/security/manager/pki/src/nsPKIParamBlock.cpp index 9f828635aed..ec00d456fba 100644 --- a/security/manager/pki/src/nsPKIParamBlock.cpp +++ b/security/manager/pki/src/nsPKIParamBlock.cpp @@ -20,7 +20,7 @@ nsresult nsPKIParamBlock::Init() { mDialogParamBlock = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID); - return !mDialogParamBlock ? NS_ERROR_OUT_OF_MEMORY : NS_OK; + return (mDialogParamBlock == nullptr) ? NS_ERROR_OUT_OF_MEMORY : NS_OK; } nsPKIParamBlock::~nsPKIParamBlock() @@ -79,7 +79,7 @@ nsPKIParamBlock::SetISupportAtIndex(int32_t index, nsISupports *object) { if (!mSupports) { mSupports = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID); - if (!mSupports) { + if (mSupports == nullptr) { return NS_ERROR_OUT_OF_MEMORY; } } diff --git a/security/manager/ssl/src/SSLServerCertVerification.cpp b/security/manager/ssl/src/SSLServerCertVerification.cpp index e3cc1e36ee6..05421099f46 100644 --- a/security/manager/ssl/src/SSLServerCertVerification.cpp +++ b/security/manager/ssl/src/SSLServerCertVerification.cpp @@ -221,7 +221,7 @@ public: void Dispatch(); private: - const RefPtr mInfoObject; + const nsRefPtr mInfoObject; public: const PRErrorCode mErrorCode; const SSLErrorMessageType mErrorMessageType; @@ -248,13 +248,13 @@ class CertErrorRunnable : public SyncRunnableBase } virtual void RunOnTargetThread(); - RefPtr mResult; // out + nsRefPtr mResult; // out private: SSLServerCertVerificationResult *CheckCertOverrides(); const void * const mFdForLogging; // may become an invalid pointer; do not dereference const nsCOMPtr mCert; - const RefPtr mInfoObject; + const nsRefPtr mInfoObject; const PRErrorCode mDefaultErrorCodeToReport; const uint32_t mCollectedErrors; const PRErrorCode mErrorCodeTrust; @@ -427,7 +427,8 @@ CreateCertErrorRunnable(PRErrorCode defaultErrorCodeToReport, return nullptr; } - RefPtr nssCert(nsNSSCertificate::Create(cert)); + nsRefPtr nssCert; + nssCert = nsNSSCertificate::Create(cert); if (!nssCert) { NS_ERROR("nsNSSCertificate::Create failed"); PR_SetError(SEC_ERROR_NO_MEMORY, 0); @@ -444,7 +445,7 @@ CreateCertErrorRunnable(PRErrorCode defaultErrorCodeToReport, return nullptr; } - RefPtr survivingParams; + nsRefPtr survivingParams; nsrv = inss->GetDefaultCERTValInParam(survivingParams); if (NS_FAILED(nsrv)) { NS_ERROR("GetDefaultCERTValInParam failed"); @@ -471,7 +472,7 @@ CreateCertErrorRunnable(PRErrorCode defaultErrorCodeToReport, srv = CERT_VerifyCertificate(CERT_GetDefaultCertDB(), cert, true, certificateUsageSSLServer, PR_Now(), static_cast(infoObject), - verify_log, nullptr); + verify_log, NULL); } else { CERTValOutParam cvout[2]; @@ -590,7 +591,7 @@ private: } return rv; } - RefPtr mCertErrorRunnable; + nsRefPtr mCertErrorRunnable; }; class SSLServerCertVerificationJob : public nsRunnable @@ -610,7 +611,7 @@ private: ~SSLServerCertVerificationJob(); const void * const mFdForLogging; - const RefPtr mInfoObject; + const nsRefPtr mInfoObject; CERTCertificate * const mCert; }; @@ -643,7 +644,7 @@ PSM_SSL_PKIX_AuthCertificate(CERTCertificate *peerCert, void * pinarg, nsCOMPtr inss = do_GetService(kNSSComponentCID, &nsrv); if (!inss) return SECFailure; - RefPtr survivingParams; + nsRefPtr survivingParams; if (NS_FAILED(inss->GetDefaultCERTValInParam(survivingParams))) return SECFailure; @@ -776,7 +777,7 @@ BlockServerCertChangeForSpdy(nsNSSSocketInfo *infoObject, nsCOMPtr cert; nsCOMPtr cert2; - RefPtr status(infoObject->SSLStatus()); + nsRefPtr status = infoObject->SSLStatus(); if (!status) { // If we didn't have a status, then this is the // first handshake on this connection, not a @@ -872,8 +873,8 @@ AuthCertificate(TransportSecurityInfo * infoObject, CERTCertificate * cert) // complete chain at any time it might need it. // But we keep only those CA certs in the temp db, that we didn't already know. - RefPtr status(infoObject->SSLStatus()); - RefPtr nsc; + nsRefPtr status = infoObject->SSLStatus(); + nsRefPtr nsc; if (!status || !status->mServerCert) { nsc = nsNSSCertificate::Create(cert); @@ -991,8 +992,8 @@ SSLServerCertVerificationJob::Dispatch(const void * fdForLogging, return SECFailure; } - RefPtr job( - new SSLServerCertVerificationJob(fdForLogging, infoObject, serverCert)); + nsRefPtr job + = new SSLServerCertVerificationJob(fdForLogging, infoObject, serverCert); nsresult nrv; if (!gCertVerificationThreadPool) { @@ -1038,16 +1039,16 @@ SSLServerCertVerificationJob::Run() PR_SetError(0, 0); SECStatus rv = AuthCertificate(mInfoObject, mCert); if (rv == SECSuccess) { - RefPtr restart( - new SSLServerCertVerificationResult(mInfoObject, 0)); + nsRefPtr restart + = new SSLServerCertVerificationResult(mInfoObject, 0); restart->Dispatch(); return NS_OK; } error = PR_GetError(); if (error != 0) { - RefPtr runnable(CreateCertErrorRunnable( - error, mInfoObject, mCert, mFdForLogging)); + nsRefPtr runnable = CreateCertErrorRunnable( + error, mInfoObject, mCert, mFdForLogging); if (!runnable) { // CreateCertErrorRunnable set a new error code error = PR_GetError(); @@ -1083,8 +1084,8 @@ SSLServerCertVerificationJob::Run() error = PR_INVALID_STATE_ERROR; } - RefPtr failure( - new SSLServerCertVerificationResult(mInfoObject, error)); + nsRefPtr failure + = new SSLServerCertVerificationResult(mInfoObject, error); failure->Dispatch(); return NS_OK; } @@ -1164,9 +1165,9 @@ AuthCertificateHook(void *arg, PRFileDesc *fd, PRBool checkSig, PRBool isServer) PRErrorCode error = PR_GetError(); if (error != 0) { - RefPtr runnable(CreateCertErrorRunnable( + nsRefPtr runnable = CreateCertErrorRunnable( error, socketInfo, serverCert, - static_cast(fd))); + static_cast(fd)); if (!runnable) { // CreateCertErrorRunnable sets a new error code when it fails error = PR_GetError(); diff --git a/security/manager/ssl/src/ScopedNSSTypes.h b/security/manager/ssl/src/ScopedNSSTypes.h index 8de8555fdc5..ec2e14d6c11 100644 --- a/security/manager/ssl/src/ScopedNSSTypes.h +++ b/security/manager/ssl/src/ScopedNSSTypes.h @@ -9,12 +9,15 @@ #include "mozilla/Scoped.h" +extern "C" { #include "prio.h" #include "cert.h" #include "cms.h" #include "keyhi.h" #include "pk11pub.h" #include "sechash.h" +} // extern "C" + // Alphabetical order by NSS type MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, diff --git a/security/manager/ssl/src/TransportSecurityInfo.cpp b/security/manager/ssl/src/TransportSecurityInfo.cpp index 28ecb9b6951..8f4581c4f6b 100644 --- a/security/manager/ssl/src/TransportSecurityInfo.cpp +++ b/security/manager/ssl/src/TransportSecurityInfo.cpp @@ -253,7 +253,7 @@ TransportSecurityInfo::GetErrorMessage(PRUnichar** aText) } *aText = ToNewUnicode(mErrorMessageCached); - return *aText ? NS_OK : NS_ERROR_OUT_OF_MEMORY; + return *aText != nullptr ? NS_OK : NS_ERROR_OUT_OF_MEMORY; } void @@ -338,6 +338,9 @@ TransportSecurityInfo::GetInterface(const nsIID & uuid, void * *result) nsresult rv; if (!mCallbacks) { nsCOMPtr ir = new PipUIContext(); + if (!ir) + return NS_ERROR_OUT_OF_MEMORY; + rv = ir->GetInterface(uuid, result); } else { rv = mCallbacks->GetInterface(uuid, result); @@ -357,7 +360,7 @@ TransportSecurityInfo::Write(nsIObjectOutputStream* stream) MutexAutoLock lock(mMutex); - RefPtr status(mSSLStatus); + nsRefPtr status = mSSLStatus; nsCOMPtr certSerializable; // Write a redundant copy of the certificate for backward compatibility @@ -739,7 +742,7 @@ GetSubjectAltNames(CERTCertificate *nssCert, nameCount = 0; PLArenaPool *san_arena = nullptr; - SECItem altNameExtension = {siBuffer, nullptr, 0 }; + SECItem altNameExtension = {siBuffer, NULL, 0 }; CERTGeneralName *sanNameList = nullptr; SECStatus rv = CERT_FindCertExtension(nssCert, SEC_OID_X509_SUBJECT_ALT_NAME, @@ -817,7 +820,7 @@ AppendErrorTextMismatch(const nsString &host, const PRUnichar *params[1]; nsresult rv; - CERTCertificate *nssCert = nullptr; + CERTCertificate *nssCert = NULL; CERTCertificateCleaner nssCertCleaner(nssCert); nsCOMPtr cert2 = do_QueryInterface(ix509, &rv); @@ -1052,8 +1055,8 @@ formatOverridableCertErrorMessage(nsISSLStatus & sslStatus, returnedMessage.Append(NS_LITERAL_STRING("\n\n")); - RefPtr ix509; - rv = sslStatus.GetServerCert(byRef(ix509)); + nsRefPtr ix509; + rv = sslStatus.GetServerCert(getter_AddRefs(ix509)); NS_ENSURE_SUCCESS(rv, rv); bool isUntrusted; diff --git a/security/manager/ssl/src/TransportSecurityInfo.h b/security/manager/ssl/src/TransportSecurityInfo.h index 3b9fed538fe..b573087f05f 100644 --- a/security/manager/ssl/src/TransportSecurityInfo.h +++ b/security/manager/ssl/src/TransportSecurityInfo.h @@ -9,7 +9,6 @@ #include "certt.h" #include "mozilla/Mutex.h" -#include "mozilla/RefPtr.h" #include "nsIInterfaceRequestor.h" #include "nsITransportSecurityInfo.h" #include "nsSSLStatus.h" @@ -108,7 +107,7 @@ private: PRErrorCode mIsCertIssuerBlacklisted; /* SSL Status */ - mozilla::RefPtr mSSLStatus; + nsRefPtr mSSLStatus; virtual void virtualDestroyNSSReference(); void destructorSafeDestroyNSSReference(); diff --git a/security/manager/ssl/src/nsCERTValInParamWrapper.h b/security/manager/ssl/src/nsCERTValInParamWrapper.h index 23e43db79bb..96bf3270d40 100644 --- a/security/manager/ssl/src/nsCERTValInParamWrapper.h +++ b/security/manager/ssl/src/nsCERTValInParamWrapper.h @@ -26,7 +26,7 @@ * In order to protect against the race, we use a reference counted wrapper. * Each user of a foreign nsCERTValInParamWrapper object * (e.g. the current global default object) - * must use RefPtr = other-object + * must use nsRefPtr = other-object * prior to calling CERT_PKIXVerifyCert. * * This guarantees the object will still be alive after the call, diff --git a/security/manager/ssl/src/nsCMS.cpp b/security/manager/ssl/src/nsCMS.cpp index 0201b3dd34f..c73a50521ea 100644 --- a/security/manager/ssl/src/nsCMS.cpp +++ b/security/manager/ssl/src/nsCMS.cpp @@ -16,16 +16,12 @@ #include "nsCERTValInParamWrapper.h" #include "prlog.h" - -#include "nsNSSCleaner.h" -#include "nsNSSComponent.h" - #ifdef PR_LOGGING extern PRLogModuleInfo* gPIPNSSLog; #endif -using namespace mozilla; - +#include "nsNSSCleaner.h" +#include "nsNSSComponent.h" static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) @@ -184,7 +180,7 @@ NS_IMETHODIMP nsCMSMessage::GetSignerCert(nsIX509Cert **scert) } else { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::GetSignerCert no signer cert, do we have a cert list? %s\n", - (si->certList ? "yes" : "no") )); + (si->certList != nullptr ? "yes" : "no") )); *scert = nullptr; } @@ -221,7 +217,7 @@ nsresult nsCMSMessage::CommonVerifySignature(unsigned char* aDigestData, uint32_ NSSCMSSignerInfo *si; int32_t nsigners; nsresult rv = NS_ERROR_FAILURE; - RefPtr survivingParams; + nsRefPtr survivingParams; nsCOMPtr inss; if (!NSS_CMSMessage_IsSigned(m_cmsMsg)) { @@ -269,7 +265,7 @@ nsresult nsCMSMessage::CommonVerifySignature(unsigned char* aDigestData, uint32_ if (!nsNSSComponent::globalConstFlagUsePKIXVerification) { if (CERT_VerifyCertificateNow(CERT_GetDefaultCertDB(), si->cert, true, certificateUsageEmailSigner, - si->cmsg->pwfn_arg, nullptr) != SECSuccess) { + si->cmsg->pwfn_arg, NULL) != SECSuccess) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CommonVerifySignature - signing cert not trusted now\n")); rv = NS_ERROR_CMS_VERIFY_UNTRUSTED; goto loser; @@ -371,10 +367,18 @@ nsresult nsCMSMessage::CommonAsyncVerifySignature(nsISMimeVerificationListener * unsigned char* aDigestData, uint32_t aDigestDataLen) { nsSMimeVerificationJob *job = new nsSMimeVerificationJob; + if (!job) + return NS_ERROR_OUT_OF_MEMORY; if (aDigestData) { job->digest_data = new unsigned char[aDigestDataLen]; + if (!job->digest_data) + { + delete job; + return NS_ERROR_OUT_OF_MEMORY; + } + memcpy(job->digest_data, aDigestData, aDigestDataLen); } else @@ -553,8 +557,8 @@ NS_IMETHODIMP nsCMSMessage::CreateEncrypted(nsIArray * aRecipientCerts) goto loser; } - m_cmsMsg = NSS_CMSMessage_Create(nullptr); - if (!m_cmsMsg) { + m_cmsMsg = NSS_CMSMessage_Create(NULL); + if (m_cmsMsg == nullptr) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create new cms message\n")); rv = NS_ERROR_OUT_OF_MEMORY; goto loser; @@ -636,8 +640,8 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned(nsIX509Cert* aSigningCert, nsIX509Cert* /* * create the message object */ - m_cmsMsg = NSS_CMSMessage_Create(nullptr); /* create a message on its own pool */ - if (!m_cmsMsg) { + m_cmsMsg = NSS_CMSMessage_Create(NULL); /* create a message on its own pool */ + if (m_cmsMsg == NULL) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create new message\n")); rv = NS_ERROR_OUT_OF_MEMORY; goto loser; @@ -646,7 +650,7 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned(nsIX509Cert* aSigningCert, nsIX509Cert* /* * build chain of objects: message->signedData->data */ - if ((sigd = NSS_CMSSignedData_Create(m_cmsMsg)) == nullptr) { + if ((sigd = NSS_CMSSignedData_Create(m_cmsMsg)) == NULL) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signed data\n")); goto loser; } @@ -670,7 +674,7 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned(nsIX509Cert* aSigningCert, nsIX509Cert* * create & attach signer information */ if ((signerinfo = NSS_CMSSignerInfo_Create(m_cmsMsg, scert, SEC_OID_SHA1)) - == nullptr) { + == NULL) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signer info\n")); goto loser; } @@ -877,7 +881,7 @@ NS_IMETHODIMP nsCMSEncoder::Start(nsICMSMessage *aMsg, NSSCMSContentCallback cb, m_ctx = new PipUIContext(); m_ecx = NSS_CMSEncoder_Start(cmsMsg->getCMS(), cb, arg, 0, 0, 0, m_ctx, 0, 0, 0, 0); - if (!m_ecx) { + if (m_ecx == nullptr) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Start - can't start encoder\n")); return NS_ERROR_FAILURE; } diff --git a/security/manager/ssl/src/nsCMSSecureMessage.cpp b/security/manager/ssl/src/nsCMSSecureMessage.cpp index 65fd3041f31..7a094b5f8b1 100644 --- a/security/manager/ssl/src/nsCMSSecureMessage.cpp +++ b/security/manager/ssl/src/nsCMSSecureMessage.cpp @@ -3,6 +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/. */ +#include "nsMemory.h" #include "nsXPIDLString.h" #include "nsCOMPtr.h" #include "nsISupports.h" @@ -146,7 +147,7 @@ SendMessage(const char *msg, const char *base64Cert, char ** _retval) nsCOMPtr ctx = new PipUIContext(); /* Step 0. Create a CMS Message */ - cmsMsg = NSS_CMSMessage_Create(nullptr); + cmsMsg = NSS_CMSMessage_Create(NULL); if (!cmsMsg) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't create NSSCMSMessage\n")); rv = NS_ERROR_FAILURE; @@ -315,7 +316,7 @@ encode(const unsigned char *data, int32_t dataLen, char **_retval) { nsresult rv = NS_OK; - *_retval = PL_Base64Encode((const char *)data, dataLen, nullptr); + *_retval = PL_Base64Encode((const char *)data, dataLen, NULL); if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } loser: @@ -336,7 +337,7 @@ decode(const char *data, unsigned char **result, int32_t * _retval) if (data[len-2] == '=') adjust++; } - *result = (unsigned char *)PL_Base64Decode(data, len, nullptr); + *result = (unsigned char *)PL_Base64Decode(data, len, NULL); if (!*result) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::decode - error decoding base64\n")); rv = NS_ERROR_ILLEGAL_VALUE; diff --git a/security/manager/ssl/src/nsCRLInfo.cpp b/security/manager/ssl/src/nsCRLInfo.cpp index 3413fa7969e..d87459e41a2 100644 --- a/security/manager/ssl/src/nsCRLInfo.cpp +++ b/security/manager/ssl/src/nsCRLInfo.cpp @@ -14,6 +14,7 @@ #include "nsNSSShutDown.h" #include "nspr.h" +extern "C" { #include "pk11func.h" #include "certdb.h" #include "cert.h" @@ -21,6 +22,7 @@ #include "nssb64.h" #include "secasn1.h" #include "secder.h" +} NS_IMPL_ISUPPORTS1(nsCRLInfo, nsICRLInfo) diff --git a/security/manager/ssl/src/nsCRLManager.cpp b/security/manager/ssl/src/nsCRLManager.cpp index 08ecb1b5783..34dc6f52f92 100644 --- a/security/manager/ssl/src/nsCRLManager.cpp +++ b/security/manager/ssl/src/nsCRLManager.cpp @@ -20,6 +20,7 @@ #include "nsNSSCertHeader.h" #include "nspr.h" +extern "C" { #include "pk11func.h" #include "certdb.h" #include "cert.h" @@ -27,6 +28,7 @@ #include "nssb64.h" #include "secasn1.h" #include "secder.h" +} #include "ssl.h" #include "ocsp.h" #include "plbase64.h" @@ -53,9 +55,9 @@ nsCRLManager::ImportCrl (uint8_t *aData, uint32_t aLength, nsIURI * aURI, uint32 nsNSSShutDownPreventionLock locker; nsresult rv; - PLArenaPool *arena = nullptr; + PLArenaPool *arena = NULL; CERTCertificate *caCert; - SECItem derName = { siBuffer, nullptr, 0 }; + SECItem derName = { siBuffer, NULL, 0 }; SECItem derCrl; CERTSignedData sd; SECStatus sec_rv; @@ -180,7 +182,7 @@ done: } } } else { - if (!crlKey) { + if(crlKey == nullptr){ return NS_ERROR_FAILURE; } nsCOMPtr prefSvc = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv); @@ -326,7 +328,7 @@ nsCRLManager::GetCrls(nsIArray ** aCrls) } if (head) { - for (node=head->first; node; node = node->next) { + for (node=head->first; node != nullptr; node = node->next) { nsCOMPtr entry = new nsCRLInfo((node->crl)); crlsArray->AppendElement(entry, false); @@ -361,7 +363,7 @@ nsCRLManager::DeleteCrl(uint32_t aCrlIndex) } if (head) { - for (i = 0, node=head->first; node; i++, node = node->next) { + for (i = 0, node=head->first; node != nullptr; i++, node = node->next) { if (i != aCrlIndex) { continue; } diff --git a/security/manager/ssl/src/nsCertOverrideService.cpp b/security/manager/ssl/src/nsCertOverrideService.cpp index f69c8f45d5d..d0746a1b29b 100644 --- a/security/manager/ssl/src/nsCertOverrideService.cpp +++ b/security/manager/ssl/src/nsCertOverrideService.cpp @@ -18,6 +18,7 @@ #include "nsPromiseFlatString.h" #include "nsThreadUtils.h" #include "nsStringBuffer.h" +#include "nsAutoPtr.h" #include "nspr.h" #include "pk11pub.h" #include "certdb.h" @@ -509,7 +510,7 @@ nsCertOverrideService::RememberValidityOverride(const nsACString & aHostName, in if (NS_FAILED(rv)) return rv; - char *dbkey = nullptr; + char *dbkey = NULL; rv = aCert->GetDbKey(&dbkey); if (NS_FAILED(rv) || !dbkey) return rv; @@ -696,7 +697,7 @@ nsCertOverrideService::GetAllOverrideHostsWithPorts(uint32_t *aCount, static bool matchesDBKey(nsIX509Cert *cert, const char *match_dbkey) { - char *dbkey = nullptr; + char *dbkey = NULL; nsresult rv = cert->GetDbKey(&dbkey); if (NS_FAILED(rv) || !dbkey) return false; diff --git a/security/manager/ssl/src/nsCertTree.cpp b/security/manager/ssl/src/nsCertTree.cpp index b979645bfba..d2bd871490c 100644 --- a/security/manager/ssl/src/nsCertTree.cpp +++ b/security/manager/ssl/src/nsCertTree.cpp @@ -22,15 +22,13 @@ #include "nsTHashtable.h" #include "nsHashKeys.h" + #include "prlog.h" -#include "nsNSSCleaner.h" - -using namespace mozilla; - #ifdef PR_LOGGING extern PRLogModuleInfo* gPIPNSSLog; #endif +#include "nsNSSCleaner.h" NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); @@ -163,7 +161,7 @@ nsCertTreeDispInfo::GetHostPort(nsAString &aHostPort) NS_IMPL_ISUPPORTS2(nsCertTree, nsICertTree, nsITreeView) -nsCertTree::nsCertTree() : mTreeArray(nullptr) +nsCertTree::nsCertTree() : mTreeArray(NULL) { mCompareCache.ops = nullptr; mNSSComponent = do_GetService(kNSSComponentCID); @@ -214,7 +212,7 @@ nsCertTree::getCacheEntry(void *cache, void *aCert) CompareCacheHashEntryPtr *entryPtr = static_cast (PL_DHashTableOperate(&aCompareCache, aCert, PL_DHASH_ADD)); - return entryPtr ? entryPtr->entry : nullptr; + return entryPtr ? entryPtr->entry : NULL; } void nsCertTree::RemoveCacheEntry(void *key) @@ -241,7 +239,7 @@ nsCertTree::CountOrganizations() int32_t orgCount = 1; for (i=1; imAddonInfo; + addonInfo = mDispInfo.SafeElementAt(i, NULL)->mAddonInfo; if (addonInfo) { nextCert = addonInfo->mCert; } @@ -282,8 +280,8 @@ nsCertTree::GetThreadDescAtIndex(int32_t index) already_AddRefed nsCertTree::GetCertAtIndex(int32_t index, int32_t *outAbsoluteCertOffset) { - RefPtr certdi( - GetDispInfoAtIndex(index, outAbsoluteCertOffset)); + nsRefPtr certdi = + GetDispInfoAtIndex(index, outAbsoluteCertOffset); if (!certdi) return nullptr; @@ -298,7 +296,7 @@ nsCertTree::GetCertAtIndex(int32_t index, int32_t *outAbsoluteCertOffset) } // If the row at index is a cert, return that cert. Otherwise, return null. -TemporaryRef +already_AddRefed nsCertTree::GetDispInfoAtIndex(int32_t index, int32_t *outAbsoluteCertOffset) { @@ -313,8 +311,7 @@ nsCertTree::GetDispInfoAtIndex(int32_t index, int32_t certIndex = cIndex + index - idx; if (outAbsoluteCertOffset) *outAbsoluteCertOffset = certIndex; - RefPtr certdi(mDispInfo.SafeElementAt(certIndex, - nullptr)); + nsRefPtr certdi = mDispInfo.SafeElementAt(certIndex, NULL); if (certdi) { nsCertTreeDispInfo *raw = certdi.get(); NS_IF_ADDREF(raw); @@ -349,8 +346,8 @@ nsCertTree::GetCompareFuncFromCertType(uint32_t aType) struct nsCertAndArrayAndPositionAndCounterAndTracker { - RefPtr certai; - nsTArray< RefPtr > *array; + nsRefPtr certai; + nsTArray< nsRefPtr > *array; int position; int counter; nsTHashtable *tracker; @@ -413,7 +410,7 @@ CollectAllHostPortOverridesCallback(const nsCertOverride &aSettings, struct nsArrayAndPositionAndCounterAndTracker { - nsTArray< RefPtr > *array; + nsTArray< nsRefPtr > *array; int position; int counter; nsTHashtable *tracker; @@ -579,7 +576,10 @@ nsCertTree::GetCertsByTypeFromCertList(CERTCertList *aCertList, } } - RefPtr certai(new nsCertAddonInfo); + nsRefPtr certai = new nsCertAddonInfo; + if (!certai) + return NS_ERROR_OUT_OF_MEMORY; + certai->mCert = pipCert; certai->mUsageCount = 0; @@ -587,8 +587,7 @@ nsCertTree::GetCertsByTypeFromCertList(CERTCertList *aCertList, int InsertPosition = 0; for (; InsertPosition < count; ++InsertPosition) { nsCOMPtr cert = nullptr; - RefPtr elem( - mDispInfo.SafeElementAt(InsertPosition, nullptr)); + nsRefPtr elem = mDispInfo.SafeElementAt(InsertPosition, NULL); if (elem && elem->mAddonInfo) { cert = elem->mAddonInfo->mCert; } @@ -598,6 +597,9 @@ nsCertTree::GetCertsByTypeFromCertList(CERTCertList *aCertList, } if (wantThisCert) { nsCertTreeDispInfo *certdi = new nsCertTreeDispInfo; + if (!certdi) + return NS_ERROR_OUT_OF_MEMORY; + certdi->mAddonInfo = certai; certai->mUsageCount++; certdi->mTypeOfEntry = nsCertTreeDispInfo::direct_db; @@ -642,7 +644,7 @@ nsCertTree::GetCertsByType(uint32_t aType, void *aCertCmpFnArg) { nsNSSShutDownPreventionLock locker; - CERTCertList *certList = nullptr; + CERTCertList *certList = NULL; nsCOMPtr cxt = new PipUIContext(); certList = PK11_ListCerts(PK11CertListUnique, cxt); nsresult rv = GetCertsByTypeFromCertList(certList, aType, aCertCmpFn, aCertCmpFnArg); @@ -710,6 +712,8 @@ nsCertTree::UpdateUIContents() uint32_t count = mDispInfo.Length(); mNumOrgs = CountOrganizations(); mTreeArray = new treeArrayEl[mNumOrgs]; + if (!mTreeArray) + return NS_ERROR_OUT_OF_MEMORY; mCellText = do_CreateInstance(NS_ARRAY_CONTRACTID); @@ -735,7 +739,7 @@ if (count) { mTreeArray[i].numChildren = 1; if (++j >= count) break; nsCOMPtr nextCert = nullptr; - nsCertAddonInfo *addonInfo = mDispInfo.SafeElementAt(j, nullptr)->mAddonInfo; + nsCertAddonInfo *addonInfo = mDispInfo.SafeElementAt(j, NULL)->mAddonInfo; if (addonInfo) { nextCert = addonInfo->mCert; } @@ -743,7 +747,7 @@ if (count) { mTreeArray[i].numChildren++; if (++j >= count) break; nextCert = nullptr; - addonInfo = mDispInfo.SafeElementAt(j, nullptr)->mAddonInfo; + addonInfo = mDispInfo.SafeElementAt(j, NULL)->mAddonInfo; if (addonInfo) { nextCert = addonInfo->mCert; } @@ -786,8 +790,7 @@ nsCertTree::DeleteEntryObject(uint32_t index) int32_t certIndex = cIndex + index - idx; bool canRemoveEntry = false; - RefPtr certdi(mDispInfo.SafeElementAt(certIndex, - nullptr)); + nsRefPtr certdi = mDispInfo.SafeElementAt(certIndex, NULL); // We will remove the element from the visual tree. // Only if we have a certdi, then we can check for additional actions. @@ -880,7 +883,8 @@ nsCertTree::GetTreeItem(uint32_t aIndex, nsICertTreeItem **_treeitem) { NS_ENSURE_ARG(_treeitem); - RefPtr certdi(GetDispInfoAtIndex(aIndex)); + nsRefPtr certdi = + GetDispInfoAtIndex(aIndex); if (!certdi) return NS_ERROR_FAILURE; @@ -894,7 +898,8 @@ nsCertTree::IsHostPortOverride(uint32_t aIndex, bool *_retval) { NS_ENSURE_ARG(_retval); - RefPtr certdi(GetDispInfoAtIndex(aIndex)); + nsRefPtr certdi = + GetDispInfoAtIndex(aIndex); if (!certdi) return NS_ERROR_FAILURE; @@ -1105,7 +1110,7 @@ nsCertTree::GetCellText(int32_t row, nsITreeColumn* col, col->GetIdConst(&colID); treeArrayEl *el = GetThreadDescAtIndex(row); - if (el) { + if (el != nullptr) { if (NS_LITERAL_STRING("certcol").Equals(colID)) _retval.Assign(el->orgName); else @@ -1114,7 +1119,8 @@ nsCertTree::GetCellText(int32_t row, nsITreeColumn* col, } int32_t absoluteCertOffset; - RefPtr certdi(GetDispInfoAtIndex(row, &absoluteCertOffset)); + nsRefPtr certdi = + GetDispInfoAtIndex(row, &absoluteCertOffset); if (!certdi) return NS_ERROR_FAILURE; @@ -1401,12 +1407,12 @@ nsCertTree::dumpMap() } for (int i=0; iorgName); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("thread desc[%d]: %s", i, NS_LossyConvertUTF16toASCII(td).get())); } nsCOMPtr ct = GetCertAtIndex(i); - if (ct) { + if (ct != nullptr) { PRUnichar *goo; ct->GetCommonName(&goo); nsAutoString doo(goo); @@ -1455,7 +1461,7 @@ void nsCertTree::CmpInitCriterion(nsIX509Cert *cert, CompareCacheHashEntry *entry, sortCriterion crit, int32_t level) { - NS_ENSURE_TRUE(cert && entry, RETURN_NOTHING); + NS_ENSURE_TRUE( (cert!=0 && entry!=0), RETURN_NOTHING ); entry->mCritInit[level] = true; nsXPIDLString &str = entry->mCrit[level]; @@ -1510,7 +1516,7 @@ nsCertTree::CmpByCrit(nsIX509Cert *a, CompareCacheHashEntry *ace, nsIX509Cert *b, CompareCacheHashEntry *bce, sortCriterion crit, int32_t level) { - NS_ENSURE_TRUE(a && ace && b && bce, 0); + NS_ENSURE_TRUE( (a!=0 && ace!=0 && b!=0 && bce!=0), 0 ); if (!ace->mCritInit[level]) { CmpInitCriterion(a, ace, crit, level); @@ -1555,7 +1561,7 @@ nsCertTree::CmpBy(void *cache, nsIX509Cert *a, nsIX509Cert *b, if (!b) return 1; - NS_ENSURE_TRUE(cache && a && b, 0); + NS_ENSURE_TRUE( (cache!=0 && a!=0 && b!=0), 0 ); CompareCacheHashEntry *ace = getCacheEntry(cache, a); CompareCacheHashEntry *bce = getCacheEntry(cache, b); diff --git a/security/manager/ssl/src/nsCertTree.h b/security/manager/ssl/src/nsCertTree.h index 1c25220e457..82609366e12 100644 --- a/security/manager/ssl/src/nsCertTree.h +++ b/security/manager/ssl/src/nsCertTree.h @@ -6,6 +6,7 @@ #define _NS_CERTTREE_H_ #include "nsCOMPtr.h" +#include "nsAutoPtr.h" #include "nsIServiceManager.h" #include "nsICertTree.h" #include "nsITreeView.h" @@ -44,7 +45,7 @@ public: nsCertAddonInfo() : mUsageCount(0) {} - mozilla::RefPtr mCert; + nsRefPtr mCert; // how many display entries reference this? // (and therefore depend on the underlying cert) int32_t mUsageCount; @@ -60,7 +61,7 @@ public: nsCertTreeDispInfo(nsCertTreeDispInfo &other); virtual ~nsCertTreeDispInfo(); - mozilla::RefPtr mAddonInfo; + nsRefPtr mAddonInfo; enum { direct_db, host_port_override } mTypeOfEntry; @@ -112,7 +113,7 @@ protected: nsresult GetCertsByTypeFromCache(nsINSSCertCache *aCache, uint32_t aType, nsCertCompareFunc aCertCmpFn, void *aCertCmpFnArg); private: - nsTArray< mozilla::RefPtr > mDispInfo; + nsTArray< nsRefPtr > mDispInfo; nsCOMPtr mTree; nsCOMPtr mSelection; treeArrayEl *mTreeArray; @@ -121,12 +122,12 @@ private: PLDHashTable mCompareCache; nsCOMPtr mNSSComponent; nsCOMPtr mOverrideService; - mozilla::RefPtr mOriginalOverrideService; + nsRefPtr mOriginalOverrideService; treeArrayEl *GetThreadDescAtIndex(int32_t _index); already_AddRefed GetCertAtIndex(int32_t _index, int32_t *outAbsoluteCertOffset = nullptr); - mozilla::TemporaryRef + already_AddRefed GetDispInfoAtIndex(int32_t index, int32_t *outAbsoluteCertOffset = nullptr); void FreeCertArray(); nsresult UpdateUIContents(); diff --git a/security/manager/ssl/src/nsCertVerificationThread.cpp b/security/manager/ssl/src/nsCertVerificationThread.cpp index 56d4295445a..f3c01ea54c6 100644 --- a/security/manager/ssl/src/nsCertVerificationThread.cpp +++ b/security/manager/ssl/src/nsCertVerificationThread.cpp @@ -2,6 +2,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/. */ +#include "nsMemory.h" +#include "nsAutoPtr.h" #include "nsCertVerificationThread.h" #include "nsThreadUtils.h" @@ -45,7 +47,7 @@ void nsCertVerificationJob::Run() PRUnichar **usages; nsCOMPtr ires; - RefPtr vres(new nsCertVerificationResult); + nsRefPtr vres = new nsCertVerificationResult; if (vres) { nsresult rv = mCert->GetUsagesArray(false, // do not ignore OCSP diff --git a/security/manager/ssl/src/nsClientAuthRemember.cpp b/security/manager/ssl/src/nsClientAuthRemember.cpp index 3f40d97734d..57955bccd1e 100644 --- a/security/manager/ssl/src/nsClientAuthRemember.cpp +++ b/security/manager/ssl/src/nsClientAuthRemember.cpp @@ -7,7 +7,6 @@ #include "nsClientAuthRemember.h" #include "nsIX509Cert.h" -#include "mozilla/RefPtr.h" #include "nsCRT.h" #include "nsNetUtil.h" #include "nsIObserverService.h" @@ -95,7 +94,7 @@ GetCertFingerprintByOidTag(CERTCertificate* nsscert, nsCString &fp) { unsigned int hash_len = HASH_ResultLenByOidTag(aOidTag); - RefPtr fingerprint(nsStringBuffer::Alloc(hash_len)); + nsRefPtr fingerprint = nsStringBuffer::Alloc(hash_len); if (!fingerprint) return NS_ERROR_OUT_OF_MEMORY; @@ -114,7 +113,7 @@ nsresult nsClientAuthRememberService::RememberDecision(const nsACString & aHostName, CERTCertificate *aServerCert, CERTCertificate *aClientCert) { - // aClientCert == nullptr means: remember that user does not want to use a cert + // aClientCert == NULL means: remember that user does not want to use a cert NS_ENSURE_ARG_POINTER(aServerCert); if (aHostName.IsEmpty()) return NS_ERROR_INVALID_ARG; @@ -128,7 +127,7 @@ nsClientAuthRememberService::RememberDecision(const nsACString & aHostName, ReentrantMonitorAutoEnter lock(monitor); if (aClientCert) { nsNSSCertificate pipCert(aClientCert); - char *dbkey = nullptr; + char *dbkey = NULL; rv = pipCert.GetDbKey(&dbkey); if (NS_SUCCEEDED(rv) && dbkey) { AddEntryToList(aHostName, fpStr, diff --git a/security/manager/ssl/src/nsClientAuthRemember.h b/security/manager/ssl/src/nsClientAuthRemember.h index 35a8a21b47a..63cf07208df 100644 --- a/security/manager/ssl/src/nsClientAuthRemember.h +++ b/security/manager/ssl/src/nsClientAuthRemember.h @@ -11,6 +11,7 @@ #include "nsTHashtable.h" #include "nsIObserver.h" #include "nsIX509Cert.h" +#include "nsAutoPtr.h" #include "nsNSSCertificate.h" #include "nsString.h" #include "nsWeakReference.h" diff --git a/security/manager/ssl/src/nsCrypto.cpp b/security/manager/ssl/src/nsCrypto.cpp index 48aeb78c30c..ca32342f4da 100644 --- a/security/manager/ssl/src/nsCrypto.cpp +++ b/security/manager/ssl/src/nsCrypto.cpp @@ -14,6 +14,7 @@ #include "nsThreadUtils.h" #include "nsIServiceManager.h" #include "nsIMemory.h" +#include "nsAutoPtr.h" #include "nsAlgorithm.h" #include "nsCRT.h" #include "prprf.h" @@ -49,8 +50,10 @@ #include "seccomon.h" #include "secerr.h" #include "sechash.h" +extern "C" { #include "crmf.h" #include "pk11pqg.h" +} #include "cmmf.h" #include "nssb64.h" #include "base64.h" @@ -63,12 +66,6 @@ #include "ssl.h" // For SSL_ClearSessionCache #include "nsNSSCleaner.h" - -#include "nsNSSShutDown.h" -#include "nsNSSCertHelper.h" - -using namespace mozilla; - NSSCleanupAutoPtrClass(SECKEYPrivateKey, SECKEY_DestroyPrivateKey) NSSCleanupAutoPtrClass(PK11SlotInfo, PK11_FreeSlot) NSSCleanupAutoPtrClass(CERTCertNicknames, CERT_FreeNicknames) @@ -76,6 +73,9 @@ NSSCleanupAutoPtrClass(PK11SymKey, PK11_FreeSymKey) NSSCleanupAutoPtrClass_WithParam(PK11Context, PK11_DestroyContext, TrueParam, true) NSSCleanupAutoPtrClass_WithParam(SECItem, SECITEM_FreeItem, TrueParam, true) +#include "nsNSSShutDown.h" +#include "nsNSSCertHelper.h" + /* * These are the most common error strings that are returned * by the JavaScript methods in case of error. @@ -336,13 +336,13 @@ static nsKeyGenType cryptojs_interpret_key_gen_type(char *keyAlg) { char *end; - if (!keyAlg) { + if (keyAlg == nullptr) { return invalidKeyGen; } /* First let's remove all leading and trailing white space */ while (isspace(keyAlg[0])) keyAlg++; end = strchr(keyAlg, '\0'); - if (!end) { + if (end == nullptr) { return invalidKeyGen; } end--; @@ -457,7 +457,7 @@ nsConvertToActualKeyGenParams(uint32_t keyGenMech, char *params, rsaParams = static_cast (nsMemory::Alloc(sizeof(PK11RSAGenParams))); - if (!rsaParams) { + if (rsaParams == nullptr) { return nullptr; } /* I'm just taking the same parameters used in @@ -726,7 +726,7 @@ cryptojs_generateOneKeyPair(JSContext *cx, nsKeyPairInfo *keyPairInfo, // "firstAttemptSlot" and "secondAttemptSlot" are alternative names // for better code readability, we don't increase the reference counts. - PK11SlotInfo *firstAttemptSlot = nullptr; + PK11SlotInfo *firstAttemptSlot = NULL; PK11AttrFlags firstAttemptFlags = 0; PK11SlotInfo *secondAttemptSlot = slot; @@ -741,7 +741,7 @@ cryptojs_generateOneKeyPair(JSContext *cx, nsKeyPairInfo *keyPairInfo, // if the destination slot is the internal slot, then there is only one attempt firstAttemptSlot = secondAttemptSlot; firstAttemptFlags = secondAttemptFlags; - secondAttemptSlot = nullptr; + secondAttemptSlot = NULL; secondAttemptFlags = 0; } else { @@ -801,12 +801,12 @@ cryptojs_generateOneKeyPair(JSContext *cx, nsKeyPairInfo *keyPairInfo, NS_RELEASE(dialogs); if (NS_SUCCEEDED(rv)) { - PK11SlotInfo *used_slot = nullptr; + PK11SlotInfo *used_slot = NULL; rv = KeygenRunnable->ConsumeResult(&used_slot, &keyPairInfo->privKey, &keyPairInfo->pubKey); if (NS_SUCCEEDED(rv)) { - if ((used_slot == firstAttemptSlot) && secondAttemptSlot) { + if ((used_slot == firstAttemptSlot) && (secondAttemptSlot != NULL)) { mustMoveKey = true; } @@ -816,8 +816,8 @@ cryptojs_generateOneKeyPair(JSContext *cx, nsKeyPairInfo *keyPairInfo, } } - firstAttemptSlot = nullptr; - secondAttemptSlot = nullptr; + firstAttemptSlot = NULL; + secondAttemptSlot = NULL; nsFreeKeyGenParams(mechanism, keyGenParams); @@ -948,9 +948,9 @@ cryptojs_ReadArgsAndGenerateKey(JSContext *cx, keyGenAlg.ptr()); goto loser; } - if (!*slot) { + if (*slot == nullptr) { *slot = nsGetSlotForKeyGen(keyGenType->keyGenType, uiCxt); - if (!*slot) + if (*slot == nullptr) goto loser; } @@ -1164,11 +1164,11 @@ nsSetKeyUsageExtension(CRMFCertRequest *crmfReq, nsPrepareBitStringForEncoding(&bitsmap, &keyUsageValue); encodedExt = SEC_ASN1EncodeItem(nullptr, nullptr, &bitsmap,&bitStrTemplate); - if (!encodedExt) { + if (encodedExt == nullptr) { goto loser; } ext = CRMF_CreateCertExtension(SEC_OID_X509_KEY_USAGE, true, encodedExt); - if (!ext) { + if (ext == nullptr) { goto loser; } extAddParams.numExtensions = 1; @@ -1488,7 +1488,7 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCertReqMsg *certReqMsg, // allows multiple requests to be sent in one step. unsigned long der_request_len = 0; - SECItem *der_request = nullptr; + SECItem *der_request = NULL; SECItemCleanerTrueParam der_request_cleaner(der_request); if (SECSuccess != CRMF_EncodeCertRequest(certReq, @@ -1516,31 +1516,31 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCertReqMsg *certReqMsg, // issuer names in the CA's certificate as follows: // K = SHA1(DER-encoded-subjectName | Kec | DER-encoded-issuerName)" - PK11SymKey *shared_secret = nullptr; + PK11SymKey *shared_secret = NULL; PK11SymKeyCleaner shared_secret_cleaner(shared_secret); - PK11SymKey *subject_and_secret = nullptr; + PK11SymKey *subject_and_secret = NULL; PK11SymKeyCleaner subject_and_secret_cleaner(subject_and_secret); - PK11SymKey *subject_and_secret_and_issuer = nullptr; + PK11SymKey *subject_and_secret_and_issuer = NULL; PK11SymKeyCleaner subject_and_secret_and_issuer_cleaner(subject_and_secret_and_issuer); - PK11SymKey *sha1_of_subject_and_secret_and_issuer = nullptr; + PK11SymKey *sha1_of_subject_and_secret_and_issuer = NULL; PK11SymKeyCleaner sha1_of_subject_and_secret_and_issuer_cleaner(sha1_of_subject_and_secret_and_issuer); shared_secret = PK11_PubDeriveWithKDF(keyInfo->privKey, // SECKEYPrivateKey *privKey keyInfo->ecPopPubKey, // SECKEYPublicKey *pubKey false, // bool isSender - nullptr, // SECItem *randomA - nullptr, // SECItem *randomB + NULL, // SECItem *randomA + NULL, // SECItem *randomB CKM_ECDH1_DERIVE, // CK_MECHANISM_TYPE derive CKM_CONCATENATE_DATA_AND_BASE, // CK_MECHANISM_TYPE target CKA_DERIVE, // CK_ATTRIBUTE_TYPE operation 0, // int keySize CKD_NULL, // CK_ULONG kdf - nullptr, // SECItem *sharedData - nullptr); // void *wincx + NULL, // SECItem *sharedData + NULL); // void *wincx if (!shared_secret) return NS_ERROR_FAILURE; @@ -1584,7 +1584,7 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCertReqMsg *certReqMsg, sha1_of_subject_and_secret_and_issuer = PK11_Derive(subject_and_secret_and_issuer, // PK11SymKey *baseKey CKM_SHA1_KEY_DERIVATION, // CK_MECHANISM_TYPE mechanism - nullptr, // SECItem *param + NULL, // SECItem *param CKM_SHA_1_HMAC, // CK_MECHANISM_TYPE target CKA_SIGN, // CK_ATTRIBUTE_TYPE operation 0); // int keySize @@ -1592,7 +1592,7 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCertReqMsg *certReqMsg, if (!sha1_of_subject_and_secret_and_issuer) return NS_ERROR_FAILURE; - PK11Context *context = nullptr; + PK11Context *context = NULL; PK11ContextCleanerTrueParam context_cleaner(context); SECItem ignore; @@ -1615,7 +1615,7 @@ nsSet_EC_DHMAC_ProofOfPossession(CRMFCertReqMsg *certReqMsg, PK11_DigestOp(context, der_request->data, der_request->len)) return NS_ERROR_FAILURE; - SECItem *result_hmac_sha1_item = nullptr; + SECItem *result_hmac_sha1_item = NULL; SECItemCleanerTrueParam result_hmac_sha1_item_cleaner(result_hmac_sha1_item); result_hmac_sha1_item = SECITEM_AllocItem(nullptr, nullptr, SHA1_LENGTH); @@ -1756,12 +1756,12 @@ nsEncodeCertReqMessages(CRMFCertReqMsg **certReqMsgs) return nullptr; } SECItem *dest = (SECItem *)PORT_Alloc(sizeof(SECItem)); - if (!dest) { + if (dest == nullptr) { return nullptr; } dest->type = siBuffer; dest->data = (unsigned char *)PORT_Alloc(len); - if (!dest->data) { + if (dest->data == nullptr) { PORT_Free(dest); return nullptr; } @@ -1788,7 +1788,7 @@ nsCreateReqFromKeyPairs(nsKeyPairInfo *keyids, int32_t numRequests, // that calls the C API of NSS. int32_t i; // The ASN1 encoder in NSS wants the last entry in the array to be - // nullptr so that it knows when the last element is. + // NULL so that it knows when the last element is. CRMFCertReqMsg **certReqMsgs = new CRMFCertReqMsg*[numRequests+1]; CRMFCertRequest *certReq; if (!certReqMsgs) @@ -1986,6 +1986,10 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMFObject** aReturn) nsCOMPtr uiCxt = new PipUIContext; int32_t numRequests = (argc - 5)/3; nsKeyPairInfo *keyids = new nsKeyPairInfo[numRequests]; + if (keyids == nullptr) { + JS_ReportError(cx, "%s\n", JS_ERROR_INTERNAL); + return NS_ERROR_OUT_OF_MEMORY; + } memset(keyids, 0, sizeof(nsKeyPairInfo)*numRequests); int keyInfoIndex; uint32_t i; @@ -2019,6 +2023,12 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMFObject** aReturn) return NS_ERROR_FAILURE; } nsCRMFObject *newObject = new nsCRMFObject(); + if (newObject == nullptr) { + JS_ReportError(cx, "%s%s\n", JS_ERROR, "could not create crmf JS object"); + + nsFreeKeyPairInfo(keyids,numRequests); + return NS_ERROR_OUT_OF_MEMORY; + } newObject->SetCRMFRequest(encodedRequest); *aReturn = newObject; //Give a reference to the returnee. @@ -2047,6 +2057,8 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMFObject** aReturn) NS_ENSURE_TRUE(principals, NS_ERROR_UNEXPECTED); nsCryptoRunArgs *args = new nsCryptoRunArgs(); + if (!args) + return NS_ERROR_OUT_OF_MEMORY; args->m_cx = cx; args->m_kungFuDeathGrip = GetISupportsFromContext(cx); @@ -2056,6 +2068,8 @@ nsCrypto::GenerateCRMFRequest(nsIDOMCRMFObject** aReturn) args->m_principals = principals; nsCryptoRunnable *cryptoRunnable = new nsCryptoRunnable(args); + if (!cryptoRunnable) + return NS_ERROR_OUT_OF_MEMORY; rv = NS_DispatchToMainThread(cryptoRunnable); if (NS_FAILED(rv)) @@ -2346,7 +2360,7 @@ nsCrypto::ImportUserCertificates(const nsAString& aNickname, if (currCert->nickname) { localNick = currCert->nickname; } - else if (!nickname || nickname[0] == '\0') { + else if (nickname == nullptr || nickname[0] == '\0') { nsNSSCertificateDB::get_default_nickname(currCert, ctx, localNick); } else { //This is the case where we're getting a brand new @@ -2359,7 +2373,7 @@ nsCrypto::ImportUserCertificates(const nsAString& aNickname, char *cast_const_away = const_cast(localNick.get()); slot = PK11_ImportCertForKey(currCert, cast_const_away, ctx); } - if (!slot) { + if (slot == nullptr) { rv = NS_ERROR_FAILURE; goto loser; } @@ -2665,7 +2679,7 @@ nsCrypto::SignText(const nsAString& aStringToSign, const nsAString& aCaOption, for (node = CERT_LIST_HEAD(certList), certsToUse = 0; !CERT_LIST_END(node, certList) && certsToUse < nicknames->numnicknames; node = CERT_LIST_NEXT(node)) { - RefPtr tempCert(nsNSSCertificate::Create(node->cert)); + nsRefPtr tempCert = nsNSSCertificate::Create(node->cert); if (tempCert) { nsAutoString nickWithSerial, details; rv = tempCert->FormatUIStrings(NS_ConvertUTF8toUTF16(nicknames->nicknames[certsToUse]), diff --git a/security/manager/ssl/src/nsDataSignatureVerifier.cpp b/security/manager/ssl/src/nsDataSignatureVerifier.cpp index ed63206b10a..68e6e46d77e 100644 --- a/security/manager/ssl/src/nsDataSignatureVerifier.cpp +++ b/security/manager/ssl/src/nsDataSignatureVerifier.cpp @@ -19,7 +19,7 @@ NS_IMPL_ISUPPORTS1(nsDataSignatureVerifier, nsIDataSignatureVerifier) const SEC_ASN1Template CERT_SignatureDataTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, nullptr, sizeof(CERTSignedData) }, + 0, NULL, sizeof(CERTSignedData) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTSignedData,signatureAlgorithm), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate), }, @@ -94,7 +94,7 @@ nsDataSignatureVerifier::VerifyData(const nsACString & aData, aData.Length(), publicKey, &(sigData.signature), &(sigData.signatureAlgorithm), - nullptr, nullptr); + NULL, NULL); // Clean up remaining objects SECKEY_DestroyPublicKey(publicKey); diff --git a/security/manager/ssl/src/nsIdentityChecking.cpp b/security/manager/ssl/src/nsIdentityChecking.cpp index 52a4919a9b0..1daa865fc08 100644 --- a/security/manager/ssl/src/nsIdentityChecking.cpp +++ b/security/manager/ssl/src/nsIdentityChecking.cpp @@ -1060,7 +1060,7 @@ static SECStatus getFirstEVPolicy(CERTCertificate *cert, SECOidTag &outOidTag) return SECFailure; if (cert->extensions) { - for (int i=0; cert->extensions[i]; i++) { + for (int i=0; cert->extensions[i] != nullptr; i++) { const SECItem *oid = &cert->extensions[i]->id; SECOidTag oidTag = SECOID_FindOIDTag(oid); @@ -1079,7 +1079,7 @@ static SECStatus getFirstEVPolicy(CERTCertificate *cert, SECOidTag &outOidTag) policyInfos = policies->policyInfos; bool found = false; - while (*policyInfos) { + while (*policyInfos != NULL) { policyInfo = *policyInfos++; SECOidTag oid_tag = policyInfo->oid; diff --git a/security/manager/ssl/src/nsKeygenHandler.cpp b/security/manager/ssl/src/nsKeygenHandler.cpp index bea17f63be3..61fc64b1f6d 100644 --- a/security/manager/ssl/src/nsKeygenHandler.cpp +++ b/security/manager/ssl/src/nsKeygenHandler.cpp @@ -4,7 +4,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/. */ +extern "C" { #include "secdert.h" +} #include "nspr.h" #include "nsNSSComponent.h" // for PIPNSS string bundle calls. #include "keyhi.h" @@ -12,7 +14,9 @@ #include "cryptohi.h" #include "base64.h" #include "secasn1.h" +extern "C" { #include "pk11pqg.h" +} #include "nsKeygenHandler.h" #include "nsVoidArray.h" #include "nsIServiceManager.h" @@ -33,7 +37,7 @@ DERTemplate SECAlgorithmIDTemplate[] = { { DER_SEQUENCE, - 0, nullptr, sizeof(SECAlgorithmID) }, + 0, NULL, sizeof(SECAlgorithmID) }, { DER_OBJECT_ID, offsetof(SECAlgorithmID,algorithm), }, { DER_OPTIONAL | DER_ANY, @@ -61,7 +65,7 @@ DERTemplate CERTPublicKeyAndChallengeTemplate[] = }; const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, nullptr, sizeof(PQGParams) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, @@ -222,7 +226,7 @@ SECKEYECParams * decode_ec_params(const char *curve) { SECKEYECParams *ecparams; - SECOidData *oidData = nullptr; + SECOidData *oidData = NULL; SECOidTag curveOidTag = SEC_OID_UNKNOWN; /* default */ int i, numCurves; @@ -235,13 +239,13 @@ decode_ec_params(const char *curve) } } - /* Return nullptr if curve name is not recognized */ + /* Return NULL if curve name is not recognized */ if ((curveOidTag == SEC_OID_UNKNOWN) || - (oidData = SECOID_FindOIDByTag(curveOidTag)) == nullptr) { + (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) { return nullptr; } - ecparams = SECITEM_AllocItem(nullptr, nullptr, (2 + oidData->oid.len)); + ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len)); if (!ecparams) return nullptr; @@ -276,6 +280,8 @@ nsKeygenFormProcessor::Create(nsISupports* aOuter, const nsIID& aIID, void* *aRe nsresult rv; NS_ENSURE_NO_AGGREGATION(aOuter); nsKeygenFormProcessor* formProc = new nsKeygenFormProcessor(); + if (!formProc) + return NS_ERROR_OUT_OF_MEMORY; nsCOMPtr stabilize = formProc; rv = formProc->Init(); @@ -527,7 +533,7 @@ nsKeygenFormProcessor::GetPublicKey(nsAString& aValue, nsAString& aChallenge, bool found_match = false; do { end = strchr(str, ','); - if (end) + if (end != nullptr) *end = '\0'; primeBits = pqg_prime_bits(str); if (keysize == primeBits) { @@ -535,7 +541,7 @@ nsKeygenFormProcessor::GetPublicKey(nsAString& aValue, nsAString& aChallenge, break; } str = end + 1; - } while (end); + } while (end != nullptr); if (!found_match) { goto loser; } @@ -748,7 +754,7 @@ loser: if ( arena ) { PORT_FreeArena(arena, true); } - if (slot) { + if (slot != nullptr) { PK11_FreeSlot(slot); } if (KeygenRunnable) { diff --git a/security/manager/ssl/src/nsNSSASN1Object.cpp b/security/manager/ssl/src/nsNSSASN1Object.cpp index 47781a2259b..99df7c45e63 100644 --- a/security/manager/ssl/src/nsNSSASN1Object.cpp +++ b/security/manager/ssl/src/nsNSSASN1Object.cpp @@ -116,7 +116,7 @@ buildASN1ObjectFromDER(unsigned char *data, uint32_t type; rv = parent->GetASN1Objects(getter_AddRefs(parentObjects)); - if (NS_FAILED(rv) || !parentObjects) + if (NS_FAILED(rv) || parentObjects == nullptr) return NS_ERROR_FAILURE; while (data < end) { code = *data; @@ -193,7 +193,7 @@ CreateFromDER(unsigned char *data, sequence->GetASN1Objects(getter_AddRefs(elements)); nsCOMPtr asn1Obj = do_QueryElementAt(elements, 0); *retval = asn1Obj; - if (!*retval) + if (*retval == nullptr) return NS_ERROR_FAILURE; NS_ADDREF(*retval); @@ -218,7 +218,7 @@ nsNSSASN1Sequence::~nsNSSASN1Sequence() NS_IMETHODIMP nsNSSASN1Sequence::GetASN1Objects(nsIMutableArray * *aASN1Objects) { - if (!mASN1Objects) { + if (mASN1Objects == nullptr) { mASN1Objects = do_CreateInstance(NS_ARRAY_CONTRACTID); } *aASN1Objects = mASN1Objects; diff --git a/security/manager/ssl/src/nsNSSCallbacks.cpp b/security/manager/ssl/src/nsNSSCallbacks.cpp index f9b9084e4da..2489b0b4584 100644 --- a/security/manager/ssl/src/nsNSSCallbacks.cpp +++ b/security/manager/ssl/src/nsNSSCallbacks.cpp @@ -337,7 +337,7 @@ nsNSSHttpRequestSession::internal_send_receive_attempt(bool &retryable_error, volatile bool &waitFlag = mListener->mWaitFlag; waitFlag = true; - RefPtr event(new nsHTTPDownloadEvent); + nsRefPtr event = new nsHTTPDownloadEvent; if (!event) return SECFailure; @@ -401,8 +401,7 @@ nsNSSHttpRequestSession::internal_send_receive_attempt(bool &retryable_error, { request_canceled = true; - RefPtr cancelevent( - new nsCancelHTTPDownloadEvent); + nsRefPtr cancelevent = new nsCancelHTTPDownloadEvent; cancelevent->mListener = mListener; rv = NS_DispatchToMainThread(cancelevent); if (NS_FAILED(rv)) { @@ -724,7 +723,7 @@ void PK11PasswordPromptRunnable::RunOnTargetThread() else { prompt = do_GetInterface(mIR); - NS_ASSERTION(prompt, "callbacks does not implement nsIPrompt"); + NS_ASSERTION(prompt != nullptr, "callbacks does not implement nsIPrompt"); } if (!prompt) @@ -775,9 +774,9 @@ void PK11PasswordPromptRunnable::RunOnTargetThread() char* PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg) { - RefPtr runnable( + nsRefPtr runnable = new PK11PasswordPromptRunnable(slot, - static_cast(arg))); + static_cast(arg)); runnable->DispatchToMainThreadAndWait(); return runnable->mResult; } @@ -871,7 +870,7 @@ void HandshakeCallback(PRFileDesc* fd, void* client_data) { infoObject->SetShortSecurityDescription(shortDesc.get()); /* Set the SSL Status information */ - RefPtr status(infoObject->SSLStatus()); + nsRefPtr status = infoObject->SSLStatus(); if (!status) { status = new nsSSLStatus(); infoObject->SetSSLStatus(status); @@ -882,7 +881,7 @@ void HandshakeCallback(PRFileDesc* fd, void* client_data) { CERTCertificate *serverCert = SSL_PeerCertificate(fd); if (serverCert) { - RefPtr nssc(nsNSSCertificate::Create(serverCert)); + nsRefPtr nssc = nsNSSCertificate::Create(serverCert); CERT_DestroyCertificate(serverCert); serverCert = nullptr; diff --git a/security/manager/ssl/src/nsNSSCertHelper.cpp b/security/manager/ssl/src/nsNSSCertHelper.cpp index 860150c8ff2..a844312149d 100644 --- a/security/manager/ssl/src/nsNSSCertHelper.cpp +++ b/security/manager/ssl/src/nsNSSCertHelper.cpp @@ -5,7 +5,6 @@ #include "prerror.h" #include "prprf.h" -#include "mozilla/Scoped.h" #include "nsNSSCertHelper.h" #include "nsCOMPtr.h" #include "nsNSSCertificate.h" @@ -18,8 +17,6 @@ #include "nsNSSCertTrust.h" #include "nsIDateTimeFormat.h" #include "nsDateTimeFormatCID.h" - -using namespace mozilla; static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); @@ -89,6 +86,8 @@ ProcessVersion(SECItem *versionItem, nsresult rv; nsAutoString text; nsCOMPtr printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; nssComponent->GetPIPNSSBundleString("CertDumpVersion", text); rv = printableItem->SetDisplayName(text); @@ -144,6 +143,9 @@ ProcessSerialNumberDER(SECItem *serialItem, nsAutoString text; nsCOMPtr printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; + rv = nssComponent->GetPIPNSSBundleString("CertDumpSerialNo", text); if (NS_FAILED(rv)) return rv; @@ -154,7 +156,7 @@ ProcessSerialNumberDER(SECItem *serialItem, nsXPIDLCString serialNumber; serialNumber.Adopt(CERT_Hexify(serialItem, 1)); - if (!serialNumber) + if (serialNumber == nullptr) return NS_ERROR_OUT_OF_MEMORY; rv = printableItem->SetDisplayValue(NS_ConvertASCIItoUTF16(serialNumber)); @@ -829,17 +831,17 @@ ProcessExtKeyUsage(SECItem *extData, nsINSSComponent *nssComponent) { nsAutoString local; - CERTOidSequence *extKeyUsage = nullptr; + CERTOidSequence *extKeyUsage = NULL; SECItem **oids; SECItem *oid; nsresult rv; extKeyUsage = CERT_DecodeOidSequence(extData); - if (!extKeyUsage) + if (extKeyUsage == NULL) return NS_ERROR_FAILURE; oids = extKeyUsage->oids; - while (oids && *oids) { + while (oids != NULL && *oids != NULL) { // For each OID, try to find a bundle string // of the form CertDumpEKU_ nsAutoString oidname; @@ -899,7 +901,12 @@ ProcessRDN(CERTRDN* rdn, nsAString &finalString, nsINSSComponent *nssComponent) // We know we can fit buffer of this length. CERT_RFC1485_EscapeAndQuote // will fail if we provide smaller buffer then the result can fit to. int escapedValueCapacity = decodeItem->len * 3 + 3; - ScopedDeleteArray escapedValue(new char[escapedValueCapacity]); + nsAutoArrayPtr escapedValue; + escapedValue = new char[escapedValueCapacity]; + if (!escapedValue) { + SECITEM_FreeItem(decodeItem, true); + return NS_ERROR_OUT_OF_MEMORY; + } SECStatus status = CERT_RFC1485_EscapeAndQuote( escapedValue.get(), @@ -1275,7 +1282,7 @@ ProcessUserNotice(SECItem *der_notice, nsAString &text, nsINSSComponent *nssComponent) { - CERTUserNotice *notice = nullptr; + CERTUserNotice *notice = NULL; SECItem **itemList; PLArenaPool *arena; @@ -1284,7 +1291,7 @@ ProcessUserNotice(SECItem *der_notice, return NS_ERROR_FAILURE; notice = CERT_DecodeUserNotice(der_notice); - if (!notice) { + if (notice == NULL) { ProcessRawBytes(nssComponent, der_notice, text); goto finish; } @@ -1357,11 +1364,11 @@ ProcessCertificatePolicies(SECItem *extData, nsresult rv = NS_OK; policies = CERT_DecodeCertificatePoliciesExtension(extData); - if (!policies) + if ( policies == NULL ) return NS_ERROR_FAILURE; policyInfos = policies->policyInfos; - while (*policyInfos) { + while (*policyInfos != NULL ) { policyInfo = *policyInfos++; switch (policyInfo->oid) { case SEC_OID_VERISIGN_USER_NOTICES: @@ -1394,7 +1401,7 @@ ProcessCertificatePolicies(SECItem *extData, if (needColon) text.Append(NS_LITERAL_STRING(":")); text.Append(NS_LITERAL_STRING(SEPARATOR)); - while (*policyQualifiers) { + while (*policyQualifiers != NULL) { text.Append(NS_LITERAL_STRING(" ")); policyQualifier = *policyQualifiers++; switch(policyQualifier->oid) { @@ -1544,10 +1551,10 @@ ProcessAuthInfoAccess(SECItem *extData, return NS_ERROR_FAILURE; aia = CERT_DecodeAuthInfoAccessExtension(arena, extData); - if (!aia) + if (aia == NULL) goto finish; - while (*aia) { + while (*aia != NULL) { desc = *aia++; switch (SECOID_FindOIDTag(&desc->method)) { case SEC_OID_PKIX_OCSP: @@ -1678,11 +1685,13 @@ ProcessSingleExtension(CERTCertExtension *extension, nsAutoString text, extvalue; GetOIDText(&extension->id, nssComponent, text); nsCOMPtrextensionItem = new nsNSSASN1PrintableItem(); + if (extensionItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; extensionItem->SetDisplayName(text); SECOidTag oidTag = SECOID_FindOIDTag(&extension->id); text.Truncate(); - if (extension->critical.data) { + if (extension->critical.data != nullptr) { if (extension->critical.data[0]) { nssComponent->GetPIPNSSBundleString("CertDumpCritical", text); } else { @@ -1712,8 +1721,10 @@ ProcessSECAlgorithmID(SECAlgorithmID *algID, nsIASN1Sequence **retSequence) { SECOidTag algOIDTag = SECOID_FindOIDTag(&algID->algorithm); - SECItem paramsOID = { siBuffer, nullptr, 0 }; + SECItem paramsOID = { siBuffer, NULL, 0 }; nsCOMPtr sequence = new nsNSSASN1Sequence(); + if (sequence == nullptr) + return NS_ERROR_OUT_OF_MEMORY; *retSequence = nullptr; nsString text; @@ -1723,6 +1734,8 @@ ProcessSECAlgorithmID(SECAlgorithmID *algID, sequence->SetIsValidContainer(false); } else { nsCOMPtr printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayValue(text); nsCOMPtr asn1Objects; @@ -1732,6 +1745,8 @@ ProcessSECAlgorithmID(SECAlgorithmID *algID, printableItem->SetDisplayName(text); printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; asn1Objects->AppendElement(printableItem, false); nssComponent->GetPIPNSSBundleString("CertDumpParams", text); @@ -1784,6 +1799,8 @@ ProcessTime(PRTime dispTime, const PRUnichar *displayName, text.Append(NS_LITERAL_STRING(" GMT)")); nsCOMPtr printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayValue(text); printableItem->SetDisplayName(nsDependentString(displayName)); @@ -1800,6 +1817,9 @@ ProcessSubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki, { nsCOMPtr spkiSequence = new nsNSSASN1Sequence(); + if (spkiSequence == nullptr) + return NS_ERROR_OUT_OF_MEMORY; + nsString text; nssComponent->GetPIPNSSBundleString("CertDumpSPKI", text); spkiSequence->SetDisplayName(text); @@ -1816,12 +1836,14 @@ ProcessSubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki, asn1Objects->AppendElement(sequenceItem, false); nsCOMPtr printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; text.Truncate(); SECKEYPublicKey *key = SECKEY_ExtractPublicKey(spki); bool displayed = false; - if (key) { + if (key != NULL) { switch (key->keyType) { case rsaKey: { displayed = true; @@ -1895,6 +1917,8 @@ ProcessExtensions(CERTCertExtension **extensions, nsINSSComponent *nssComponent) { nsCOMPtr extensionSequence = new nsNSSASN1Sequence; + if (extensionSequence == nullptr) + return NS_ERROR_OUT_OF_MEMORY; nsString text; nssComponent->GetPIPNSSBundleString("CertDumpExtensions", text); @@ -1972,6 +1996,8 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, // The code in this method will assert this is the structure we're dealing // and then add more user friendly text for that field. nsCOMPtr sequence = new nsNSSASN1Sequence(); + if (sequence == nullptr) + return NS_ERROR_OUT_OF_MEMORY; nsString text; nssComponent->GetPIPNSSBundleString("CertDumpCertificate", text); @@ -2009,6 +2035,8 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, ProcessName(&mCert->issuer, nssComponent, getter_Copies(value)); printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayValue(value); nssComponent->GetPIPNSSBundleString("CertDumpIssuer", text); @@ -2039,6 +2067,8 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, nssComponent->GetPIPNSSBundleString("CertDumpSubject", text); printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayName(text); ProcessName(&mCert->subject, nssComponent,getter_Copies(value)); @@ -2052,7 +2082,7 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, SECItem data; // Is there an issuerUniqueID? - if (mCert->issuerID.data) { + if (mCert->issuerID.data != nullptr) { // The issuerID is encoded as a bit string. // The function ProcessRawBytes expects the // length to be in bytes, so let's convert the @@ -2062,6 +2092,8 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, ProcessRawBytes(nssComponent, &data, text); printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayValue(text); nssComponent->GetPIPNSSBundleString("CertDumpIssuerUniqueID", text); @@ -2079,6 +2111,8 @@ nsNSSCertificate::CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence, ProcessRawBytes(nssComponent, &data, text); printableItem = new nsNSSASN1PrintableItem(); + if (printableItem == nullptr) + return NS_ERROR_OUT_OF_MEMORY; printableItem->SetDisplayValue(text); nssComponent->GetPIPNSSBundleString("CertDumpSubjectUniqueID", text); @@ -2115,6 +2149,9 @@ nsNSSCertificate::CreateASN1Struct() nsCOMPtr sequence = new nsNSSASN1Sequence(); mASN1Structure = sequence; + if (mASN1Structure == nullptr) { + return NS_ERROR_OUT_OF_MEMORY; + } nsCOMPtr asn1Objects; sequence->GetASN1Objects(getter_AddRefs(asn1Objects)); @@ -2174,7 +2211,7 @@ getCertType(CERTCertificate *cert) return nsIX509Cert::SERVER_CERT; if (trust.HasPeer(false, true, false) && cert->emailAddr) return nsIX509Cert::EMAIL_CERT; - if (CERT_IsCACert(cert, nullptr)) + if (CERT_IsCACert(cert,NULL)) return nsIX509Cert::CA_CERT; if (cert->emailAddr) return nsIX509Cert::EMAIL_CERT; diff --git a/security/manager/ssl/src/nsNSSCertificate.cpp b/security/manager/ssl/src/nsNSSCertificate.cpp index bdb288b7118..54770e48dcd 100644 --- a/security/manager/ssl/src/nsNSSCertificate.cpp +++ b/security/manager/ssl/src/nsNSSCertificate.cpp @@ -38,6 +38,7 @@ #include "nsXULAppAPI.h" #include "nspr.h" +extern "C" { #include "pk11func.h" #include "certdb.h" #include "cert.h" @@ -45,14 +46,13 @@ #include "nssb64.h" #include "secasn1.h" #include "secder.h" +} #include "ssl.h" #include "ocsp.h" #include "plbase64.h" #include "cms.h" #include "cert.h" -using namespace mozilla; - #ifdef PR_LOGGING extern PRLogModuleInfo* gPIPNSSLog; #endif @@ -127,7 +127,7 @@ nsNSSCertificate::InitFromDER(char *certDER, int derLen) if (!aCert) return false; - if (!aCert->dbhandle) + if(aCert->dbhandle == nullptr) { aCert->dbhandle = CERT_GetDefaultCertDB(); } @@ -258,7 +258,7 @@ GetKeyUsagesString(CERTCertificate *cert, nsINSSComponent *nssComponent, text.Truncate(); SECItem keyUsageItem; - keyUsageItem.data = nullptr; + keyUsageItem.data = NULL; SECStatus srv; @@ -822,7 +822,7 @@ nsNSSCertificate::GetChain(nsIArray **_rvChain) NS_ENSURE_ARG(_rvChain); nsresult rv; /* Get the cert chain from NSS */ - CERTCertList *nssChain = nullptr; + CERTCertList *nssChain = NULL; PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting chain for \"%s\"\n", mCert->nickname)); nssChain = CERT_GetCertChainFromCert(mCert, PR_Now(), certUsageSSLClient); if (!nssChain) @@ -860,13 +860,13 @@ nsNSSCertificate::GetAllTokenNames(uint32_t *aLength, PRUnichar*** aTokenNames) NS_ENSURE_ARG(aLength); NS_ENSURE_ARG(aTokenNames); *aLength = 0; - *aTokenNames = nullptr; + *aTokenNames = NULL; /* Get the slots from NSS */ - PK11SlotList *slots = nullptr; + PK11SlotList *slots = NULL; PK11SlotListCleaner slotCleaner(slots); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting slots for \"%s\"\n", mCert->nickname)); - slots = PK11_GetAllSlotsForCert(mCert, nullptr); + slots = PK11_GetAllSlotsForCert(mCert, NULL); if (!slots) { if (PORT_GetError() == SEC_ERROR_NO_TOKEN) return NS_OK; // List of slots is empty, return empty array @@ -894,7 +894,7 @@ nsNSSCertificate::GetAllTokenNames(uint32_t *aLength, PRUnichar*** aTokenNames) if (!(*aTokenNames)[iToken]) { NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(iToken, *aTokenNames); *aLength = 0; - *aTokenNames = nullptr; + *aTokenNames = NULL; return NS_ERROR_OUT_OF_MEMORY; } } @@ -1201,6 +1201,8 @@ nsNSSCertificate::GetValidity(nsIX509CertValidity **aValidity) NS_ENSURE_ARG(aValidity); nsX509CertValidity *validity = new nsX509CertValidity(mCert); + if (nullptr == validity) + return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(validity); *aValidity = static_cast(validity); @@ -1220,7 +1222,7 @@ nsNSSCertificate::VerifyForUsage(uint32_t usage, uint32_t *verificationResult) nsCOMPtr inss = do_GetService(kNSSComponentCID, &nsrv); if (!inss) return nsrv; - RefPtr survivingParams; + nsRefPtr survivingParams; nsrv = inss->GetDefaultCERTValInParam(survivingParams); if (NS_FAILED(nsrv)) return nsrv; @@ -1285,14 +1287,14 @@ nsNSSCertificate::VerifyForUsage(uint32_t usage, uint32_t *verificationResult) if (!nsNSSComponent::globalConstFlagUsePKIXVerification) { CERTCertDBHandle *defaultcertdb = CERT_GetDefaultCertDB(); verify_result = CERT_VerifyCertificateNow(defaultcertdb, mCert, true, - nss_usage, nullptr, nullptr); + nss_usage, NULL, NULL); } else { CERTValOutParam cvout[1]; cvout[0].type = cert_po_end; verify_result = CERT_PKIXVerifyCert(mCert, nss_usage, survivingParams->GetRawPointerForNSS(), - cvout, nullptr); + cvout, NULL); } if (verify_result == SECSuccess) @@ -1393,6 +1395,8 @@ nsNSSCertificate::RequestUsagesArrayAsync(nsICertVerificationListener *aResultLi return NS_ERROR_FAILURE; nsCertVerificationJob *job = new nsCertVerificationJob; + if (!job) + return NS_ERROR_OUT_OF_MEMORY; job->mCert = this; job->mListener = aResultListener; @@ -1477,7 +1481,7 @@ nsNSSCertificate::GetASN1Structure(nsIASN1Object * *aASN1Structure) nsNSSShutDownPreventionLock locker; nsresult rv = NS_OK; NS_ENSURE_ARG_POINTER(aASN1Structure); - if (!mASN1Structure) { + if (mASN1Structure == nullptr) { // First create the recursive structure os ASN1Objects // which tells us the layout of the cert. rv = CreateASN1Struct(); @@ -1569,7 +1573,7 @@ char* nsNSSCertificate::defaultServerNickname(CERTCertificate* cert) else { nickname = PR_smprintf("%s #%d", servername, count); } - if (!nickname) { + if (nickname == NULL) { break; } @@ -1617,12 +1621,12 @@ nsNSSCertList::AddCert(nsIX509Cert *aCert) CERTCertificate *cert; cert = nssCert->GetCert(); - if (!cert) { + if (cert == nullptr) { NS_ERROR("Somehow got nullptr for mCertificate in nsNSSCertificate."); return NS_ERROR_FAILURE; } - if (!mCertList) { + if (mCertList == nullptr) { NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList."); return NS_ERROR_FAILURE; } @@ -1640,12 +1644,12 @@ nsNSSCertList::DeleteCert(nsIX509Cert *aCert) CERTCertificate *cert = nssCert->GetCert(); CERTCertListNode *node; - if (!cert) { + if (cert == nullptr) { NS_ERROR("Somehow got nullptr for mCertificate in nsNSSCertificate."); return NS_ERROR_FAILURE; } - if (!mCertList) { + if (mCertList == nullptr) { NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList."); return NS_ERROR_FAILURE; } @@ -1668,7 +1672,7 @@ nsNSSCertList::DupCertList(CERTCertList *aCertList) CERTCertList *newList = CERT_NewCertList(); - if (!newList) { + if (newList == nullptr) { return nullptr; } @@ -1692,6 +1696,9 @@ NS_IMETHODIMP nsNSSCertList::GetEnumerator(nsISimpleEnumerator **_retval) { nsCOMPtr enumerator = new nsNSSCertListEnumerator(mCertList); + if (!enumerator) { + return NS_ERROR_OUT_OF_MEMORY; + } *_retval = enumerator; NS_ADDREF(*_retval); diff --git a/security/manager/ssl/src/nsNSSCertificate.h b/security/manager/ssl/src/nsNSSCertificate.h index d4fabfa24a1..af6c3e7f25a 100644 --- a/security/manager/ssl/src/nsNSSCertificate.h +++ b/security/manager/ssl/src/nsNSSCertificate.h @@ -14,7 +14,6 @@ #include "nsIASN1Object.h" #include "nsISMimeCert.h" #include "nsIIdentityInfo.h" -#include "nsCOMPtr.h" #include "nsNSSShutDown.h" #include "nsISimpleEnumerator.h" #include "nsISerializable.h" diff --git a/security/manager/ssl/src/nsNSSCertificateDB.cpp b/security/manager/ssl/src/nsNSSCertificateDB.cpp index 7905dc8d4fc..b89a7e90af8 100644 --- a/security/manager/ssl/src/nsNSSCertificateDB.cpp +++ b/security/manager/ssl/src/nsNSSCertificateDB.cpp @@ -27,6 +27,7 @@ #include "nsThreadUtils.h" #include "nspr.h" +extern "C" { #include "pk11func.h" #include "certdb.h" #include "cert.h" @@ -34,18 +35,16 @@ #include "nssb64.h" #include "secasn1.h" #include "secder.h" +} #include "ssl.h" #include "ocsp.h" #include "plbase64.h" -#include "nsNSSCleaner.h" - -using namespace mozilla; - #ifdef PR_LOGGING extern PRLogModuleInfo* gPIPNSSLog; #endif +#include "nsNSSCleaner.h" NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) NSSCleanupAutoPtrClass(CERTCertList, CERT_DestroyCertList) NSSCleanupAutoPtrClass(CERTCertificateList, CERT_DestroyCertificateList) @@ -70,20 +69,20 @@ nsNSSCertificateDB::FindCertByNickname(nsISupports *aToken, nsIX509Cert **_rvCert) { nsNSSShutDownPreventionLock locker; - CERTCertificate *cert = nullptr; - char *asciiname = nullptr; + CERTCertificate *cert = NULL; + char *asciiname = NULL; NS_ConvertUTF16toUTF8 aUtf8Nickname(nickname); asciiname = const_cast(aUtf8Nickname.get()); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname)); #if 0 // what it should be, but for now... if (aToken) { - cert = PK11_FindCertFromNickname(asciiname, nullptr); + cert = PK11_FindCertFromNickname(asciiname, NULL); } else { cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), asciiname); } #endif - cert = PK11_FindCertFromNickname(asciiname, nullptr); + cert = PK11_FindCertFromNickname(asciiname, NULL); if (!cert) { cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), asciiname); } @@ -144,7 +143,7 @@ nsNSSCertificateDB::FindCertByDBKey(const char *aDBkey, nsISupports *aToken, if (cert) { nsNSSCertificate *nssCert = nsNSSCertificate::Create(cert); CERT_DestroyCertificate(cert); - if (!nssCert) + if (nssCert == nullptr) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(nssCert); *_cert = static_cast(nssCert); @@ -163,7 +162,7 @@ nsNSSCertificateDB::FindCertNicknames(nsISupports *aToken, /* * obtain the cert list from NSS */ - CERTCertList *certList = nullptr; + CERTCertList *certList = NULL; PK11CertListType pk11type; #if 0 // this would seem right, but it didn't work... @@ -173,7 +172,7 @@ nsNSSCertificateDB::FindCertNicknames(nsISupports *aToken, else #endif pk11type = PK11CertListUnique; - certList = PK11_ListCerts(pk11type, nullptr); + certList = PK11_ListCerts(pk11type, NULL); if (!certList) goto cleanup; /* @@ -203,7 +202,7 @@ collect_certs(void *arg, SECItem **certs, int numcerts) collectArgs->numcerts = numcerts; collectArgs->rawCerts = (SECItem *) PORT_ArenaZAlloc(collectArgs->arena, sizeof(SECItem) * numcerts); - if (!collectArgs->rawCerts) + if ( collectArgs->rawCerts == NULL ) return(SECFailure); cert = collectArgs->rawCerts; @@ -226,7 +225,7 @@ nsNSSCertificateDB::getCertsFromPackage(PLArenaPool *arena, uint8_t *data, nsNSSShutDownPreventionLock locker; CERTDERCerts *collectArgs = (CERTDERCerts *)PORT_ArenaZAlloc(arena, sizeof(CERTDERCerts)); - if (!collectArgs) + if ( collectArgs == nullptr ) return nullptr; collectArgs->arena = arena; @@ -348,7 +347,7 @@ nsNSSCertificateDB::handleCACertDownload(nsIArray *x509Certs, CERTCertificateCleaner tmpCertCleaner(tmpCert); - if (!CERT_IsCACert(tmpCert, nullptr)) { + if (!CERT_IsCACert(tmpCert, NULL)) { DisplayCertificateAlert(ctx, "NotACACert", certToShow); return NS_ERROR_FAILURE; } @@ -390,7 +389,7 @@ nsNSSCertificateDB::handleCACertDownload(nsIArray *x509Certs, // build a CertList for filtering CERTCertList *certList = CERT_NewCertList(); - if (!certList) { + if (certList == NULL) { return NS_ERROR_FAILURE; } @@ -494,8 +493,8 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, SECStatus srv = SECFailure; nsresult nsrv = NS_OK; CERTCertDBHandle *certdb; - CERTCertificate **certArray = nullptr; - CERTCertList *certList = nullptr; + CERTCertificate **certArray = NULL; + CERTCertList *certList = NULL; CERTCertListNode *node; PRTime now; SECCertUsage certusage; @@ -509,7 +508,7 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, nsCOMPtr inss = do_GetService(kNSSComponentCID, &nsrv); if (!inss) return nsrv; - RefPtr survivingParams; + nsRefPtr survivingParams; nsrv = inss->GetDefaultCERTValInParam(survivingParams); if (NS_FAILED(nsrv)) return nsrv; @@ -541,10 +540,10 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, } srv = CERT_ImportCerts(certdb, certusage, numcerts, rawArray, - &certArray, false, false, nullptr); + &certArray, false, false, NULL); PORT_Free(rawArray); - rawArray = nullptr; + rawArray = NULL; if (srv != SECSuccess) { nsrv = NS_ERROR_FAILURE; @@ -553,7 +552,7 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, // build a CertList for filtering certList = CERT_NewCertList(); - if (!certList) { + if (certList == NULL) { nsrv = NS_ERROR_FAILURE; goto loser; } @@ -582,7 +581,7 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, if (!nsNSSComponent::globalConstFlagUsePKIXVerification) { if (CERT_VerifyCert(certdb, node->cert, - true, certusage, now, ctx, nullptr) != SECSuccess) { + true, certusage, now, ctx, NULL) != SECSuccess) { alert_and_skip = true; } } @@ -624,9 +623,9 @@ nsNSSCertificateDB::ImportEmailCertificate(uint8_t * data, uint32_t length, rawArray[i] = &certChain->certs[i]; } CERT_ImportCerts(certdb, certusage, certChain->len, - rawArray, nullptr, true, false, nullptr); + rawArray, NULL, true, false, NULL); - CERT_SaveSMimeProfile(node->cert, nullptr, nullptr); + CERT_SaveSMimeProfile(node->cert, NULL, NULL); PORT_Free(rawArray); } @@ -668,7 +667,7 @@ nsNSSCertificateDB::ImportServerCertificate(uint8_t * data, uint32_t length, return NS_ERROR_FAILURE; } cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), certCollection->rawCerts, - nullptr, false, true); + (char *)NULL, false, true); if (!cert) { nsrv = NS_ERROR_FAILURE; goto loser; @@ -686,7 +685,7 @@ nsNSSCertificateDB::ImportServerCertificate(uint8_t * data, uint32_t length, serverNickname = nsNSSCertificate::defaultServerNickname(cert); srv = CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageSSLServer, - numcerts, rawCerts, nullptr, true, false, + numcerts, rawCerts, NULL, true, false, serverNickname); PR_FREEIF(serverNickname); if ( srv != SECSuccess ) { @@ -712,12 +711,12 @@ loser: nsresult nsNSSCertificateDB::ImportValidCACerts(int numCACerts, SECItem *CACerts, nsIInterfaceRequestor *ctx) { - CERTCertList *certList = nullptr; + CERTCertList *certList = NULL; SECItem **rawArray; // build a CertList for filtering certList = CERT_NewCertList(); - if (!certList) { + if (certList == NULL) { return NS_ERROR_FAILURE; } @@ -725,7 +724,7 @@ nsNSSCertificateDB::ImportValidCACerts(int numCACerts, SECItem *CACerts, nsIInte // get all certs into temp store SECStatus srv = SECFailure; - CERTCertificate **certArray = nullptr; + CERTCertificate **certArray = NULL; rawArray = (SECItem **) PORT_Alloc(sizeof(SECItem *) * numCACerts); if ( !rawArray ) { @@ -737,10 +736,10 @@ nsNSSCertificateDB::ImportValidCACerts(int numCACerts, SECItem *CACerts, nsIInte } srv = CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageAnyCA, numCACerts, rawArray, - &certArray, false, true, nullptr); + &certArray, false, true, NULL); PORT_Free(rawArray); - rawArray = nullptr; + rawArray = NULL; if (srv != SECSuccess) { return NS_ERROR_FAILURE; @@ -767,7 +766,7 @@ nsNSSCertificateDB::ImportValidCACertsInList(CERTCertList *certList, nsIInterfac nsCOMPtr inss = do_GetService(kNSSComponentCID, &nsrv); if (!inss) return nsrv; - RefPtr survivingParams; + nsRefPtr survivingParams; nsrv = inss->GetDefaultCERTValInParam(survivingParams); if (NS_FAILED(nsrv)) return nsrv; @@ -793,7 +792,7 @@ nsNSSCertificateDB::ImportValidCACertsInList(CERTCertList *certList, nsIInterfac if (!nsNSSComponent::globalConstFlagUsePKIXVerification) { if (CERT_VerifyCert(CERT_GetDefaultCertDB(), node->cert, - true, certUsageVerifyCA, PR_Now(), ctx, nullptr) != SECSuccess) { + true, certUsageVerifyCA, PR_Now(), ctx, NULL) != SECSuccess) { alert_and_skip = true; } } @@ -835,7 +834,7 @@ nsNSSCertificateDB::ImportValidCACertsInList(CERTCertList *certList, nsIInterfac rawArray[i] = &certChain->certs[i]; } CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageAnyCA, certChain->len, - rawArray, nullptr, true, true, nullptr); + rawArray, NULL, true, true, NULL); PORT_Free(rawArray); } @@ -894,10 +893,10 @@ nsNSSCertificateDB::ImportUserCertificate(uint8_t *data, uint32_t length, nsIInt SECItem *CACerts; CERTDERCerts * collectArgs; PLArenaPool *arena; - CERTCertificate * cert = nullptr; + CERTCertificate * cert=NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) { + if ( arena == NULL ) { goto loser; } @@ -907,13 +906,13 @@ nsNSSCertificateDB::ImportUserCertificate(uint8_t *data, uint32_t length, nsIInt } cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), collectArgs->rawCerts, - nullptr, false, true); + (char *)NULL, false, true); if (!cert) { goto loser; } - slot = PK11_KeyForCertExists(cert, nullptr, ctx); - if (!slot) { + slot = PK11_KeyForCertExists(cert, NULL, ctx); + if ( slot == NULL ) { nsCOMPtr certToShow = nsNSSCertificate::Create(cert); DisplayCertificateAlert(ctx, "UserCertIgnoredNoPrivateKey", certToShow); goto loser; @@ -1136,6 +1135,8 @@ nsNSSCertificateDB::ImportCertsFromFile(nsISupports *aToken, return NS_ERROR_FAILURE; unsigned char *buf = new unsigned char[file_info.size]; + if (!buf) + return NS_ERROR_OUT_OF_MEMORY; int32_t bytes_obtained = PR_Read(fd, buf, file_info.size); PR_Close(fd); @@ -1306,7 +1307,7 @@ nsNSSCertificateDB::getCertNames(CERTCertList *certList, nsNSSShutDownPreventionLock locker; CERTCertListNode *node; uint32_t numcerts = 0, i=0; - PRUnichar **tmpArray = nullptr; + PRUnichar **tmpArray = NULL; PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("List of certs %d:\n", type)); for (node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList); @@ -1324,8 +1325,8 @@ nsNSSCertificateDB::getCertNames(CERTCertList *certList, node = CERT_LIST_NEXT(node)) { if (getCertType(node->cert) == type) { nsNSSCertificate pipCert(node->cert); - char *dbkey = nullptr; - char *namestr = nullptr; + char *dbkey = NULL; + char *namestr = NULL; nsAutoString certstr; pipCert.GetDbKey(&dbkey); nsAutoString keystr = NS_ConvertASCIItoUTF16(dbkey); @@ -1383,7 +1384,7 @@ nsNSSCertificateDB::FindEmailEncryptionCert(const nsAString &aNickname, nsIX509C CERTCertificate *cert = 0; nsCOMPtr ctx = new PipUIContext(); nsNSSCertificate *nssCert = nullptr; - char *asciiname = nullptr; + char *asciiname = NULL; NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname); asciiname = const_cast(aUtf8Nickname.get()); @@ -1394,7 +1395,7 @@ nsNSSCertificateDB::FindEmailEncryptionCert(const nsAString &aNickname, nsIX509C if (!cert) { goto loser; } nssCert = nsNSSCertificate::Create(cert); - if (!nssCert) { + if (nssCert == nullptr) { rv = NS_ERROR_OUT_OF_MEMORY; } NS_ADDREF(nssCert); @@ -1423,7 +1424,7 @@ nsNSSCertificateDB::FindEmailSigningCert(const nsAString &aNickname, nsIX509Cert CERTCertificate *cert = 0; nsCOMPtr ctx = new PipUIContext(); nsNSSCertificate *nssCert = nullptr; - char *asciiname = nullptr; + char *asciiname = NULL; NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname); asciiname = const_cast(aUtf8Nickname.get()); @@ -1434,7 +1435,7 @@ nsNSSCertificateDB::FindEmailSigningCert(const nsAString &aNickname, nsIX509Cert if (!cert) { goto loser; } nssCert = nsNSSCertificate::Create(cert); - if (!nssCert) { + if (nssCert == nullptr) { rv = NS_ERROR_OUT_OF_MEMORY; } NS_ADDREF(nssCert); @@ -1452,7 +1453,7 @@ nsNSSCertificateDB::FindCertByEmailAddress(nsISupports *aToken, const char *aEma nsNSSShutDownPreventionLock locker; nsCOMPtr inss; - RefPtr survivingParams; + nsRefPtr survivingParams; nsresult nsrv; if (nsNSSComponent::globalConstFlagUsePKIXVerification) { @@ -1527,7 +1528,7 @@ nsNSSCertificateDB::ConstructX509FromBase64(const char *base64, // sure would be nice to have a smart pointer class for PL_ allocations // unfortunately, we cannot distinguish out-of-memory from bad-input here uint32_t len = PL_strlen(base64); - char *certDER = PL_Base64Decode(base64, len, nullptr); + char *certDER = PL_Base64Decode(base64, len, NULL); if (!certDER) return NS_ERROR_ILLEGAL_VALUE; if (!*certDER) { @@ -1664,7 +1665,7 @@ nsNSSCertificateDB::get_default_nickname(CERTCertificate *cert, * card. */ dummycert = PK11_FindCertFromNickname(nickname.get(), ctx); - if (dummycert) { + if (dummycert != NULL) { /* * Make sure the subject names are different. */ @@ -1676,7 +1677,7 @@ nsNSSCertificateDB::get_default_nickname(CERTCertificate *cert, * nickname. */ CERT_DestroyCertificate(dummycert); - dummycert = nullptr; + dummycert = NULL; } } } @@ -1752,9 +1753,10 @@ nsNSSCertificateDB::GetCerts(nsIX509CertList **_retval) nsCOMPtr nssCertList; certList = PK11_ListCerts(PK11CertListUnique, ctx); - // nsNSSCertList 1) adopts certList, and 2) handles the nullptr case fine. + // nsNSSCertList 1) adopts certList, and 2) handles the NULL case fine. // (returns an empty list) nssCertList = new nsNSSCertList(certList, true); + if (!nssCertList) { return NS_ERROR_OUT_OF_MEMORY; } *_retval = nssCertList; NS_ADDREF(*_retval); diff --git a/security/manager/ssl/src/nsNSSComponent.cpp b/security/manager/ssl/src/nsNSSComponent.cpp index 949fe243a91..2ab940e53ba 100644 --- a/security/manager/ssl/src/nsNSSComponent.cpp +++ b/security/manager/ssl/src/nsNSSComponent.cpp @@ -36,6 +36,7 @@ #include "nsIDOMSmartCardEvent.h" #include "nsIDOMCrypto.h" #include "nsThreadUtils.h" +#include "nsAutoPtr.h" #include "nsCRT.h" #include "nsCRLInfo.h" #include "nsCertOverrideService.h" @@ -77,8 +78,10 @@ #include "nsILocalFileWin.h" #endif +extern "C" { #include "pkcs12.h" #include "p12plcy.h" +} using namespace mozilla; using namespace mozilla::psm; @@ -319,7 +322,7 @@ nsNSSComponent::nsNSSComponent() mNSSInitialized(false), mCrlTimerLock("nsNSSComponent.mCrlTimerLock"), mThreadList(nullptr), - mCertVerificationThread(nullptr) + mCertVerificationThread(NULL) { #ifdef PR_LOGGING if (!gPIPNSSLog) @@ -357,7 +360,7 @@ nsNSSComponent::deleteBackgroundThreads() void nsNSSComponent::createBackgroundThreads() { - NS_ASSERTION(!mCertVerificationThread, + NS_ASSERTION(mCertVerificationThread == nullptr, "Cert verification thread already created."); mCertVerificationThread = new nsCertVerificationThread; @@ -384,7 +387,7 @@ nsNSSComponent::~nsNSSComponent() } crlDownloadTimerOn = false; } - if (crlsScheduledForDownload) { + if(crlsScheduledForDownload != nullptr){ crlsScheduledForDownload->Reset(); delete crlsScheduledForDownload; } @@ -413,6 +416,9 @@ nsNSSComponent::PostEvent(const nsAString &eventType, { nsCOMPtr runnable = new nsTokenEventRunnable(eventType, tokenName); + if (!runnable) { + return NS_ERROR_OUT_OF_MEMORY; + } return NS_DispatchToMainThread(runnable); } @@ -508,7 +514,7 @@ nsNSSComponent::DispatchEventToWindow(nsIDOMWindow *domWin, // find the document nsCOMPtr doc; rv = domWin->GetDocument(getter_AddRefs(doc)); - if (!doc) { + if (doc == nullptr) { return NS_FAILED(rv) ? rv : NS_ERROR_FAILURE; } @@ -527,6 +533,10 @@ nsNSSComponent::DispatchEventToWindow(nsIDOMWindow *domWin, new nsSmartCardEvent(tokenName); // init the smart card event, fail here if we can't complete the // initialization. + if (!smartCardEvent) { + return NS_ERROR_OUT_OF_MEMORY; + } + rv = smartCardEvent->Init(event); if (NS_FAILED(rv)) { return rv; @@ -653,10 +663,16 @@ nsNSSComponent::LaunchSmartCardThread(SECMODModule *module) { SmartCardMonitoringThread *newThread; if (SECMOD_HasRemovableSlots(module)) { - if (!mThreadList) { + if (mThreadList == nullptr) { mThreadList = new SmartCardThreadList(); + if (!mThreadList) { + return NS_ERROR_OUT_OF_MEMORY; + } } newThread = new SmartCardMonitoringThread(module); + if (!newThread) { + return NS_ERROR_OUT_OF_MEMORY; + } // newThread is adopted by the add. return mThreadList->Add(newThread); } @@ -696,8 +712,8 @@ nss_addEscape(const char *string, char quote) } newString = (char*)PORT_ZAlloc(escapes+size+1); - if (!newString) { - return nullptr; + if (newString == NULL) { + return NULL; } for (src=string, dest=newString; *src; src++,dest++) { @@ -1038,7 +1054,7 @@ static CipherPref CipherPrefs[] = { {"security.ssl3.rsa_null_sha", SSL_RSA_WITH_NULL_SHA}, // No encryption with RSA authentication and a SHA1 MAC {"security.ssl3.rsa_null_md5", SSL_RSA_WITH_NULL_MD5}, // No encryption with RSA authentication and an MD5 MAC {"security.ssl3.rsa_seed_sha", TLS_RSA_WITH_SEED_CBC_SHA}, // SEED encryption with RSA and a SHA1 MAC - {nullptr, 0} /* end marker */ + {NULL, 0} /* end marker */ }; static void @@ -1126,7 +1142,7 @@ void nsNSSComponent::setValidationOptions(nsIPrefBranch * pref) ocspMode_FailureIsVerificationFailure : ocspMode_FailureIsNotAVerificationFailure); - RefPtr newCVIN(new nsCERTValInParamWrapper); + nsRefPtr newCVIN = new nsCERTValInParamWrapper; if (NS_SUCCEEDED(newCVIN->Construct( aiaDownloadEnabled ? nsCERTValInParamWrapper::missing_cert_download_on : nsCERTValInParamWrapper::missing_cert_download_off, @@ -1185,6 +1201,8 @@ nsNSSComponent::PostCRLImportEvent(const nsCSubstring &urlString, { //Create the event nsCOMPtr event = new CRLDownloadEvent(urlString, listener); + if (!event) + return NS_ERROR_OUT_OF_MEMORY; //Get a handle to the ui thread return NS_DispatchToMainThread(event); @@ -1209,8 +1227,8 @@ nsresult nsNSSComponent::DownloadCrlSilently() crlsScheduledForDownload->Put(&hashKey,(void *)nullptr); //Set up the download handler - RefPtr psmDownloader( - new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL)); + nsRefPtr psmDownloader = + new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL); psmDownloader->setSilentDownload(true); psmDownloader->setCrlAutodownloadKey(mCrlUpdateKey); @@ -1421,7 +1439,7 @@ nsNSSComponent::StopCRLUpdateTimer() //If it is at all running. if (mUpdateTimerInitialized) { - if (crlsScheduledForDownload) { + if(crlsScheduledForDownload != nullptr){ crlsScheduledForDownload->Reset(); delete crlsScheduledForDownload; crlsScheduledForDownload = nullptr; @@ -1627,7 +1645,7 @@ nsNSSComponent::InitializeNSS(bool showWarningBox) if (NS_FAILED(rv)) { PR_LOG(gPIPNSSLog, PR_LOG_ERROR, ("Unable to get profile directory\n")); ConfigureInternalPKCS11Token(); - SECStatus init_rv = NSS_NoDB_Init(nullptr); + SECStatus init_rv = NSS_NoDB_Init(NULL); if (init_rv != SECSuccess) { nsPSMInitPanic::SetPanic(); return NS_ERROR_NOT_AVAILABLE; @@ -2046,7 +2064,7 @@ static PRBool DecryptionAllowedCallback(SECAlgorithmID *algid, static void * GetPasswordKeyCallback(void *arg, void *handle) { - return nullptr; + return NULL; } NS_IMETHODIMP @@ -2617,7 +2635,7 @@ nsNSSComponent::IsNSSInitialized(bool *initialized) } NS_IMETHODIMP -nsNSSComponent::GetDefaultCERTValInParam(RefPtr &out) +nsNSSComponent::GetDefaultCERTValInParam(nsRefPtr &out) { MutexAutoLock lock(mutex); if (!mNSSInitialized) @@ -2627,7 +2645,7 @@ nsNSSComponent::GetDefaultCERTValInParam(RefPtr &out) } NS_IMETHODIMP -nsNSSComponent::GetDefaultCERTValInParamLocalOnly(RefPtr &out) +nsNSSComponent::GetDefaultCERTValInParamLocalOnly(nsRefPtr &out) { MutexAutoLock lock(mutex); if (!mNSSInitialized) @@ -3173,7 +3191,7 @@ PSMContentDownloader::OnDataAvailable(nsIRequest* request, size_t newSize = (mBufferOffset + aLength) *2; // grow some more than needed char *newBuffer; newBuffer = (char*)nsMemory::Realloc(mByteData, newSize); - if (!newBuffer) { + if (newBuffer == nullptr) { return NS_ERROR_OUT_OF_MEMORY; } mByteData = newBuffer; diff --git a/security/manager/ssl/src/nsNSSComponent.h b/security/manager/ssl/src/nsNSSComponent.h index 2391d95565d..efa83c2c431 100644 --- a/security/manager/ssl/src/nsNSSComponent.h +++ b/security/manager/ssl/src/nsNSSComponent.h @@ -8,7 +8,6 @@ #define _nsNSSComponent_h_ #include "mozilla/Mutex.h" -#include "mozilla/RefPtr.h" #include "nsCOMPtr.h" #include "nsISignatureVerifier.h" #include "nsIURIContentListener.h" @@ -160,10 +159,8 @@ class NS_NO_VTABLE nsINSSComponent : public nsISupports { NS_IMETHOD IsNSSInitialized(bool *initialized) = 0; - NS_IMETHOD GetDefaultCERTValInParam( - mozilla::RefPtr &out) = 0; - NS_IMETHOD GetDefaultCERTValInParamLocalOnly( - mozilla::RefPtr &out) = 0; + NS_IMETHOD GetDefaultCERTValInParam(nsRefPtr &out) = 0; + NS_IMETHOD GetDefaultCERTValInParamLocalOnly(nsRefPtr &out) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsINSSComponent, NS_INSSCOMPONENT_IID) @@ -263,10 +260,8 @@ public: NS_IMETHOD EnsureIdentityInfoLoaded(); NS_IMETHOD IsNSSInitialized(bool *initialized); - NS_IMETHOD GetDefaultCERTValInParam( - mozilla::RefPtr &out); - NS_IMETHOD GetDefaultCERTValInParamLocalOnly( - mozilla::RefPtr &out); + NS_IMETHOD GetDefaultCERTValInParam(nsRefPtr &out); + NS_IMETHOD GetDefaultCERTValInParamLocalOnly(nsRefPtr &out); private: nsresult InitializeNSS(bool showWarningBox); @@ -327,9 +322,9 @@ private: nsCertVerificationThread *mCertVerificationThread; nsNSSHttpInterface mHttpForNSS; - mozilla::RefPtr mClientAuthRememberService; - mozilla::RefPtr mDefaultCERTValInParam; - mozilla::RefPtr mDefaultCERTValInParamLocalOnly; + nsRefPtr mClientAuthRememberService; + nsRefPtr mDefaultCERTValInParam; + nsRefPtr mDefaultCERTValInParamLocalOnly; static PRStatus IdentityInfoInit(void); PRCallOnceType mIdentityInfoCallOnce; diff --git a/security/manager/ssl/src/nsNSSIOLayer.cpp b/security/manager/ssl/src/nsNSSIOLayer.cpp index e2208d969e5..2df64002e58 100644 --- a/security/manager/ssl/src/nsNSSIOLayer.cpp +++ b/security/manager/ssl/src/nsNSSIOLayer.cpp @@ -147,7 +147,7 @@ static void getSecureBrowserUI(nsIInterfaceRequestor * callbacks, nsISecureBrowserUI ** result) { - NS_ASSERTION(result, "result parameter to getSecureBrowserUI is null"); + NS_ASSERTION(result != nullptr, "result parameter to getSecureBrowserUI is null"); *result = nullptr; NS_ASSERTION(NS_IsMainThread(), @@ -373,7 +373,7 @@ void nsNSSSocketInfo::GetPreviousCert(nsIX509Cert** _result) NS_ASSERTION(_result, "_result parameter to GetPreviousCert is null"); *_result = nullptr; - RefPtr runnable(new PreviousCertRunnable(mCallbacks)); + nsRefPtr runnable = new PreviousCertRunnable(mCallbacks); nsresult rv = runnable->DispatchToMainThreadAndWait(); NS_ASSERTION(NS_SUCCEEDED(rv), "runnable->DispatchToMainThreadAndWait() failed"); runnable->mPreviousCert.forget(_result); @@ -834,7 +834,7 @@ class SSLErrorRunnable : public SyncRunnableBase nsHandleSSLError(mInfoObject, mErrType, mErrorCode); } - RefPtr mInfoObject; + nsRefPtr mInfoObject; ::mozilla::psm::SSLErrorMessageType mErrType; const PRErrorCode mErrorCode; }; @@ -908,9 +908,9 @@ int32_t checkHandshake(int32_t bytesTransfered, bool wasReading, // expensive no-op.) if (!wantRetry && (IS_SSL_ERROR(err) || IS_SEC_ERROR(err)) && !socketInfo->GetErrorCode()) { - RefPtr runnable(new SSLErrorRunnable(socketInfo, - PlainErrorMessage, - err)); + nsRefPtr runnable = new SSLErrorRunnable(socketInfo, + PlainErrorMessage, + err); (void) runnable->DispatchToMainThreadAndWait(); } } @@ -1042,7 +1042,7 @@ static PRFileDesc *_PSM_InvalidDesc(void) { PR_ASSERT(!"I/O method is invalid"); PR_SetError(PR_INVALID_METHOD_ERROR, 0); - return nullptr; + return NULL; } static PRStatus PSMGetsockname(PRFileDesc *fd, PRNetAddr *addr) @@ -1212,15 +1212,24 @@ nsresult nsSSLIOLayerHelpers::Init() mutex = new Mutex("nsSSLIOLayerHelpers.mutex"); mTLSIntolerantSites = new nsTHashtable(); + if (!mTLSIntolerantSites) + return NS_ERROR_OUT_OF_MEMORY; + mTLSIntolerantSites->Init(1); mTLSTolerantSites = new nsTHashtable(); + if (!mTLSTolerantSites) + return NS_ERROR_OUT_OF_MEMORY; + // Initialize the tolerant site hashtable to 16 items at the start seems // reasonable as most servers are TLS tolerant. We just want to lower // the rate of hashtable array reallocation. mTLSTolerantSites->Init(16); mRenegoUnrestrictedSites = new nsTHashtable(); + if (!mRenegoUnrestrictedSites) + return NS_ERROR_OUT_OF_MEMORY; + mRenegoUnrestrictedSites->Init(1); mTreatUnsafeNegotiationAsBroken = false; @@ -1353,7 +1362,7 @@ SECStatus nsConvertCANamesToStrings(PLArenaPool* arena, char** caNameStrings, char* namestring; for (n = 0; n < caNames->nnames; n++) { - newitem.data = nullptr; + newitem.data = NULL; dername = &caNames->names[n]; rv = DER_Lengths(dername, &headerlen, &contentlen); @@ -1370,7 +1379,7 @@ SECStatus nsConvertCANamesToStrings(PLArenaPool* arena, char** caNameStrings, */ if (dername->len <= 127) { newitem.data = (unsigned char *) PR_Malloc(dername->len + 2); - if (!newitem.data) { + if (newitem.data == NULL) { goto loser; } newitem.data[0] = (unsigned char)0x30; @@ -1379,7 +1388,7 @@ SECStatus nsConvertCANamesToStrings(PLArenaPool* arena, char** caNameStrings, } else if (dername->len <= 255) { newitem.data = (unsigned char *) PR_Malloc(dername->len + 3); - if (!newitem.data) { + if (newitem.data == NULL) { goto loser; } newitem.data[0] = (unsigned char)0x30; @@ -1390,7 +1399,7 @@ SECStatus nsConvertCANamesToStrings(PLArenaPool* arena, char** caNameStrings, else { /* greater than 256, better be less than 64k */ newitem.data = (unsigned char *) PR_Malloc(dername->len + 4); - if (!newitem.data) { + if (newitem.data == NULL) { goto loser; } newitem.data[0] = (unsigned char)0x30; @@ -1403,26 +1412,26 @@ SECStatus nsConvertCANamesToStrings(PLArenaPool* arena, char** caNameStrings, } namestring = CERT_DerNameToAscii(dername); - if (!namestring) { + if (namestring == NULL) { /* XXX - keep going until we fail to convert the name */ caNameStrings[n] = const_cast(""); } else { caNameStrings[n] = PORT_ArenaStrdup(arena, namestring); PR_Free(namestring); - if (!caNameStrings[n]) { + if (caNameStrings[n] == NULL) { goto loser; } } - if (newitem.data) { + if (newitem.data != NULL) { PR_Free(newitem.data); } } return SECSuccess; loser: - if (newitem.data) { + if (newitem.data != NULL) { PR_Free(newitem.data); } return SECFailure; @@ -1456,7 +1465,7 @@ typedef struct { /* corresponding ASN1 templates */ static const SEC_ASN1Template cert_CertificateScopeEntryTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, nullptr, sizeof(CERTCertificateScopeEntry) }, + 0, NULL, sizeof(CERTCertificateScopeEntry) }, { SEC_ASN1_ANY, offsetof(CERTCertificateScopeEntry, derConstraint) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_INTEGER, @@ -1478,16 +1487,16 @@ SECStatus cert_DecodeScopeOfUseEntries(PRArenaPool* arena, SECItem* extData, CERTCertificateScopeEntry*** entries, int* numEntries) { - certCertificateScopeOfUse* scope = nullptr; + certCertificateScopeOfUse* scope = NULL; SECStatus rv = SECSuccess; int i; - *entries = nullptr; /* in case of failure */ + *entries = NULL; /* in case of failure */ *numEntries = 0; /* ditto */ scope = (certCertificateScopeOfUse*) PORT_ArenaZAlloc(arena, sizeof(certCertificateScopeOfUse)); - if (!scope) { + if (scope == NULL) { goto loser; } @@ -1498,10 +1507,10 @@ SECStatus cert_DecodeScopeOfUseEntries(PRArenaPool* arena, SECItem* extData, } *entries = scope->entries; - PR_ASSERT(*entries); + PR_ASSERT(*entries != NULL); /* first, let's count 'em. */ - for (i = 0; (*entries)[i]; i++) ; + for (i = 0; (*entries)[i] != NULL; i++) ; *numEntries = i; /* convert certCertificateScopeEntry sequence into what we can readily @@ -1510,8 +1519,8 @@ SECStatus cert_DecodeScopeOfUseEntries(PRArenaPool* arena, SECItem* extData, for (i = 0; i < *numEntries; i++) { (*entries)[i]->constraint = CERT_DecodeGeneralName(arena, &((*entries)[i]->derConstraint), - nullptr); - if ((*entries)[i]->derPort.data) { + NULL); + if ((*entries)[i]->derPort.data != NULL) { (*entries)[i]->port = (int)DER_GetInteger(&((*entries)[i]->derPort)); } @@ -1536,8 +1545,8 @@ static SECStatus cert_DecodeCertIPAddress(SECItem* genname, *constraint = 0; *mask = 0; - PR_ASSERT(genname->data); - if (!genname->data) { + PR_ASSERT(genname->data != NULL); + if (genname->data == NULL) { return SECFailure; } if (genname->len != 8) { @@ -1577,15 +1586,15 @@ static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname, bool rv = true; /* whether the cert can be presented */ SECStatus srv; SECItem extData; - PLArenaPool* arena = nullptr; - CERTCertificateScopeEntry** entries = nullptr; + PLArenaPool* arena = NULL; + CERTCertificateScopeEntry** entries = NULL; /* arrays of decoded scope entries */ int numEntries = 0; int i; - char* hostLower = nullptr; + char* hostLower = NULL; uint32_t hostIPAddr = 0; - PR_ASSERT(cert && hostname && hostIP); + PR_ASSERT((cert != NULL) && (hostname != NULL) && (hostIP != NULL)); /* find cert extension */ srv = CERT_FindCertExtension(cert, SEC_OID_NS_CERT_EXT_SCOPE_OF_USE, @@ -1599,7 +1608,7 @@ static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname, } arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) { + if (arena == NULL) { goto done; } @@ -1624,8 +1633,8 @@ static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname, */ CERTGeneralName* genname = entries[i]->constraint; - /* if constraint is nullptr, don't bother looking */ - if (!genname) { + /* if constraint is NULL, don't bother looking */ + if (genname == NULL) { /* this is not a failure: just continue */ continue; } @@ -1635,20 +1644,20 @@ static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname, /* we have a DNS name constraint; we should use only the host name * information */ - char* pattern = nullptr; - char* substring = nullptr; + char* pattern = NULL; + char* substring = NULL; /* null-terminate the string */ genname->name.other.data[genname->name.other.len] = '\0'; pattern = _str_to_lower((char*)genname->name.other.data); - if (!hostLower) { + if (hostLower == NULL) { /* so that it's done only if necessary and only once */ hostLower = _str_to_lower(PL_strdup(hostname)); } /* the hostname satisfies the constraint */ - if (((substring = strstr(hostLower, pattern)) != nullptr) && + if (((substring = strstr(hostLower, pattern)) != NULL) && /* the hostname contains the pattern */ (strlen(substring) == strlen(pattern)) && /* the hostname ends with the pattern */ @@ -1710,10 +1719,10 @@ static bool CERT_MatchesScopeOfUse(CERTCertificate* cert, char* hostname, } done: /* clean up entries */ - if (arena) { + if (arena != NULL) { PORT_FreeArena(arena, false); } - if (hostLower) { + if (hostLower != NULL) { PR_Free(hostLower); } return rv; @@ -1738,7 +1747,7 @@ done: */ nsresult nsGetUserCertChoice(SSM_UserCertChoice* certChoice) { - char *mode = nullptr; + char *mode=NULL; nsresult ret; NS_ENSURE_ARG_POINTER(certChoice); @@ -1777,7 +1786,7 @@ static bool hasExplicitKeyUsageNonRepudiation(CERTCertificate *cert) SECStatus srv; SECItem keyUsageItem; - keyUsageItem.data = nullptr; + keyUsageItem.data = NULL; srv = CERT_FindKeyUsageExtension(cert, &keyUsageItem); if (srv == SECFailure) @@ -1846,8 +1855,8 @@ SECStatus nsNSS_SSLGetClientAuthData(void* arg, PRFileDesc* socket, return SECFailure; } - RefPtr info( - reinterpret_cast(socket->higher->secret)); + nsRefPtr info + = reinterpret_cast(socket->higher->secret); CERTCertificate* serverCert = SSL_PeerCertificate(socket); if (!serverCert) { @@ -1870,8 +1879,8 @@ SECStatus nsNSS_SSLGetClientAuthData(void* arg, PRFileDesc* socket, } // XXX: This should be done asynchronously; see bug 696976 - RefPtr runnable( - new ClientAuthDataRunnable(caNames, pRetCert, pRetKey, info, serverCert)); + nsRefPtr runnable = + new ClientAuthDataRunnable(caNames, pRetCert, pRetKey, info, serverCert); nsresult rv = runnable->DispatchToMainThreadAndWait(); if (NS_FAILED(rv)) { PR_SetError(SEC_ERROR_NO_MEMORY, 0); @@ -1890,14 +1899,14 @@ SECStatus nsNSS_SSLGetClientAuthData(void* arg, PRFileDesc* socket, void ClientAuthDataRunnable::RunOnTargetThread() { - PLArenaPool* arena = nullptr; + PLArenaPool* arena = NULL; char** caNameStrings; - CERTCertificate* cert = nullptr; - SECKEYPrivateKey* privKey = nullptr; - CERTCertList* certList = nullptr; + CERTCertificate* cert = NULL; + SECKEYPrivateKey* privKey = NULL; + CERTCertList* certList = NULL; CERTCertListNode* node; - CERTCertNicknames* nicknames = nullptr; - char* extracted = nullptr; + CERTCertNicknames* nicknames = NULL; + char* extracted = NULL; int keyError = 0; /* used for private key retrieval error */ SSM_UserCertChoice certChoice; int32_t NumberOfCerts = 0; @@ -1905,13 +1914,13 @@ void ClientAuthDataRunnable::RunOnTargetThread() /* create caNameStrings */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) { + if (arena == NULL) { goto loser; } caNameStrings = (char**)PORT_ArenaAlloc(arena, sizeof(char*)*(mCANames->nnames)); - if (!caNameStrings) { + if (caNameStrings == NULL) { goto loser; } @@ -1933,7 +1942,7 @@ void ClientAuthDataRunnable::RunOnTargetThread() certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), certUsageSSLClient, false, true, wincx); - if (!certList) { + if (certList == NULL) { goto noCert; } @@ -1950,7 +1959,7 @@ void ClientAuthDataRunnable::RunOnTargetThread() goto noCert; } - CERTCertificate* low_prio_nonrep_cert = nullptr; + CERTCertificate* low_prio_nonrep_cert = NULL; CERTCertificateCleaner low_prio_cleaner(low_prio_nonrep_cert); /* loop through the list until we find a cert with a key */ @@ -1967,10 +1976,10 @@ void ClientAuthDataRunnable::RunOnTargetThread() #endif privKey = PK11_FindKeyByAnyCert(node->cert, wincx); - if (privKey) { + if (privKey != NULL) { if (hasExplicitKeyUsageNonRepudiation(node->cert)) { SECKEY_DestroyPrivateKey(privKey); - privKey = nullptr; + privKey = NULL; // Not a prefered cert if (!low_prio_nonrep_cert) // did not yet find a low prio cert low_prio_nonrep_cert = CERT_DupCertificate(node->cert); @@ -1992,11 +2001,11 @@ void ClientAuthDataRunnable::RunOnTargetThread() if (!cert && low_prio_nonrep_cert) { cert = low_prio_nonrep_cert; - low_prio_nonrep_cert = nullptr; // take it away from the cleaner + low_prio_nonrep_cert = NULL; // take it away from the cleaner privKey = PK11_FindKeyByAnyCert(cert, wincx); } - if (!cert) { + if (cert == NULL) { goto noCert; } } @@ -2009,9 +2018,9 @@ void ClientAuthDataRunnable::RunOnTargetThread() nsresult rv; NS_DEFINE_CID(nssComponentCID, NS_NSSCOMPONENT_CID); nsCOMPtr nssComponent(do_GetService(nssComponentCID, &rv)); - RefPtr cars; + nsRefPtr cars; if (nssComponent) { - nssComponent->GetClientAuthRememberService(byRef(cars)); + nssComponent->GetClientAuthRememberService(getter_AddRefs(cars)); } bool hasRemembered = false; @@ -2071,17 +2080,17 @@ if (hasRemembered) if (!hasRemembered) { /* user selects a cert to present */ - nsIClientAuthDialogs *dialogs = nullptr; + nsIClientAuthDialogs *dialogs = NULL; int32_t selectedIndex = -1; - PRUnichar **certNicknameList = nullptr; - PRUnichar **certDetailsList = nullptr; + PRUnichar **certNicknameList = NULL; + PRUnichar **certDetailsList = NULL; /* find all user certs that are for SSL */ /* note that we are allowing expired certs in this list */ certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), certUsageSSLClient, false, false, wincx); - if (!certList) { + if (certList == NULL) { goto noCert; } @@ -2125,7 +2134,7 @@ if (!hasRemembered) nicknames = getNSSCertNicknamesFromCertList(certList); - if (!nicknames) { + if (nicknames == NULL) { goto loser; } @@ -2177,7 +2186,7 @@ if (!hasRemembered) node = CERT_LIST_NEXT(node) ) { - RefPtr tempCert(nsNSSCertificate::Create(node->cert)); + nsRefPtr tempCert = nsNSSCertificate::Create(node->cert); if (!tempCert) continue; @@ -2254,13 +2263,13 @@ if (!hasRemembered) if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; } - if (!cert) { + if (cert == NULL) { goto loser; } /* go get the private key */ privKey = PK11_FindKeyByAnyCert(cert, wincx); - if (!privKey) { + if (privKey == NULL) { keyError = PR_GetError(); if (keyError == SEC_ERROR_BAD_PASSWORD) { /* problem with password: bail */ @@ -2278,23 +2287,23 @@ loser: if (mRV == SECSuccess) { mRV = SECFailure; } - if (cert) { + if (cert != NULL) { CERT_DestroyCertificate(cert); - cert = nullptr; + cert = NULL; } done: int error = PR_GetError(); - if (extracted) { + if (extracted != NULL) { PR_Free(extracted); } - if (nicknames) { + if (nicknames != NULL) { CERT_FreeNicknames(nicknames); } - if (certList) { + if (certList != NULL) { CERT_DestroyCertList(certList); } - if (arena) { + if (arena != NULL) { PORT_FreeArena(arena, false); } @@ -2323,7 +2332,7 @@ nsSSLIOLayerImportFD(PRFileDesc *fd, // Disable this hook if we connect anonymously. See bug 466080. if (anonymousLoad) { - SSL_GetClientAuthDataHook(sslSock, nullptr, infoObject); + SSL_GetClientAuthDataHook(sslSock, NULL, infoObject); } else { SSL_GetClientAuthDataHook(sslSock, (SSLGetClientAuthData)nsNSS_SSLGetClientAuthData, diff --git a/security/manager/ssl/src/nsNSSIOLayer.h b/security/manager/ssl/src/nsNSSIOLayer.h index 4467c375bce..44e65357736 100644 --- a/security/manager/ssl/src/nsNSSIOLayer.h +++ b/security/manager/ssl/src/nsNSSIOLayer.h @@ -10,6 +10,7 @@ #include "TransportSecurityInfo.h" #include "nsISSLSocketControl.h" #include "nsIClientAuthDialogs.h" +#include "nsAutoPtr.h" #include "nsNSSCertificate.h" #include "nsDataHashtable.h" #include "nsTHashtable.h" diff --git a/security/manager/ssl/src/nsNSSModule.cpp b/security/manager/ssl/src/nsNSSModule.cpp index 90debb59281..ea122d8bc64 100644 --- a/security/manager/ssl/src/nsNSSModule.cpp +++ b/security/manager/ssl/src/nsNSSModule.cpp @@ -52,6 +52,12 @@ PR_BEGIN_MACRO \ _InstanceClass * inst; \ inst = new _InstanceClass(); \ + if (NULL == inst) { \ + if (ensureOperator == nssLoadingComponent) \ + EnsureNSSInitialized(nssInitFailed); \ + rv = NS_ERROR_OUT_OF_MEMORY; \ + return rv; \ + } \ NS_ADDREF(inst); \ rv = inst->QueryInterface(aIID, aResult); \ NS_RELEASE(inst); \ @@ -61,6 +67,12 @@ PR_BEGIN_MACRO \ _InstanceClass * inst; \ inst = new _InstanceClass(); \ + if (NULL == inst) { \ + if (ensureOperator == nssLoadingComponent) \ + EnsureNSSInitialized(nssInitFailed); \ + rv = NS_ERROR_OUT_OF_MEMORY; \ + return rv; \ + } \ NS_ADDREF(inst); \ rv = inst->_InitMethod(); \ if(NS_SUCCEEDED(rv)) { \ @@ -87,8 +99,8 @@ _InstanceClassChrome##Constructor(nsISupports *aOuter, REFNSIID aIID, \ { \ nsresult rv; \ \ - *aResult = nullptr; \ - if (nullptr != aOuter) { \ + *aResult = NULL; \ + if (NULL != aOuter) { \ rv = NS_ERROR_NO_AGGREGATION; \ return rv; \ } \ @@ -131,8 +143,8 @@ _InstanceClassChrome##Constructor(nsISupports *aOuter, REFNSIID aIID, \ { \ nsresult rv; \ \ - *aResult = nullptr; \ - if (nullptr != aOuter) { \ + *aResult = NULL; \ + if (NULL != aOuter) { \ rv = NS_ERROR_NO_AGGREGATION; \ return rv; \ } \ @@ -250,43 +262,43 @@ NS_DEFINE_NAMED_CID(NS_NSSERRORSSERVICE_CID); NS_DEFINE_NAMED_CID(NS_NSSVERSION_CID); static const mozilla::Module::CIDEntry kNSSCIDs[] = { - { &kNS_NSSCOMPONENT_CID, false, nullptr, nsNSSComponentConstructor }, - { &kNS_SSLSOCKETPROVIDER_CID, false, nullptr, nsSSLSocketProviderConstructor }, - { &kNS_STARTTLSSOCKETPROVIDER_CID, false, nullptr, nsTLSSocketProviderConstructor }, - { &kNS_SDR_CID, false, nullptr, nsSecretDecoderRingConstructor }, - { &kNS_PK11TOKENDB_CID, false, nullptr, nsPK11TokenDBConstructor }, - { &kNS_PKCS11MODULEDB_CID, false, nullptr, nsPKCS11ModuleDBConstructor }, - { &kNS_PSMCONTENTLISTEN_CID, false, nullptr, PSMContentListenerConstructor }, - { &kNS_X509CERT_CID, false, nullptr, nsNSSCertificateConstructor }, - { &kNS_X509CERTDB_CID, false, nullptr, nsNSSCertificateDBConstructor }, - { &kNS_NSSCERTCACHE_CID, false, nullptr, nsNSSCertCacheConstructor }, - { &kNS_FORMPROCESSOR_CID, false, nullptr, nsKeygenFormProcessor::Create }, + { &kNS_NSSCOMPONENT_CID, false, NULL, nsNSSComponentConstructor }, + { &kNS_SSLSOCKETPROVIDER_CID, false, NULL, nsSSLSocketProviderConstructor }, + { &kNS_STARTTLSSOCKETPROVIDER_CID, false, NULL, nsTLSSocketProviderConstructor }, + { &kNS_SDR_CID, false, NULL, nsSecretDecoderRingConstructor }, + { &kNS_PK11TOKENDB_CID, false, NULL, nsPK11TokenDBConstructor }, + { &kNS_PKCS11MODULEDB_CID, false, NULL, nsPKCS11ModuleDBConstructor }, + { &kNS_PSMCONTENTLISTEN_CID, false, NULL, PSMContentListenerConstructor }, + { &kNS_X509CERT_CID, false, NULL, nsNSSCertificateConstructor }, + { &kNS_X509CERTDB_CID, false, NULL, nsNSSCertificateDBConstructor }, + { &kNS_NSSCERTCACHE_CID, false, NULL, nsNSSCertCacheConstructor }, + { &kNS_FORMPROCESSOR_CID, false, NULL, nsKeygenFormProcessor::Create }, #ifdef MOZ_XUL - { &kNS_CERTTREE_CID, false, nullptr, nsCertTreeConstructor }, + { &kNS_CERTTREE_CID, false, NULL, nsCertTreeConstructor }, #endif - { &kNS_PKCS11_CID, false, nullptr, nsPkcs11Constructor }, - { &kNS_CRYPTO_CID, false, nullptr, nsCryptoConstructor }, - { &kNS_CMSSECUREMESSAGE_CID, false, nullptr, nsCMSSecureMessageConstructor }, - { &kNS_CMSDECODER_CID, false, nullptr, nsCMSDecoderConstructor }, - { &kNS_CMSENCODER_CID, false, nullptr, nsCMSEncoderConstructor }, - { &kNS_CMSMESSAGE_CID, false, nullptr, nsCMSMessageConstructor }, - { &kNS_CRYPTO_HASH_CID, false, nullptr, nsCryptoHashConstructor }, - { &kNS_CRYPTO_HMAC_CID, false, nullptr, nsCryptoHMACConstructor }, - { &kNS_CERT_PICKER_CID, false, nullptr, nsCertPickerConstructor }, - { &kNS_CRLMANAGER_CID, false, nullptr, nsCRLManagerConstructor }, - { &kNS_NTLMAUTHMODULE_CID, false, nullptr, nsNTLMAuthModuleConstructor }, - { &kNS_STREAMCIPHER_CID, false, nullptr, nsStreamCipherConstructor }, - { &kNS_KEYMODULEOBJECT_CID, false, nullptr, nsKeyObjectConstructor }, - { &kNS_KEYMODULEOBJECTFACTORY_CID, false, nullptr, nsKeyObjectFactoryConstructor }, - { &kNS_DATASIGNATUREVERIFIER_CID, false, nullptr, nsDataSignatureVerifierConstructor }, - { &kNS_CERTOVERRIDE_CID, false, nullptr, nsCertOverrideServiceConstructor }, - { &kNS_RANDOMGENERATOR_CID, false, nullptr, nsRandomGeneratorConstructor }, - { &kNS_RECENTBADCERTS_CID, false, nullptr, nsRecentBadCertsServiceConstructor }, - { &kNS_SSLSTATUS_CID, false, nullptr, nsSSLStatusConstructor }, - { &kTRANSPORTSECURITYINFO_CID, false, nullptr, TransportSecurityInfoConstructor }, - { &kNS_NSSERRORSSERVICE_CID, false, nullptr, NSSErrorsServiceConstructor }, - { &kNS_NSSVERSION_CID, false, nullptr, nsNSSVersionConstructor }, - { nullptr } + { &kNS_PKCS11_CID, false, NULL, nsPkcs11Constructor }, + { &kNS_CRYPTO_CID, false, NULL, nsCryptoConstructor }, + { &kNS_CMSSECUREMESSAGE_CID, false, NULL, nsCMSSecureMessageConstructor }, + { &kNS_CMSDECODER_CID, false, NULL, nsCMSDecoderConstructor }, + { &kNS_CMSENCODER_CID, false, NULL, nsCMSEncoderConstructor }, + { &kNS_CMSMESSAGE_CID, false, NULL, nsCMSMessageConstructor }, + { &kNS_CRYPTO_HASH_CID, false, NULL, nsCryptoHashConstructor }, + { &kNS_CRYPTO_HMAC_CID, false, NULL, nsCryptoHMACConstructor }, + { &kNS_CERT_PICKER_CID, false, NULL, nsCertPickerConstructor }, + { &kNS_CRLMANAGER_CID, false, NULL, nsCRLManagerConstructor }, + { &kNS_NTLMAUTHMODULE_CID, false, NULL, nsNTLMAuthModuleConstructor }, + { &kNS_STREAMCIPHER_CID, false, NULL, nsStreamCipherConstructor }, + { &kNS_KEYMODULEOBJECT_CID, false, NULL, nsKeyObjectConstructor }, + { &kNS_KEYMODULEOBJECTFACTORY_CID, false, NULL, nsKeyObjectFactoryConstructor }, + { &kNS_DATASIGNATUREVERIFIER_CID, false, NULL, nsDataSignatureVerifierConstructor }, + { &kNS_CERTOVERRIDE_CID, false, NULL, nsCertOverrideServiceConstructor }, + { &kNS_RANDOMGENERATOR_CID, false, NULL, nsRandomGeneratorConstructor }, + { &kNS_RECENTBADCERTS_CID, false, NULL, nsRecentBadCertsServiceConstructor }, + { &kNS_SSLSTATUS_CID, false, NULL, nsSSLStatusConstructor }, + { &kTRANSPORTSECURITYINFO_CID, false, NULL, TransportSecurityInfoConstructor }, + { &kNS_NSSERRORSSERVICE_CID, false, NULL, NSSErrorsServiceConstructor }, + { &kNS_NSSVERSION_CID, false, NULL, nsNSSVersionConstructor }, + { NULL } }; static const mozilla::Module::ContractIDEntry kNSSContracts[] = { @@ -325,7 +337,7 @@ static const mozilla::Module::ContractIDEntry kNSSContracts[] = { { NS_CERTOVERRIDE_CONTRACTID, &kNS_CERTOVERRIDE_CID }, { NS_RANDOMGENERATOR_CONTRACTID, &kNS_RANDOMGENERATOR_CID }, { NS_RECENTBADCERTS_CONTRACTID, &kNS_RECENTBADCERTS_CID }, - { nullptr } + { NULL } }; static const mozilla::Module::CategoryEntry kNSSCategories[] = { @@ -336,7 +348,7 @@ static const mozilla::Module::CategoryEntry kNSSCategories[] = { { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-pkcs7-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" }, { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" }, { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/pkix-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" }, - { nullptr } + { NULL } }; static const mozilla::Module kNSSModule = { diff --git a/security/manager/ssl/src/nsNSSShutDown.h b/security/manager/ssl/src/nsNSSShutDown.h index 100ede478c5..91829d130e4 100644 --- a/security/manager/ssl/src/nsNSSShutDown.h +++ b/security/manager/ssl/src/nsNSSShutDown.h @@ -76,7 +76,7 @@ private: bool mIsUIForbidden; // nullptr means "no restriction" - // if not null, activity is only allowed on that thread + // if != nullptr, activity is only allowed on that thread PRThread* mNSSRestrictedThread; }; diff --git a/security/manager/ssl/src/nsNTLMAuthModule.cpp b/security/manager/ssl/src/nsNTLMAuthModule.cpp index a6938441a38..69f3b4bceb1 100644 --- a/security/manager/ssl/src/nsNTLMAuthModule.cpp +++ b/security/manager/ssl/src/nsNTLMAuthModule.cpp @@ -223,7 +223,7 @@ static void LogToken(const char *name, const void *token, uint32_t tokenLen) if (!LOG_ENABLED()) return; - char *b64data = PL_Base64Encode((const char *) token, tokenLen, nullptr); + char *b64data = PL_Base64Encode((const char *) token, tokenLen, NULL); if (b64data) { PR_LogPrint("%s: %s\n", name, b64data); @@ -528,7 +528,7 @@ ParseType2Msg(const void *inBuf, uint32_t inLen, Type2Msg *msg) { // Do not error out, for (conservative) backward compatibility. msg->targetLen = 0; - msg->target = nullptr; + msg->target = NULL; } // read flags diff --git a/security/manager/ssl/src/nsPK11TokenDB.cpp b/security/manager/ssl/src/nsPK11TokenDB.cpp index 4dde84141d1..67223c106bd 100644 --- a/security/manager/ssl/src/nsPK11TokenDB.cpp +++ b/security/manager/ssl/src/nsPK11TokenDB.cpp @@ -374,8 +374,8 @@ NS_IMETHODIMP nsPK11Token::ChangePassword(const PRUnichar *oldPassword, const PR NS_ConvertUTF16toUTF8 aUtf8NewPassword(newPassword); rv = PK11_ChangePW(mSlot, - (oldPassword ? const_cast(aUtf8OldPassword.get()) : nullptr), - (newPassword ? const_cast(aUtf8NewPassword.get()) : nullptr)); + (oldPassword != NULL ? const_cast(aUtf8OldPassword.get()) : NULL), + (newPassword != NULL ? const_cast(aUtf8NewPassword.get()) : NULL)); return (rv == SECSuccess) ? NS_OK : NS_ERROR_FAILURE; } @@ -447,6 +447,8 @@ NS_IMETHODIMP nsPK11TokenDB::GetInternalKeyToken(nsIPK11Token **_retval) if (!slot) { rv = NS_ERROR_FAILURE; goto done; } token = new nsPK11Token(slot); + if (!token) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; } + *_retval = token; NS_ADDREF(*_retval); @@ -467,6 +469,8 @@ FindTokenByName(const PRUnichar* tokenName, nsIPK11Token **_retval) if (!slot) { rv = NS_ERROR_FAILURE; goto done; } *_retval = new nsPK11Token(slot); + if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; } + NS_ADDREF(*_retval); done: @@ -494,7 +498,10 @@ NS_IMETHODIMP nsPK11TokenDB::ListTokens(nsIEnumerator* *_retval) for (le = PK11_GetFirstSafe(list); le; le = PK11_GetNextSafe(list, le, false)) { nsCOMPtr token = new nsPK11Token(le->slot); - rv = array->AppendElement(token); + rv = token + ? array->AppendElement(token) + : NS_ERROR_OUT_OF_MEMORY; + if (NS_FAILED(rv)) { PK11_FreeSlotListElement(list, le); rv = NS_ERROR_OUT_OF_MEMORY; diff --git a/security/manager/ssl/src/nsPKCS11Slot.cpp b/security/manager/ssl/src/nsPKCS11Slot.cpp index ef99de44cf7..7e1e05545df 100644 --- a/security/manager/ssl/src/nsPKCS11Slot.cpp +++ b/security/manager/ssl/src/nsPKCS11Slot.cpp @@ -176,6 +176,8 @@ nsPKCS11Slot::GetToken(nsIPK11Token **_retval) return NS_ERROR_NOT_AVAILABLE; nsCOMPtr token = new nsPK11Token(mSlot); + if (!token) + return NS_ERROR_OUT_OF_MEMORY; *_retval = token; NS_ADDREF(*_retval); return NS_OK; @@ -217,7 +219,7 @@ nsPKCS11Slot::GetStatus(uint32_t *_retval) *_retval = SLOT_NOT_PRESENT; else if (PK11_NeedLogin(mSlot) && PK11_NeedUserInit(mSlot)) *_retval = SLOT_UNINITIALIZED; - else if (PK11_NeedLogin(mSlot) && !PK11_IsLoggedIn(mSlot, nullptr)) + else if (PK11_NeedLogin(mSlot) && !PK11_IsLoggedIn(mSlot, NULL)) *_retval = SLOT_NOT_LOGGED_IN; else if (PK11_NeedLogin(mSlot)) *_retval = SLOT_LOGGED_IN; @@ -287,7 +289,7 @@ nsPKCS11Module::GetLibName(PRUnichar **aName) if ( mModule->dllName ) { *aName = ToNewUnicode(NS_ConvertUTF8toUTF16(mModule->dllName)); } else { - *aName = nullptr; + *aName = NULL; } return NS_OK; } @@ -303,13 +305,13 @@ nsPKCS11Module::FindSlotByName(const PRUnichar *aName, char *asciiname = ToNewUTF8String(nsDependentString(aName)); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname)); - PK11SlotInfo *slotinfo = nullptr; + PK11SlotInfo *slotinfo = NULL; PK11SlotList *slotList = PK11_FindSlotsByNames(mModule->dllName, - asciiname /* slotName */, nullptr /* token Name */, false); + asciiname /* slotName */, NULL /* token Name */, false); if (!slotList) { /* name must be the token name */ slotList = PK11_FindSlotsByNames(mModule->dllName, - nullptr /*slot Name */, asciiname /* token Name */, false); + NULL /*slot Name */, asciiname /* token Name */, false); } if (slotList) { /* should only be one */ @@ -320,7 +322,7 @@ nsPKCS11Module::FindSlotByName(const PRUnichar *aName, } if (!slotinfo) { // workaround - the builtin module has no name - if (!asciiname) { + if (asciiname == nullptr) { return NS_ERROR_FAILURE; } else if (nsCRT::strcmp(asciiname, "Root Certificates") == 0) { slotinfo = PK11_ReferenceSlot(mModule->slots[0]); @@ -333,6 +335,8 @@ nsPKCS11Module::FindSlotByName(const PRUnichar *aName, nsMemory::Free(asciiname); nsCOMPtr slot = new nsPKCS11Slot(slotinfo); PK11_FreeSlot(slotinfo); + if (!slot) + return NS_ERROR_OUT_OF_MEMORY; *_retval = slot; NS_ADDREF(*_retval); return NS_OK; @@ -385,9 +389,11 @@ nsPKCS11ModuleDB::GetInternal(nsIPKCS11Module **_retval) { nsNSSShutDownPreventionLock locker; SECMODModule *nssMod = - SECMOD_CreateModule(nullptr, SECMOD_INT_NAME, nullptr, SECMOD_INT_FLAGS); + SECMOD_CreateModule(NULL,SECMOD_INT_NAME, NULL,SECMOD_INT_FLAGS); nsCOMPtr module = new nsPKCS11Module(nssMod); SECMOD_DestroyModule(nssMod); + if (!module) + return NS_ERROR_OUT_OF_MEMORY; *_retval = module; NS_ADDREF(*_retval); return NS_OK; @@ -399,9 +405,11 @@ nsPKCS11ModuleDB::GetInternalFIPS(nsIPKCS11Module **_retval) { nsNSSShutDownPreventionLock locker; SECMODModule *nssMod = - SECMOD_CreateModule(nullptr, SECMOD_FIPS_NAME, nullptr, SECMOD_FIPS_FLAGS); + SECMOD_CreateModule(NULL, SECMOD_FIPS_NAME, NULL, SECMOD_FIPS_FLAGS); nsCOMPtr module = new nsPKCS11Module(nssMod); SECMOD_DestroyModule(nssMod); + if (!module) + return NS_ERROR_OUT_OF_MEMORY; *_retval = module; NS_ADDREF(*_retval); return NS_OK; @@ -420,6 +428,8 @@ nsPKCS11ModuleDB::FindModuleByName(const PRUnichar *aName, return NS_ERROR_FAILURE; nsCOMPtr module = new nsPKCS11Module(mod); SECMOD_DestroyModule(mod); + if (!module) + return NS_ERROR_OUT_OF_MEMORY; *_retval = module; NS_ADDREF(*_retval); return NS_OK; @@ -441,6 +451,8 @@ nsPKCS11ModuleDB::FindSlotByName(const PRUnichar *aName, return NS_ERROR_FAILURE; nsCOMPtr slot = new nsPKCS11Slot(slotinfo); PK11_FreeSlot(slotinfo); + if (!slot) + return NS_ERROR_OUT_OF_MEMORY; *_retval = slot; NS_ADDREF(*_retval); return NS_OK; diff --git a/security/manager/ssl/src/nsPKCS12Blob.cpp b/security/manager/ssl/src/nsPKCS12Blob.cpp index 2e5dcc269f0..9b853b4ebc5 100644 --- a/security/manager/ssl/src/nsPKCS12Blob.cpp +++ b/security/manager/ssl/src/nsPKCS12Blob.cpp @@ -102,7 +102,7 @@ nsPKCS12Blob::ImportFromFile(nsIFile *file) if (!mToken) { if (!mTokenSet) { - rv = SetToken(nullptr); // Ask the user to pick a slot + rv = SetToken(NULL); // Ask the user to pick a slot if (NS_FAILED(rv)) { handleError(PIP_PKCS12_USER_CANCELED); return rv; @@ -142,12 +142,12 @@ nsPKCS12Blob::ImportFromFileHelper(nsIFile *file, nsNSSShutDownPreventionLock locker; nsresult rv; SECStatus srv = SECSuccess; - SEC_PKCS12DecoderContext *dcx = nullptr; + SEC_PKCS12DecoderContext *dcx = NULL; SECItem unicodePw; PK11SlotInfo *slot=nullptr; nsXPIDLString tokenName; - unicodePw.data = nullptr; + unicodePw.data = NULL; aWantRetry = rr_do_not_retry; @@ -160,7 +160,7 @@ nsPKCS12Blob::ImportFromFileHelper(nsIFile *file, // get file password (unicode) rv = getPKCS12FilePassword(&unicodePw); if (NS_FAILED(rv)) goto finish; - if (!unicodePw.data) { + if (unicodePw.data == NULL) { handleError(PIP_PKCS12_USER_CANCELED); return NS_OK; } @@ -177,7 +177,7 @@ nsPKCS12Blob::ImportFromFileHelper(nsIFile *file, } // initialize the decoder - dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, nullptr, + dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, NULL, digest_open, digest_close, digest_read, digest_write, this); @@ -260,7 +260,7 @@ nsPKCS12Blob::LoadCerts(const PRUnichar **certNames, int numCerts) /* Add the certs */ for (int i=0; iLogin(true); if (NS_FAILED(rv)) goto finish; // get file password (unicode) - unicodePw.data = nullptr; + unicodePw.data = NULL; rv = newPKCS12FilePassword(&unicodePw); if (NS_FAILED(rv)) goto finish; - if (!unicodePw.data) { + if (unicodePw.data == NULL) { handleError(PIP_PKCS12_USER_CANCELED); return NS_OK; } // what about slotToUse in psm 1.x ??? // create export context - ecx = SEC_PKCS12CreateExportContext(nullptr, nullptr, nullptr /*slot*/, nullptr); + ecx = SEC_PKCS12CreateExportContext(NULL, NULL, NULL /*slot*/, NULL); if (!ecx) { srv = SECFailure; goto finish; @@ -393,7 +393,7 @@ nsPKCS12Blob::ExportToFile(nsIFile *file, } // XXX this is why, to verify the slot is the same - // PK11_FindObjectForCert(nssCert, nullptr, slot); + // PK11_FindObjectForCert(nssCert, NULL, slot); // create the cert and key safes keySafe = SEC_PKCS12CreateUnencryptedSafe(ecx); if (!SEC_PKCS12IsEncryptionAllowed() || PK11_IsFIPS()) { @@ -407,9 +407,9 @@ nsPKCS12Blob::ExportToFile(nsIFile *file, goto finish; } // add the cert and key to the blob - srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, nullptr, nssCert, + srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, NULL, nssCert, CERT_GetDefaultCertDB(), // XXX - keySafe, nullptr, true, &unicodePw, + keySafe, NULL, true, &unicodePw, SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC); if (srv) goto finish; // cert was dup'ed, so release it @@ -419,7 +419,7 @@ nsPKCS12Blob::ExportToFile(nsIFile *file, if (!numCertsExported) goto finish; // prepare the instance to write to an export file - this->mTmpFile = nullptr; + this->mTmpFile = NULL; file->GetPath(filePath); // Use the nsCOMPtr var localFileRef so that // the reference to the nsIFile we create gets released as soon as @@ -449,7 +449,7 @@ finish: SEC_PKCS12DestroyExportContext(ecx); if (this->mTmpFile) { PR_Close(this->mTmpFile); - this->mTmpFile = nullptr; + this->mTmpFile = NULL; } SECITEM_ZfreeItem(&unicodePw, false); return rv; @@ -471,7 +471,7 @@ nsPKCS12Blob::unicodeToItem(const PRUnichar *uni, SECItem *item) { int len = 0; while (uni[len++] != 0); - SECITEM_AllocItem(nullptr, item, sizeof(PRUnichar) * len); + SECITEM_AllocItem(NULL, item, sizeof(PRUnichar) * len); #ifdef IS_LITTLE_ENDIAN int i = 0; for (i=0; i slot; + nsRefPtr slot; { MutexAutoLock lock(mMutex); slot = new nsPKCS11Slot(mSlot); } + if (!slot) + return NS_ERROR_OUT_OF_MEMORY; return CallQueryInterface (slot.get(), _retval); } diff --git a/security/manager/ssl/src/nsRecentBadCerts.cpp b/security/manager/ssl/src/nsRecentBadCerts.cpp index eee2f509d75..cfedc1bebd8 100644 --- a/security/manager/ssl/src/nsRecentBadCerts.cpp +++ b/security/manager/ssl/src/nsRecentBadCerts.cpp @@ -6,13 +6,14 @@ #include "nsRecentBadCerts.h" #include "nsIX509Cert.h" -#include "mozilla/RefPtr.h" #include "nsSSLStatus.h" #include "nsCOMPtr.h" +#include "nsAutoPtr.h" #include "nsNSSCertificate.h" #include "nsCRT.h" #include "nsPromiseFlatString.h" #include "nsStringBuffer.h" +#include "nsAutoPtr.h" #include "nspr.h" #include "pk11pub.h" #include "certdb.h" @@ -52,7 +53,9 @@ nsRecentBadCertsService::GetRecentBadCert(const nsAString & aHostNameWithPort, return NS_ERROR_INVALID_ARG; *aStatus = nullptr; - RefPtr status(new nsSSLStatus()); + nsRefPtr status = new nsSSLStatus(); + if (!status) + return NS_ERROR_OUT_OF_MEMORY; SECItem foundDER; foundDER.len = 0; diff --git a/security/manager/ssl/src/nsSDR.cpp b/security/manager/ssl/src/nsSDR.cpp index 4ce8f6d1c0e..881a93d2c18 100644 --- a/security/manager/ssl/src/nsSDR.cpp +++ b/security/manager/ssl/src/nsSDR.cpp @@ -58,6 +58,7 @@ Encrypt(unsigned char * data, int32_t dataLen, unsigned char * *result, int32_t SECItem reply; SECStatus s; nsCOMPtr ctx = new PipUIContext(); + if (!ctx) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } slot = PK11_GetInternalKeySlot(); if (!slot) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; } @@ -100,6 +101,7 @@ Decrypt(unsigned char * data, int32_t dataLen, unsigned char * *result, int32_t SECItem request; SECItem reply; nsCOMPtr ctx = new PipUIContext(); + if (!ctx) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } *result = 0; *_retval = 0; @@ -138,7 +140,7 @@ EncryptString(const char *text, char **_retval) unsigned char *encrypted = 0; int32_t eLen; - if (!text || !_retval) { + if (text == nullptr || _retval == nullptr) { rv = NS_ERROR_INVALID_POINTER; goto loser; } @@ -166,7 +168,7 @@ DecryptString(const char *crypt, char **_retval) unsigned char *decrypted = 0; int32_t decryptedLen; - if (!crypt || !_retval) { + if (crypt == nullptr || _retval == nullptr) { rv = NS_ERROR_INVALID_POINTER; goto loser; } @@ -295,7 +297,7 @@ encode(const unsigned char *data, int32_t dataLen, char **_retval) { nsresult rv = NS_OK; - char *result = PL_Base64Encode((const char *)data, dataLen, nullptr); + char *result = PL_Base64Encode((const char *)data, dataLen, NULL); if (!result) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; } *_retval = NS_strdup(result); @@ -319,7 +321,7 @@ decode(const char *data, unsigned char **result, int32_t * _retval) if (data[len-2] == '=') adjust++; } - *result = (unsigned char *)PL_Base64Decode(data, len, nullptr); + *result = (unsigned char *)PL_Base64Decode(data, len, NULL); if (!*result) { rv = NS_ERROR_ILLEGAL_VALUE; goto loser; } *_retval = (len*3)/4 - adjust; diff --git a/security/manager/ssl/src/nsSSLStatus.h b/security/manager/ssl/src/nsSSLStatus.h index 61599779a7e..1eb4d13581d 100644 --- a/security/manager/ssl/src/nsSSLStatus.h +++ b/security/manager/ssl/src/nsSSLStatus.h @@ -8,7 +8,8 @@ #define _NSSSLSTATUS_H #include "nsISSLStatus.h" -#include "nsCOMPtr.h" + +#include "nsAutoPtr.h" #include "nsXPIDLString.h" #include "nsIX509Cert.h" #include "nsISerializable.h" diff --git a/security/manager/ssl/src/nsSmartCardMonitor.cpp b/security/manager/ssl/src/nsSmartCardMonitor.cpp index 72660dd764c..0284a4f9d6f 100644 --- a/security/manager/ssl/src/nsSmartCardMonitor.cpp +++ b/security/manager/ssl/src/nsSmartCardMonitor.cpp @@ -89,8 +89,11 @@ SmartCardThreadList::Add(SmartCardMonitoringThread *thread) { SmartCardThreadEntry *current = new SmartCardThreadEntry(thread, head, nullptr, &head); - // OK to forget current here, it's on the list - return thread->Start(); + if (current) { + // OK to forget current here, it's on the list + return thread->Start(); + } + return NS_ERROR_OUT_OF_MEMORY; } @@ -272,7 +275,7 @@ void SmartCardMonitoringThread::Execute() // loop starts.. do { slot = SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1) ); - if (!slot) { + if (slot == nullptr) { break; } diff --git a/security/manager/ssl/src/nsStreamCipher.cpp b/security/manager/ssl/src/nsStreamCipher.cpp index f8263c1fa0e..626eb8083bd 100644 --- a/security/manager/ssl/src/nsStreamCipher.cpp +++ b/security/manager/ssl/src/nsStreamCipher.cpp @@ -10,7 +10,7 @@ NS_IMPL_ISUPPORTS1(nsStreamCipher, nsIStreamCipher) nsStreamCipher::nsStreamCipher() - : mContext(nullptr) + : mContext(NULL) { } @@ -89,6 +89,8 @@ NS_IMETHODIMP nsStreamCipher::Update(const uint8_t *aData, uint32_t aLen) return NS_ERROR_NOT_INITIALIZED; unsigned char* output = new unsigned char[aLen]; + if (!output) + return NS_ERROR_OUT_OF_MEMORY; unsigned char* input = (unsigned char*)aData; int32_t setLen; @@ -130,6 +132,8 @@ NS_IMETHODIMP nsStreamCipher::UpdateFromString(const nsACString& aInput) uint32_t len = aInput.Length(); unsigned char* output = new unsigned char[len]; + if (!output) + return NS_ERROR_OUT_OF_MEMORY; int32_t setLen; @@ -169,7 +173,14 @@ NS_IMETHODIMP nsStreamCipher::Discard(int32_t aLen) return NS_ERROR_NOT_INITIALIZED; unsigned char* output = new unsigned char[aLen]; + if (!output) + return NS_ERROR_OUT_OF_MEMORY; + unsigned char* input = new unsigned char[aLen]; + if (!input) { + delete [] output; + return NS_ERROR_OUT_OF_MEMORY; + } int32_t setLen; diff --git a/security/manager/ssl/src/nsUsageArrayHelper.cpp b/security/manager/ssl/src/nsUsageArrayHelper.cpp index 6f8401b5b1c..2894a544f9e 100644 --- a/security/manager/ssl/src/nsUsageArrayHelper.cpp +++ b/security/manager/ssl/src/nsUsageArrayHelper.cpp @@ -14,9 +14,9 @@ #include "nspr.h" #include "nsNSSCertHeader.h" +extern "C" { #include "secerr.h" - -using namespace mozilla; +} static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); @@ -166,7 +166,7 @@ if (!nsNSSComponent::globalConstFlagUsePKIXVerification) { certificateUsageObjectSigner | certificateUsageSSLCA | certificateUsageStatusResponder, - nullptr, &usages); + NULL, &usages); err = PR_GetError(); } else { @@ -174,7 +174,7 @@ else { nsCOMPtr inss = do_GetService(kNSSComponentCID, &nsrv); if (!inss) return nsrv; - RefPtr survivingParams; + nsRefPtr survivingParams; if (localOnly) nsrv = inss->GetDefaultCERTValInParamLocalOnly(survivingParams); else @@ -190,7 +190,7 @@ else { CERT_PKIXVerifyCert(mCert, certificateUsageCheckAllUsages, survivingParams->GetRawPointerForNSS(), - cvout, nullptr); + cvout, NULL); err = PR_GetError(); usages = cvout[0].value.scalar.usages; } diff --git a/storage/public/StatementCache.h b/storage/public/StatementCache.h index e64d9ab3808..c8b5faf19a1 100644 --- a/storage/public/StatementCache.h +++ b/storage/public/StatementCache.h @@ -65,7 +65,7 @@ public: } template - NS_ALWAYS_INLINE already_AddRefed + MOZ_ALWAYS_INLINE already_AddRefed GetCachedStatement(const char (&aQuery)[N]) { nsDependentCString query(aQuery, N - 1); diff --git a/testing/mochitest/android.json b/testing/mochitest/android.json index 7108f3f31f5..dc477d2782d 100644 --- a/testing/mochitest/android.json +++ b/testing/mochitest/android.json @@ -152,6 +152,7 @@ "dom/indexedDB/test/test_event_propagation.html": "TIMED_OUT, bug 780855", "dom/indexedDB/test/test_app_isolation_inproc.html": "TIMED_OUT", "dom/indexedDB/test/test_app_isolation_oop.html": "TIMED_OUT", + "dom/indexedDB/test/test_webapp_clearBrowserData.html": "No test app installed", "dom/network/tests/test_network_basics.html": "", "dom/permission/tests/test_permission_basics.html": "", "dom/sms/tests/test_sms_basics.html": "", diff --git a/testing/specialpowers/content/specialpowersAPI.js b/testing/specialpowers/content/specialpowersAPI.js index aaa0c49494b..c39fb4d6d43 100644 --- a/testing/specialpowers/content/specialpowersAPI.js +++ b/testing/specialpowers/content/specialpowersAPI.js @@ -1194,6 +1194,19 @@ SpecialPowersAPI.prototype = { .getService(Ci.nsIIOService) .newURI(arg, null, null) .spec; + } else if (arg.manifestURL) { + // It's a thing representing an app. + let tmp = {}; + Components.utils.import("resource://gre/modules/Webapps.jsm", tmp); + + let app = tmp.DOMApplicationRegistry.getAppByManifestURL(arg.manifestURL); + if (!app) { + throw "No app for this manifest!"; + } + + appId = app.localId; + url = app.origin; + isInBrowserElement = arg.isInBrowserElement || false; } else if (arg.nodePrincipal) { // It's a document. url = arg.nodePrincipal.URI.spec; diff --git a/testing/talos/talos.json b/testing/talos/talos.json index 51f530a7a2f..82224074cc1 100644 --- a/testing/talos/talos.json +++ b/testing/talos/talos.json @@ -1,6 +1,6 @@ { "talos.zip": { - "url": "http://build.mozilla.org/talos/zips/talos.0e9224d7bc95.zip", + "url": "http://build.mozilla.org/talos/zips/talos.b1d61df65e8a.zip", "path": "" } } diff --git a/toolkit/components/places/SQLFunctions.cpp b/toolkit/components/places/SQLFunctions.cpp index af5f01f70c8..0b0bf92c2e2 100644 --- a/toolkit/components/places/SQLFunctions.cpp +++ b/toolkit/components/places/SQLFunctions.cpp @@ -44,7 +44,7 @@ namespace { * @return a pointer to the next word boundary after aStart */ static - NS_ALWAYS_INLINE const_char_iterator + MOZ_ALWAYS_INLINE const_char_iterator nextWordBoundary(const_char_iterator const aStart, const_char_iterator const aNext, const_char_iterator const aEnd) { @@ -76,7 +76,7 @@ namespace { * findAnywhere and findOnBoundary do almost the same thing, so it's natural * to implement them in terms of a single function. They're both * performance-critical functions, however, and checking aBehavior makes them - * a bit slower. Our solution is to define findInString as NS_ALWAYS_INLINE + * a bit slower. Our solution is to define findInString as MOZ_ALWAYS_INLINE * and rely on the compiler to optimize out the aBehavior check. * * @param aToken @@ -91,7 +91,7 @@ namespace { * @return true if aToken was found in aSourceString, false otherwise. */ static - NS_ALWAYS_INLINE bool + MOZ_ALWAYS_INLINE bool findInString(const nsDependentCSubstring &aToken, const nsACString &aSourceString, FindInStringBehavior aBehavior) diff --git a/toolkit/components/telemetry/Histograms.json b/toolkit/components/telemetry/Histograms.json index 9b4b40994e8..76094d4bd83 100644 --- a/toolkit/components/telemetry/Histograms.json +++ b/toolkit/components/telemetry/Histograms.json @@ -2101,19 +2101,53 @@ "kind": "boolean", "description": "DOM: Ranges that are detached on destruction (bug 702948)" }, - "GLOBALDOMSTORAGE_KEY_SIZE_BYTES": { + "LOCALDOMSTORAGE_GETALLKEYS_MS": { "kind": "exponential", - "low": 1024, - "high": "32768", + "high": "3000", "n_buckets": 10, - "description": "DOM storage: size of keys stored in globalStorage" + "description": "Time to return a list of all keys in domain's LocalStorage (ms)" }, - "GLOBALDOMSTORAGE_VALUE_SIZE_BYTES": { + "LOCALDOMSTORAGE_GETVALUE_MS": { "kind": "exponential", - "low": 1024, - "high": "32768", + "high": "3000", "n_buckets": 10, - "description": "DOM storage: size of values stored in globalStorage" + "description": "Time to return a value for a key in LocalStorage (ms)" + }, + "LOCALDOMSTORAGE_SETVALUE_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to set a single key's value in LocalStorage (ms)" + }, + "LOCALDOMSTORAGE_REMOVEKEY_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to remove a single key from LocalStorage (ms)" + }, + "LOCALDOMSTORAGE_REMOVEALL_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to clear LocalStorage for all domains (ms)" + }, + "LOCALDOMSTORAGE_FETCH_DOMAIN_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to fetch LocalStorage data for a domain (ms)" + }, + "LOCALDOMSTORAGE_FETCH_QUOTA_USE_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to fetch quota use stats for a TLD (ms)" + }, + "LOCALDOMSTORAGE_TIMER_FLUSH_MS": { + "kind": "exponential", + "high": "3000", + "n_buckets": 10, + "description": "Time to flush dirty entries from the cache (ms)" }, "LOCALDOMSTORAGE_KEY_SIZE_BYTES": { "kind": "exponential", diff --git a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp index bc8d14d426f..83f4a2f9878 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp @@ -276,6 +276,7 @@ nsUrlClassifierDBServiceWorker::DoLookup(const nsACString& spec, nsresult rv = OpenDb(); if (NS_FAILED(rv)) { c->LookupComplete(nullptr); + NS_ERROR("Unable to open SafeBrowsing database."); return NS_ERROR_FAILURE; } @@ -398,7 +399,7 @@ nsUrlClassifierDBServiceWorker::GetTables(nsIUrlClassifierCallback* c) nsresult rv = OpenDb(); if (NS_FAILED(rv)) { - NS_ERROR("Unable to open database"); + NS_ERROR("Unable to open SafeBrowsing database"); return NS_ERROR_FAILURE; } @@ -450,7 +451,7 @@ nsUrlClassifierDBServiceWorker::BeginUpdate(nsIUrlClassifierUpdateObserver *obse nsresult rv = OpenDb(); if (NS_FAILED(rv)) { - NS_ERROR("Unable to open database"); + NS_ERROR("Unable to open SafeBrowsing database"); return NS_ERROR_FAILURE; } @@ -641,9 +642,10 @@ NS_IMETHODIMP nsUrlClassifierDBServiceWorker::ResetDatabase() { nsresult rv = OpenDb(); - NS_ENSURE_SUCCESS(rv, rv); - mClassifier->Reset(); + if (NS_SUCCEEDED(rv)) { + mClassifier->Reset(); + } rv = CloseDb(); NS_ENSURE_SUCCESS(rv, rv); @@ -767,6 +769,10 @@ nsUrlClassifierDBServiceWorker::OpenDb() LOG(("Opening db")); + nsresult rv; + mCryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv); + NS_ENSURE_SUCCESS(rv, rv); + nsAutoPtr classifier(new Classifier()); if (!classifier) { return NS_ERROR_OUT_OF_MEMORY; @@ -775,17 +781,12 @@ nsUrlClassifierDBServiceWorker::OpenDb() classifier->SetFreshTime(gFreshnessGuarantee); classifier->SetPerClientRandomize(mPerClientRandomize); - nsresult rv = classifier->Open(*mCacheDir); - if (NS_FAILED(rv)) { - NS_WARNING("Failed to open URL classifier."); - } + rv = classifier->Open(*mCacheDir); + NS_ENSURE_SUCCESS(rv, rv); mHashKey = classifier->GetHashKey(); mClassifier = classifier; - mCryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv); - NS_ENSURE_SUCCESS(rv, rv); - return NS_OK; } diff --git a/toolkit/content/tests/chrome/Makefile.in b/toolkit/content/tests/chrome/Makefile.in index 3493c16523b..a78ad0af44c 100644 --- a/toolkit/content/tests/chrome/Makefile.in +++ b/toolkit/content/tests/chrome/Makefile.in @@ -159,6 +159,7 @@ MOCHITEST_CHROME_FILES = findbar_window.xul \ test_mousecapture.xul \ test_arrowpanel.xul \ test_menuitem_commands.xul \ + test_popup_moveToAnchor.xul \ $(NULL) # test_panel_focus.xul won't work if the Full Keyboard Access preference is set to diff --git a/toolkit/content/tests/chrome/test_popup_moveToAnchor.xul b/toolkit/content/tests/chrome/test_popup_moveToAnchor.xul new file mode 100644 index 00000000000..57dd833822b --- /dev/null +++ b/toolkit/content/tests/chrome/test_popup_moveToAnchor.xul @@ -0,0 +1,85 @@ + + + + + + + Popup moveToAnchor Tests + + + + +