Compare commits

..
Author SHA1 Message Date
Moonchild 610e44320c Issue #2342: Remove MOZ_MUST_USE macro 2023-11-05 12:38:11 +01:00
Moonchild 10476e27da Issue #2342: Use [[nodiscard]] in /mfbt 2023-11-05 12:37:04 +01:00
Moonchild a4777b1c21 Issue #2342: Use [[nodiscard]] in /xpcom and xpidl parser 2023-11-05 10:41:52 +01:00
Moonchild 9f6e448f78 Issue #2342: Use [[nodiscard]] in /uriloader /widget
Also a few misc low-volume places.
2023-11-05 00:59:31 +01:00
Moonchild 19a21bac1b Issue #2342: Use [[nodiscard]] in /netwerk 2023-11-04 23:42:53 +01:00
Moonchild c7867ce130 Issue #2342: Use [[nodiscard]] in /memory and remove Sun Studio hack 2023-11-04 22:57:30 +01:00
Moonchild 34c068e611 Issue #2342: Use [[nodiscard]] in /media 2023-11-04 22:28:58 +01:00
Moonchild a48e621048 Issue #2342: Use [[nodiscard]] in /js 2023-11-04 20:06:50 +01:00
Moonchild de5d3b1034 Issue #2342: Use [[nodiscard]] in IPDL generation and fix warnings
DOM plugin code had two warning in IPC caught by [[nodiscard]], these
were fixed in one go.
2023-11-04 01:24:20 +01:00
Moonchild f8737bbf4f Issue #2342: Use [[nodiscard]] in /ipc 2023-11-04 01:22:37 +01:00
Moonchild d9c70eaba2 Issue #2342: Use [[nodiscard]] in /hal /image and /intl 2023-11-04 01:21:57 +01:00
Moonchild 9308c63ce6 Issue #2281 - Remove the use of non-standard namespace std::tr1 in
Google's WebRTC gtest code
2023-11-04 00:13:32 +01:00
Moonchild 6314e01691 Issue #2342: Use [[nodiscard]] in /accessible and /caps 2023-11-03 12:17:29 +01:00
Moonchild b7b2f1de84 Issue #2342: Use [[nodiscard]] in /gfx and /layout 2023-11-03 00:34:37 +01:00
Moonchild b838d6634c Issue #2342: Use [[nodiscard]] in /dom 2023-11-03 00:17:31 +01:00
Moonchild dc4ea7f680 Merge branch 'master' into c++17-work 2023-11-02 12:20:37 +01:00
Moonchild 0e427867e3 Issue #2281 - Force clobber
Without a clobber, mozconfigure doesn't properly pick up the /std:c++17
or -std=gnu++17 compiler switches needed to put them into C++17 mode.
2023-10-18 14:40:16 +02:00
Moonchild 8137a4e122 Issue #2281 - Add some deduction guides for class template arguments.
This is necessary if we want to start using Span() constructors
instead of the MakeSpan() kludge.
2023-10-18 14:35:59 +02:00
Moonchild 46138995f6 Issue #2281 - Default to C++17 when building.
Configure the toolchain to default to C++17 language standard with
optional gnu extensions (if on GCC)
2023-10-15 15:12:23 +02:00
Moonchild aeb9de40a5 Issue #2281 - Avoid class-static constexpr in TypedArrayObject 2023-10-15 01:54:25 +02:00
Moonchild 3d693801f9 Issue #2281 - Build LZ4 as C instead of including it as C++. 2023-10-15 00:19:13 +02:00
Moonchild 14fa712b8c Issue #2281 - The 'register' storage class is no longer a thing in c++17 2023-10-13 23:12:37 +02:00
Moonchild 7d93034fd0 Issue #2281 - Mark mozalloc new() as noexcept to aligh with what the VC
runtime expects.

Currently spams warnings but may actually error out if not fixed, or
result in undefined behaviour if mismatching signatures are treated as
redeclarations with different exception specifications.
2023-10-13 23:12:00 +02:00
Moonchild 1769e74839 Issue #2281 - Replace std::iterator inheritance with iterator traits
definitions (as required by C++17).
2023-10-13 23:07:22 +02:00
16646 changed files with 1578319 additions and 5517737 deletions

No files matched your search

+1 -1
View File
@@ -22,4 +22,4 @@
# changes to stick? As of bug 928195, this shouldn't be necessary! Please # changes to stick? As of bug 928195, this shouldn't be necessary! Please
# don't change CLOBBER for WebIDL changes any more. # don't change CLOBBER for WebIDL changes any more.
Clobber for Issue #3027 Switching to C++17 requires CLOBBER to pick up compiler conf. (Issue #2281)
+4 -8
View File
@@ -14,7 +14,7 @@ endif
export TOPLEVEL_BUILD := 1 export TOPLEVEL_BUILD := 1
default:: default::
BACKEND_ONCE_STAMP := backend.once.stamp
ifndef TEST_MOZBUILD ifndef TEST_MOZBUILD
ifdef MOZ_BUILD_APP ifdef MOZ_BUILD_APP
include $(wildcard $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk) include $(wildcard $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk)
@@ -46,7 +46,7 @@ ifndef TEST_MOZBUILD
ifndef MOZ_PROFILE_USE ifndef MOZ_PROFILE_USE
# We need to explicitly put BUILD_BACKEND_FILES here otherwise the rule in # We need to explicitly put BUILD_BACKEND_FILES here otherwise the rule in
# rules.mk doesn't run early enough. # rules.mk doesn't run early enough.
$(TIERS) binaries:: CLOBBER $(configure_dir)/configure config.status $(BACKEND_ONCE_STAMP) $(TIERS) binaries:: CLOBBER $(configure_dir)/configure config.status $(BUILD_BACKEND_FILES)
# While our mozbuild backend has some kind of crazy install_manfests junk to # While our mozbuild backend has some kind of crazy install_manfests junk to
# try and make this not have to happen, we actually want dist/bin to be # try and make this not have to happen, we actually want dist/bin to be
@@ -100,11 +100,7 @@ config.status js/src/config.status:
ifndef TEST_MOZBUILD ifndef TEST_MOZBUILD
.PHONY: backend .PHONY: backend
backend: $(BACKEND_ONCE_STAMP) backend: $(BUILD_BACKEND_FILES)
# Create a per-invocation stamp so backend regenerates only once
$(BACKEND_ONCE_STAMP):
@echo "Stamping backend regeneration."
@$(TOUCH) $@
# A traditional rule would look like this: # A traditional rule would look like this:
# backend.%: # backend.%:
@@ -126,7 +122,7 @@ $(subst .,%,$(BUILD_BACKEND_FILES)):
@echo 'Build configuration changed. Regenerating backend.' @echo 'Build configuration changed. Regenerating backend.'
$(PYTHON) config.status $(PYTHON) config.status
Makefile: $(BACKEND_ONCE_STAMP) Makefile: $(BUILD_BACKEND_FILES)
@$(TOUCH) $@ @$(TOUCH) $@
define build_backend_rule define build_backend_rule
-7
View File
@@ -19,13 +19,6 @@ If you are interested in the development and building side of things, some
information will be available on the [Pale Moon developer site](http://developer.palemoon.org). information will be available on the [Pale Moon developer site](http://developer.palemoon.org).
You are also always welcome to get in touch with our community on the [Pale Moon forum](https://forum.palemoon.org/). You are also always welcome to get in touch with our community on the [Pale Moon forum](https://forum.palemoon.org/).
### Code search
While our repo has basic code searching capabilities (via `git grep`), you are strongly
encouraged to instead use the dedicated code search and cross-referencing site:
[https://xref.palemoon.org/](https://xref.palemoon.org/)
This repo and a copy of the front-end are amalgamated in the `goanna-central` index.
### A note about trademarks and branding ### A note about trademarks and branding
Although this repository is primarily licensed under Mozilla Public License v2.0, the Although this repository is primarily licensed under Mozilla Public License v2.0, the
-8
View File
@@ -1,8 +0,0 @@
TRADEMARK NOTICE
================
The name "Goanna" and visual representations (logo) have not been
registered by the Copyright owners as a trademark in any jurisdiction.
However, because Goanna has been distributed and maintained world-wide,
continually since 2015, the Copyright owners claim "common-law trademark
protection" in any jurisdiction where common-law trademark is recognized.
+15 -65
View File
@@ -6,7 +6,7 @@
#include "Platform.h" #include "Platform.h"
#include "nsIAccessibleEvent.h" #include "nsIAccessibleEvent.h"
#include "nsIGSettingsService.h" #include "nsIGConfService.h"
#include "nsIServiceManager.h" #include "nsIServiceManager.h"
#include "nsMai.h" #include "nsMai.h"
#include "AtkSocketAccessible.h" #include "AtkSocketAccessible.h"
@@ -18,6 +18,10 @@
#endif #endif
#include <gtk/gtk.h> #include <gtk/gtk.h>
#if (MOZ_WIDGET_GTK == 3)
extern "C" __attribute__((weak,visibility("default"))) int atk_bridge_adaptor_init(int*, char **[]);
#endif
using namespace mozilla; using namespace mozilla;
using namespace mozilla::a11y; using namespace mozilla::a11y;
@@ -29,20 +33,12 @@ extern "C" {
typedef GType (* AtkGetTypeType) (void); typedef GType (* AtkGetTypeType) (void);
typedef void (*GnomeAccessibilityInit) (void); typedef void (*GnomeAccessibilityInit) (void);
typedef void (*GnomeAccessibilityShutdown) (void); typedef void (*GnomeAccessibilityShutdown) (void);
#if (MOZ_WIDGET_GTK == 3)
typedef int (*AtkBridgeAdaptorInit) (int*, char***);
#endif
} }
static PRLibrary* sATKLib = nullptr; static PRLibrary* sATKLib = nullptr;
static const char sATKLibName[] = "libatk-1.0.so.0"; static const char sATKLibName[] = "libatk-1.0.so.0";
static const char sATKHyperlinkImplGetTypeSymbol[] = static const char sATKHyperlinkImplGetTypeSymbol[] =
"atk_hyperlink_impl_get_type"; "atk_hyperlink_impl_get_type";
#if (MOZ_WIDGET_GTK == 3)
static PRLibrary* sAtkBridgeAdaptorLib = nullptr;
static const char sAtkBridgeAdaptorLibName[] = "libatk-bridge-2.0.so.0";
static const char sAtkBridgeAdaptorInitSymbol[] = "atk_bridge_adaptor_init";
#endif
gboolean toplevel_event_watcher(GSignalInvocationHint*, guint, const GValue*, gboolean toplevel_event_watcher(GSignalInvocationHint*, guint, const GValue*,
gpointer); gpointer);
@@ -131,38 +127,6 @@ LoadGtkModule(GnomeAccessibilityModule& aModule)
return NS_OK; return NS_OK;
} }
#if (MOZ_WIDGET_GTK == 3)
static bool
InitAtkBridgeAdaptor()
{
AtkBridgeAdaptorInit initBridge =
reinterpret_cast<AtkBridgeAdaptorInit>(
PR_FindFunctionSymbolAndLibrary(sAtkBridgeAdaptorInitSymbol,
&sAtkBridgeAdaptorLib));
if (!initBridge) {
sAtkBridgeAdaptorLib = PR_LoadLibrary(sAtkBridgeAdaptorLibName);
if (sAtkBridgeAdaptorLib) {
initBridge =
reinterpret_cast<AtkBridgeAdaptorInit>(
PR_FindFunctionSymbol(sAtkBridgeAdaptorLib,
sAtkBridgeAdaptorInitSymbol));
if (!initBridge) {
PR_UnloadLibrary(sAtkBridgeAdaptorLib);
sAtkBridgeAdaptorLib = nullptr;
}
}
}
if (!initBridge) {
return false;
}
initBridge(nullptr, nullptr);
return true;
}
#endif
void void
a11y::PlatformInit() a11y::PlatformInit()
{ {
@@ -217,7 +181,9 @@ a11y::PlatformInit()
// Init atk-bridge now // Init atk-bridge now
PR_SetEnv("NO_AT_BRIDGE=0"); PR_SetEnv("NO_AT_BRIDGE=0");
#if (MOZ_WIDGET_GTK == 3) #if (MOZ_WIDGET_GTK == 3)
if (!InitAtkBridgeAdaptor()) if (atk_bridge_adaptor_init) {
atk_bridge_adaptor_init(nullptr, nullptr);
} else
#endif #endif
{ {
nsresult rv = LoadGtkModule(sAtkBridge); nsresult rv = LoadGtkModule(sAtkBridge);
@@ -262,13 +228,6 @@ a11y::PlatformShutdown()
sAtkBridge.init = nullptr; sAtkBridge.init = nullptr;
sAtkBridge.shutdown = nullptr; sAtkBridge.shutdown = nullptr;
} }
#if (MOZ_WIDGET_GTK == 3)
if (sAtkBridgeAdaptorLib) {
// Do not shutdown/unload atk-bridge; an exit function registered by
// the bridge will take care of it.
sAtkBridgeAdaptorLib = nullptr;
}
#endif
#if (MOZ_WIDGET_GTK == 2) #if (MOZ_WIDGET_GTK == 2)
if (sGail.lib) { if (sGail.lib) {
// Do not shutdown gail because // Do not shutdown gail because
@@ -401,22 +360,13 @@ dbus_done:
return sShouldEnable; return sShouldEnable;
#endif #endif
// check GSettings //check gconf-2 setting
#define GSETINGS_A11Y_INTERFACE "org.gnome.desktop.interface" #define GCONF_A11Y_KEY "/desktop/gnome/interface/accessibility"
#define GSETINGS_A11Y_KEY "toolkit-accessibility" nsresult rv = NS_OK;
nsCOMPtr<nsIGSettingsService> gsettings = nsCOMPtr<nsIGConfService> gconf =
do_GetService(NS_GSETTINGSSERVICE_CONTRACTID); do_GetService(NS_GCONFSERVICE_CONTRACTID, &rv);
nsCOMPtr<nsIGSettingsCollection> a11y_settings; if (NS_SUCCEEDED(rv) && gconf)
gconf->GetBool(NS_LITERAL_CSTRING(GCONF_A11Y_KEY), &sShouldEnable);
if (gsettings) {
gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(GSETINGS_A11Y_INTERFACE),
getter_AddRefs(a11y_settings));
if (a11y_settings) {
a11y_settings->GetBoolean(NS_LITERAL_CSTRING(GSETINGS_A11Y_KEY),
&sShouldEnable);
}
}
return sShouldEnable; return sShouldEnable;
} }
+1 -1
View File
@@ -55,7 +55,7 @@ private:
{ {
explicit IteratorState(Accessible* aParent, IteratorState* mParentState = nullptr); explicit IteratorState(Accessible* aParent, IteratorState* mParentState = nullptr);
RefPtr<Accessible> mParent; Accessible* mParent;
int32_t mIndex; int32_t mIndex;
IteratorState* mParentState; IteratorState* mParentState;
}; };
@@ -276,7 +276,6 @@ NotificationController::DropMutationEvent(AccTreeMutationEvent* aEvent)
MOZ_ASSERT(hideEvent); MOZ_ASSERT(hideEvent);
if (hideEvent->NeedsShutdown()) { if (hideEvent->NeedsShutdown()) {
mDocument->UncacheChildrenInSubtree(aEvent->GetAccessible());
mDocument->ShutdownChildrenInSubtree(aEvent->GetAccessible()); mDocument->ShutdownChildrenInSubtree(aEvent->GetAccessible());
} }
} }
-4
View File
@@ -7,10 +7,6 @@
* ROLE(geckoRole, stringRole, atkRole, macRole, msaaRole, ia2Role, nameRule) * ROLE(geckoRole, stringRole, atkRole, macRole, msaaRole, ia2Role, nameRule)
*/ */
#ifndef NSAccessibilityCellRole
#define NSAccessibilityCellRole NSAccessibilityUnknownRole
#endif
ROLE(NOTHING, ROLE(NOTHING,
"nothing", "nothing",
ATK_ROLE_UNKNOWN, ATK_ROLE_UNKNOWN,
+1 -1
View File
@@ -80,7 +80,7 @@ StyleInfo::TextIndent(nsAString& aValue)
} }
void void
StyleInfo::Margin(Side aSide, nsAString& aValue) StyleInfo::Margin(css::Side aSide, nsAString& aValue)
{ {
MOZ_ASSERT(mElement->GetPrimaryFrame(), " mElement->GetPrimaryFrame() needs to be valid pointer"); MOZ_ASSERT(mElement->GetPrimaryFrame(), " mElement->GetPrimaryFrame() needs to be valid pointer");
aValue.Truncate(); aValue.Truncate();
+4 -12
View File
@@ -44,9 +44,7 @@
#ifdef XP_WIN #ifdef XP_WIN
#include "mozilla/a11y/Compatibility.h" #include "mozilla/a11y/Compatibility.h"
#include "mozilla/dom/ContentChild.h" #include "mozilla/dom/ContentChild.h"
#ifdef MOZ_ENABLE_NPAPI
#include "HTMLWin32ObjectAccessible.h" #include "HTMLWin32ObjectAccessible.h"
#endif
#include "mozilla/StaticPtr.h" #include "mozilla/StaticPtr.h"
#endif #endif
@@ -57,10 +55,8 @@
#include "nsImageFrame.h" #include "nsImageFrame.h"
#include "nsIObserverService.h" #include "nsIObserverService.h"
#include "nsLayoutUtils.h" #include "nsLayoutUtils.h"
#ifdef MOZ_ENABLE_NPAPI
#include "nsPluginFrame.h" #include "nsPluginFrame.h"
#endif #include "nsSVGPathGeometryFrame.h"
#include "SVGGeometryFrame.h"
#include "nsTreeBodyFrame.h" #include "nsTreeBodyFrame.h"
#include "nsTreeColumns.h" #include "nsTreeColumns.h"
#include "nsTreeUtils.h" #include "nsTreeUtils.h"
@@ -83,7 +79,7 @@
#include "XULTabAccessible.h" #include "XULTabAccessible.h"
#include "XULTreeGridAccessibleWrap.h" #include "XULTreeGridAccessibleWrap.h"
#if (defined(XP_WIN) || defined(MOZ_ACCESSIBILITY_ATK)) && defined(MOZ_ENABLE_NPAPI) #if defined(XP_WIN) || defined(MOZ_ACCESSIBILITY_ATK)
#include "nsNPAPIPluginInstance.h" #include "nsNPAPIPluginInstance.h"
#endif #endif
@@ -435,7 +431,6 @@ private:
NS_IMPL_ISUPPORTS(PluginTimerCallBack, nsITimerCallback) NS_IMPL_ISUPPORTS(PluginTimerCallBack, nsITimerCallback)
#endif #endif
#ifdef MOZ_ENABLE_NPAPI
already_AddRefed<Accessible> already_AddRefed<Accessible>
nsAccessibilityService::CreatePluginAccessible(nsPluginFrame* aFrame, nsAccessibilityService::CreatePluginAccessible(nsPluginFrame* aFrame,
nsIContent* aContent, nsIContent* aContent,
@@ -498,7 +493,6 @@ nsAccessibilityService::CreatePluginAccessible(nsPluginFrame* aFrame,
return nullptr; return nullptr;
} }
#endif // MOZ_ENABLE_NPAPI
void void
nsAccessibilityService::DeckPanelSwitched(nsIPresShell* aPresShell, nsAccessibilityService::DeckPanelSwitched(nsIPresShell* aPresShell,
@@ -1165,8 +1159,8 @@ nsAccessibilityService::CreateAccessible(nsINode* aNode,
if (!newAcc) { if (!newAcc) {
if (content->IsSVGElement()) { if (content->IsSVGElement()) {
SVGGeometryFrame* geometryFrame = do_QueryFrame(frame); nsSVGPathGeometryFrame* pathGeometryFrame = do_QueryFrame(frame);
if (geometryFrame) { if (pathGeometryFrame) {
// A graphic elements: rect, circle, ellipse, line, path, polygon, // A graphic elements: rect, circle, ellipse, line, path, polygon,
// polyline and image. A 'use' and 'text' graphic elements require // polyline and image. A 'use' and 'text' graphic elements require
// special support. // special support.
@@ -1644,13 +1638,11 @@ nsAccessibilityService::CreateAccessibleByFrameType(nsIFrame* aFrame,
case eOuterDocType: case eOuterDocType:
newAcc = new OuterDocAccessible(aContent, document); newAcc = new OuterDocAccessible(aContent, document);
break; break;
#ifdef MOZ_ENABLE_NPAPI
case ePluginType: { case ePluginType: {
nsPluginFrame* pluginFrame = do_QueryFrame(aFrame); nsPluginFrame* pluginFrame = do_QueryFrame(aFrame);
newAcc = CreatePluginAccessible(pluginFrame, aContent, aContext); newAcc = CreatePluginAccessible(pluginFrame, aContent, aContext);
break; break;
} }
#endif
case eTextLeafType: case eTextLeafType:
newAcc = new TextLeafAccessibleWrap(aContent, document); newAcc = new TextLeafAccessibleWrap(aContent, document);
break; break;
-4
View File
@@ -20,9 +20,7 @@
class nsImageFrame; class nsImageFrame;
class nsIArray; class nsIArray;
class nsIPersistentProperties; class nsIPersistentProperties;
#ifdef MOZ_ENABLE_NPAPI
class nsPluginFrame; class nsPluginFrame;
#endif
class nsITreeView; class nsITreeView;
namespace mozilla { namespace mozilla {
@@ -89,11 +87,9 @@ public:
Accessible* GetRootDocumentAccessible(nsIPresShell* aPresShell, Accessible* GetRootDocumentAccessible(nsIPresShell* aPresShell,
bool aCanCreate); bool aCanCreate);
#ifdef MOZ_ENABLE_NPAPI
already_AddRefed<Accessible> already_AddRefed<Accessible>
CreatePluginAccessible(nsPluginFrame* aFrame, nsIContent* aContent, CreatePluginAccessible(nsPluginFrame* aFrame, nsIContent* aContent,
Accessible* aContext); Accessible* aContext);
#endif
/** /**
* Adds/remove ATK root accessible for gtk+ native window to/from children * Adds/remove ATK root accessible for gtk+ native window to/from children
+1 -3
View File
@@ -157,7 +157,7 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(DocAccessible, Accessible)
tmp->mARIAOwnsHash.Clear(); tmp->mARIAOwnsHash.Clear();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DocAccessible) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DocAccessible)
NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver) NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver)
NS_INTERFACE_MAP_ENTRY(nsIMutationObserver) NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
@@ -1307,8 +1307,6 @@ DocAccessible::UnbindFromDocument(Accessible* aAccessible)
{ {
NS_ASSERTION(mAccessibleCache.GetWeak(aAccessible->UniqueID()), NS_ASSERTION(mAccessibleCache.GetWeak(aAccessible->UniqueID()),
"Unbinding the unbound accessible!"); "Unbinding the unbound accessible!");
MOZ_ASSERT(!mARIAOwnsHash.Contains(aAccessible),
"Container still lingering in mARIAOwnsHash");
// Fire focus event on accessible having DOM focus if active item was removed // Fire focus event on accessible having DOM focus if active item was removed
// from the tree. // from the tree.
+1 -1
View File
@@ -76,7 +76,7 @@ HyperTextAccessible::NativeState()
{ {
uint64_t states = AccessibleWrap::NativeState(); uint64_t states = AccessibleWrap::NativeState();
if (mContent->AsElement()->State().HasState(NS_EVENT_STATE_READWRITE)) { if (mContent->AsElement()->State().HasState(NS_EVENT_STATE_MOZ_READWRITE)) {
states |= states::EDITABLE; states |= states::EDITABLE;
} else if (mContent->IsHTMLElement(nsGkAtoms::article)) { } else if (mContent->IsHTMLElement(nsGkAtoms::article)) {
+1 -2
View File
@@ -486,14 +486,13 @@ DocAccessibleParent::SetCOMProxy(const RefPtr<IAccessible>& aCOMProxy)
IAccessibleHolder holder(Move(ptr)); IAccessibleHolder holder(Move(ptr));
Unused << SendParentCOMProxy(holder); Unused << SendParentCOMProxy(holder);
} }
#ifdef MOZ_ENABLE_NPAPI
bool bool
DocAccessibleParent::RecvGetWindowedPluginIAccessible( DocAccessibleParent::RecvGetWindowedPluginIAccessible(
const WindowsHandle& aHwnd, IAccessibleHolder* aPluginCOMProxy) const WindowsHandle& aHwnd, IAccessibleHolder* aPluginCOMProxy)
{ {
return false; return false;
} }
#endif
#endif // defined(XP_WIN) #endif // defined(XP_WIN)
+2 -3
View File
@@ -143,11 +143,10 @@ public:
#if defined(XP_WIN) #if defined(XP_WIN)
void SetCOMProxy(const RefPtr<IAccessible>& aCOMProxy); void SetCOMProxy(const RefPtr<IAccessible>& aCOMProxy);
#ifdef MOZ_ENABLE_NPAPI
virtual bool RecvGetWindowedPluginIAccessible( virtual bool RecvGetWindowedPluginIAccessible(
const WindowsHandle& aHwnd, IAccessibleHolder* aPluginCOMProxy) override; const WindowsHandle& aHwnd, IAccessibleHolder* aPluginCOMProxy) override;
#endif // MOZ_ENABLE_NPAPI #endif
#endif // XP_WIN
private: private:
-2
View File
@@ -61,10 +61,8 @@ parent:
*/ */
async BindChildDoc(PDocAccessible aChildDoc, uint64_t aID); async BindChildDoc(PDocAccessible aChildDoc, uint64_t aID);
#ifdef MOZ_ENABLE_NPAPI
sync GetWindowedPluginIAccessible(WindowsHandle aHwnd) sync GetWindowedPluginIAccessible(WindowsHandle aHwnd)
returns (IAccessibleHolder aPluginCOMProxy); returns (IAccessibleHolder aPluginCOMProxy);
#endif
child: child:
async ParentCOMProxy(IAccessibleHolder aParentCOMProxy); async ParentCOMProxy(IAccessibleHolder aParentCOMProxy);
+1 -1
View File
@@ -8,7 +8,7 @@ if CONFIG['COMPILE_ENVIRONMENT']:
# With --disable-accessibility, we need to compile PDocAccessible.ipdl (which # With --disable-accessibility, we need to compile PDocAccessible.ipdl (which
# also depends on COMPtrTypes.h), but not the C++. # also depends on COMPtrTypes.h), but not the C++.
PREPROCESSED_IPDL_SOURCES += ['PDocAccessible.ipdl'] IPDL_SOURCES += ['PDocAccessible.ipdl']
EXPORTS.mozilla.a11y += ['COMPtrTypes.h'] EXPORTS.mozilla.a11y += ['COMPtrTypes.h']
if CONFIG['ACCESSIBILITY']: if CONFIG['ACCESSIBILITY']:
+2 -2
View File
@@ -340,9 +340,9 @@ this.AccessFu = { // jshint ignore:line
case 'remote-browser-shown': case 'remote-browser-shown':
case 'inprocess-browser-shown': case 'inprocess-browser-shown':
{ {
// Ignore notifications that aren't from a Browser // Ignore notifications that aren't from a BrowserOrApp
let frameLoader = aSubject.QueryInterface(Ci.nsIFrameLoader); let frameLoader = aSubject.QueryInterface(Ci.nsIFrameLoader);
if (!frameLoader.ownerIsMozBrowserFrame) { if (!frameLoader.ownerIsMozBrowserOrAppFrame) {
return; return;
} }
this._handleMessageManager(frameLoader.messageManager); this._handleMessageManager(frameLoader.messageManager);
-2
View File
@@ -295,7 +295,6 @@ enum CheckboxValue {
@implementation mozPaneAccessible @implementation mozPaneAccessible
#if defined(MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
- (NSUInteger)accessibilityArrayAttributeCount:(NSString*)attribute - (NSUInteger)accessibilityArrayAttributeCount:(NSString*)attribute
{ {
AccessibleWrap* accWrap = [self getGeckoAccessible]; AccessibleWrap* accWrap = [self getGeckoAccessible];
@@ -314,7 +313,6 @@ enum CheckboxValue {
return [super accessibilityArrayAttributeCount:attribute]; return [super accessibilityArrayAttributeCount:attribute];
} }
#endif
- (NSArray*)children - (NSArray*)children
{ {
+4 -34
View File
@@ -47,24 +47,6 @@ ConvertToNSArray(nsTArray<ProxyAccessible*>& aArray)
return nativeArray; return nativeArray;
} }
// Convert to an object without @ syntax
static inline id
ConvertToId(NSInteger val)
{
return [NSString stringWithFormat:@"%i", val];
}
// Missing from SDK 10.5
#if !defined(MAC_OS_X_VERSION_10_6) || (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6)
#define __IntToNSString(x) ([NSString stringWithFormat:@"%i", x])
#define NSAccessibilityRowIndexRangeAttribute @"AXRowIndexRange"
#define NSAccessibilityColumnIndexRangeAttribute @"AXColumnIndexRange"
#define NSAccessibilityRowHeaderUIElementsAttribute @"AXRowHeaderUIElements"
#define NSAccessibilityColumnHeaderUIElementsAttribute @"AXColumnHeaderUIElements"
#define NSAccessibilityRowCountAttribute @"AXRowCount"
#define NSAccessibilityColumnCountAttribute @"AXColumnCount"
#endif
@implementation mozTablePartAccessible @implementation mozTablePartAccessible
- (BOOL)isLayoutTablePart; - (BOOL)isLayoutTablePart;
{ {
@@ -101,14 +83,10 @@ ConvertToId(NSInteger val)
{ {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL; NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
#if defined(MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames]; NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames];
if ([self isLayoutTablePart]) { if ([self isLayoutTablePart]) {
return additionalAttributes; return additionalAttributes;
} }
#else
NSArray* additionalAttributes = [[NSArray alloc] init];
#endif
static NSArray* tableAttrs = nil; static NSArray* tableAttrs = nil;
if (!tableAttrs) { if (!tableAttrs) {
@@ -130,9 +108,9 @@ ConvertToId(NSInteger val)
if (AccessibleWrap* accWrap = [self getGeckoAccessible]) { if (AccessibleWrap* accWrap = [self getGeckoAccessible]) {
TableAccessible* table = accWrap->AsTable(); TableAccessible* table = accWrap->AsTable();
if ([attribute isEqualToString:NSAccessibilityRowCountAttribute]) if ([attribute isEqualToString:NSAccessibilityRowCountAttribute])
return ConvertToId(table->RowCount()); return @(table->RowCount());
if ([attribute isEqualToString:NSAccessibilityColumnCountAttribute]) if ([attribute isEqualToString:NSAccessibilityColumnCountAttribute])
return ConvertToId(table->ColCount()); return @(table->ColCount());
if ([attribute isEqualToString:NSAccessibilityRowsAttribute]) { if ([attribute isEqualToString:NSAccessibilityRowsAttribute]) {
// Create a new array with the list of table rows. // Create a new array with the list of table rows.
NSMutableArray* nativeArray = [[NSMutableArray alloc] init]; NSMutableArray* nativeArray = [[NSMutableArray alloc] init];
@@ -149,9 +127,9 @@ ConvertToId(NSInteger val)
} }
} else if (ProxyAccessible* proxy = [self getProxyAccessible]) { } else if (ProxyAccessible* proxy = [self getProxyAccessible]) {
if ([attribute isEqualToString:NSAccessibilityRowCountAttribute]) if ([attribute isEqualToString:NSAccessibilityRowCountAttribute])
return ConvertToId(proxy->TableRowCount()); return @(proxy->TableRowCount());
if ([attribute isEqualToString:NSAccessibilityColumnCountAttribute]) if ([attribute isEqualToString:NSAccessibilityColumnCountAttribute])
return ConvertToId(proxy->TableColumnCount()); return @(proxy->TableColumnCount());
if ([attribute isEqualToString:NSAccessibilityRowsAttribute]) { if ([attribute isEqualToString:NSAccessibilityRowsAttribute]) {
// Create a new array with the list of table rows. // Create a new array with the list of table rows.
NSMutableArray* nativeArray = [[NSMutableArray alloc] init]; NSMutableArray* nativeArray = [[NSMutableArray alloc] init];
@@ -177,14 +155,10 @@ ConvertToId(NSInteger val)
{ {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL; NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
#if defined(MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames]; NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames];
if ([self isLayoutTablePart]) { if ([self isLayoutTablePart]) {
return additionalAttributes; return additionalAttributes;
} }
#else
NSArray* additionalAttributes = [[NSArray alloc] init];
#endif
static NSArray* tableRowAttrs = nil; static NSArray* tableRowAttrs = nil;
if (!tableRowAttrs) { if (!tableRowAttrs) {
@@ -240,14 +214,10 @@ ConvertToId(NSInteger val)
{ {
NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL; NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
#if defined(MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames]; NSArray* additionalAttributes = [super additionalAccessibilityAttributeNames];
if ([self isLayoutTablePart]) { if ([self isLayoutTablePart]) {
return additionalAttributes; return additionalAttributes;
} }
#else
NSArray* additionalAttributes = [[NSArray alloc] init];
#endif
static NSArray* tableCellAttrs = nil; static NSArray* tableCellAttrs = nil;
if (!tableCellAttrs) { if (!tableCellAttrs) {
+1 -7
View File
@@ -23,6 +23,7 @@ SOURCES += [
'DocAccessibleWrap.cpp', 'DocAccessibleWrap.cpp',
'EnumVariant.cpp', 'EnumVariant.cpp',
'HTMLTableAccessibleWrap.cpp', 'HTMLTableAccessibleWrap.cpp',
'HTMLWin32ObjectAccessible.cpp',
'HyperTextAccessibleWrap.cpp', 'HyperTextAccessibleWrap.cpp',
'ImageAccessibleWrap.cpp', 'ImageAccessibleWrap.cpp',
'IUnknownImpl.cpp', 'IUnknownImpl.cpp',
@@ -37,13 +38,6 @@ SOURCES += [
'XULTreeGridAccessibleWrap.cpp', 'XULTreeGridAccessibleWrap.cpp',
] ]
if CONFIG['MOZ_ENABLE_NPAPI']:
SOURCES += [
'HTMLWin32ObjectAccessible.cpp',
]
LOCAL_INCLUDES += [ LOCAL_INCLUDES += [
'/accessible/base', '/accessible/base',
'/accessible/generic', '/accessible/generic',
+9 -9
View File
@@ -40,7 +40,7 @@ def loadEventIDL(parser, includePath, eventname):
class Configuration: class Configuration:
def __init__(self, filename): def __init__(self, filename):
config = {} config = {}
exec(compile(open(filename, "rb").read(), filename, 'exec'), config) execfile(filename, config)
self.simple_events = config.get('simple_events', []) self.simple_events = config.get('simple_events', [])
def firstCap(str): def firstCap(str):
@@ -64,7 +64,7 @@ def print_header_file(fd, conf, incdirs):
for e in conf.simple_events: for e in conf.simple_events:
idl, idl_path = loadEventIDL(p, incdirs, e) idl, idl_path = loadEventIDL(p, incdirs, e)
idl_paths.add(idl_path) idl_paths.add(idl_path)
for iface in [p for p in idl.productions if p.kind == "interface"]: for iface in filter(lambda p: p.kind == "interface", idl.productions):
classname = ("xpcAcc%s" % e) classname = ("xpcAcc%s" % e)
baseinterfaces = interfaces(iface) baseinterfaces = interfaces(iface)
@@ -73,7 +73,7 @@ def print_header_file(fd, conf, incdirs):
fd.write("public:\n") fd.write("public:\n")
attributes = allAttributes(iface) attributes = allAttributes(iface)
args = list(map(writeAttributeParams, attributes)) args = map(writeAttributeParams, attributes)
fd.write(" %s(%s) :\n" % (classname, ", ".join(args))) fd.write(" %s(%s) :\n" % (classname, ", ".join(args)))
initializers = [] initializers = []
@@ -83,7 +83,7 @@ def print_header_file(fd, conf, incdirs):
fd.write(" NS_DECL_CYCLE_COLLECTING_ISUPPORTS\n") fd.write(" NS_DECL_CYCLE_COLLECTING_ISUPPORTS\n")
fd.write(" NS_DECL_CYCLE_COLLECTION_CLASS(%s)\n" % (classname)) fd.write(" NS_DECL_CYCLE_COLLECTION_CLASS(%s)\n" % (classname))
for iface in [i for i in baseinterfaces if i.name != "nsISupports"]: for iface in filter(lambda i: i.name != "nsISupports", baseinterfaces):
fd.write(" NS_DECL_%s\n" % iface.name.upper()) fd.write(" NS_DECL_%s\n" % iface.name.upper())
fd.write("\nprivate:\n") fd.write("\nprivate:\n")
@@ -97,13 +97,13 @@ def print_header_file(fd, conf, incdirs):
return idl_paths return idl_paths
def interfaceAttributeTypes(idl): def interfaceAttributeTypes(idl):
ifaces = [p for p in idl.productions if p.kind == "interface"] ifaces = filter(lambda p: p.kind == "interface", idl.productions)
attributes = [] attributes = []
for i in ifaces: for i in ifaces:
ifaceAttributes = allAttributes(i) ifaceAttributes = allAttributes(i)
attributes.extend(ifaceAttributes) attributes.extend(ifaceAttributes)
ifaceAttrs = [a for a in attributes if a.realtype.nativeType("in").endswith("*")] ifaceAttrs = filter(lambda a: a.realtype.nativeType("in").endswith("*"), attributes)
return [a.realtype.nativeType("in").strip(" *") for a in ifaceAttrs] return map(lambda a: a.realtype.nativeType("in").strip(" *"), ifaceAttrs)
def print_cpp(idl, fd, conf, eventname): def print_cpp(idl, fd, conf, eventname):
for p in idl.productions: for p in idl.productions:
@@ -186,7 +186,7 @@ def interfaces(iface):
def allAttributes(iface): def allAttributes(iface):
attributes = [] attributes = []
for i in interfaces(iface): for i in interfaces(iface):
attrs = [m for m in i.members if isinstance(m, xpidl.Attribute)] attrs = filter(lambda m: isinstance(m, xpidl.Attribute), i.members)
attributes.extend(attrs) attributes.extend(attrs)
return attributes return attributes
@@ -194,7 +194,7 @@ def allAttributes(iface):
def write_cpp(eventname, iface, fd): def write_cpp(eventname, iface, fd):
classname = "xpcAcc%s" % eventname classname = "xpcAcc%s" % eventname
attributes = allAttributes(iface) attributes = allAttributes(iface)
ccattributes = [m for m in attributes if m.realtype.nativeType('in').endswith('*')] ccattributes = filter(lambda m: m.realtype.nativeType('in').endswith('*'), attributes)
fd.write("NS_IMPL_CYCLE_COLLECTION(%s" % classname) fd.write("NS_IMPL_CYCLE_COLLECTION(%s" % classname)
for c in ccattributes: for c in ccattributes:
fd.write(", m%s" % firstCap(c.name)) fd.write(", m%s" % firstCap(c.name))
+1 -1
View File
@@ -30,7 +30,7 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(xpcAccessibleDocument,
tmp->mCache.Clear(); tmp->mCache.Clear();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(xpcAccessibleDocument) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(xpcAccessibleDocument)
NS_INTERFACE_MAP_ENTRY(nsIAccessibleDocument) NS_INTERFACE_MAP_ENTRY(nsIAccessibleDocument)
NS_INTERFACE_MAP_END_INHERITING(xpcAccessibleHyperText) NS_INTERFACE_MAP_END_INHERITING(xpcAccessibleHyperText)
+8 -5
View File
@@ -73,7 +73,7 @@ XULTreeAccessible::~XULTreeAccessible()
NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeAccessible, Accessible, NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeAccessible, Accessible,
mTree, mAccessibleCache) mTree, mAccessibleCache)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XULTreeAccessible) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XULTreeAccessible)
NS_INTERFACE_MAP_END_INHERITING(Accessible) NS_INTERFACE_MAP_END_INHERITING(Accessible)
NS_IMPL_ADDREF_INHERITED(XULTreeAccessible, Accessible) NS_IMPL_ADDREF_INHERITED(XULTreeAccessible, Accessible)
@@ -709,9 +709,12 @@ XULTreeItemAccessibleBase::~XULTreeItemAccessibleBase()
NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessibleBase, Accessible, NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessibleBase, Accessible,
mTree) mTree)
NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessibleBase, NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessibleBase)
Accessible, NS_INTERFACE_TABLE_INHERITED(XULTreeItemAccessibleBase,
XULTreeItemAccessibleBase) XULTreeItemAccessibleBase)
NS_INTERFACE_TABLE_TAIL_INHERITING(Accessible)
NS_IMPL_ADDREF_INHERITED(XULTreeItemAccessibleBase, Accessible)
NS_IMPL_RELEASE_INHERITED(XULTreeItemAccessibleBase, Accessible)
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// XULTreeItemAccessibleBase: Accessible // XULTreeItemAccessibleBase: Accessible
@@ -1081,7 +1084,7 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessible,
XULTreeItemAccessibleBase, XULTreeItemAccessibleBase,
mColumn) mColumn)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XULTreeItemAccessible) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XULTreeItemAccessible)
NS_INTERFACE_MAP_END_INHERITING(XULTreeItemAccessibleBase) NS_INTERFACE_MAP_END_INHERITING(XULTreeItemAccessibleBase)
NS_IMPL_ADDREF_INHERITED(XULTreeItemAccessible, XULTreeItemAccessibleBase) NS_IMPL_ADDREF_INHERITED(XULTreeItemAccessible, XULTreeItemAccessibleBase)
NS_IMPL_RELEASE_INHERITED(XULTreeItemAccessible, XULTreeItemAccessibleBase) NS_IMPL_RELEASE_INHERITED(XULTreeItemAccessible, XULTreeItemAccessibleBase)
+2 -2
View File
@@ -263,7 +263,7 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeGridRowAccessible,
XULTreeItemAccessibleBase, XULTreeItemAccessibleBase,
mAccessibleCache) mAccessibleCache)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XULTreeGridRowAccessible) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XULTreeGridRowAccessible)
NS_INTERFACE_MAP_END_INHERITING(XULTreeItemAccessibleBase) NS_INTERFACE_MAP_END_INHERITING(XULTreeItemAccessibleBase)
NS_IMPL_ADDREF_INHERITED(XULTreeGridRowAccessible, NS_IMPL_ADDREF_INHERITED(XULTreeGridRowAccessible,
@@ -447,7 +447,7 @@ XULTreeGridCellAccessible::~XULTreeGridCellAccessible()
NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeGridCellAccessible, LeafAccessible, NS_IMPL_CYCLE_COLLECTION_INHERITED(XULTreeGridCellAccessible, LeafAccessible,
mTree, mColumn) mTree, mColumn)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XULTreeGridCellAccessible) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XULTreeGridCellAccessible)
NS_INTERFACE_MAP_END_INHERITING(LeafAccessible) NS_INTERFACE_MAP_END_INHERITING(LeafAccessible)
NS_IMPL_ADDREF_INHERITED(XULTreeGridCellAccessible, LeafAccessible) NS_IMPL_ADDREF_INHERITED(XULTreeGridCellAccessible, LeafAccessible)
NS_IMPL_RELEASE_INHERITED(XULTreeGridCellAccessible, LeafAccessible) NS_IMPL_RELEASE_INHERITED(XULTreeGridCellAccessible, LeafAccessible)
+5 -4
View File
@@ -5,11 +5,11 @@
'''Parses a given application.ini file and outputs the corresponding '''Parses a given application.ini file and outputs the corresponding
XULAppData structure as a C++ header file''' XULAppData structure as a C++ header file'''
import configparser import ConfigParser
import sys import sys
def main(output, file): def main(output, file):
config = configparser.RawConfigParser() config = ConfigParser.RawConfigParser()
config.read(file) config.read(file)
flags = set() flags = set()
try: try:
@@ -27,7 +27,8 @@ def main(output, file):
'App:id', 'Gecko:minversion', 'Gecko:maxversion') 'App:id', 'Gecko:minversion', 'Gecko:maxversion')
missing = [var for var in expected if var not in appdata] missing = [var for var in expected if var not in appdata]
if missing: if missing:
print("Missing values in %s: %s" % (file, ', '.join(missing)), file=sys.stderr) print >>sys.stderr, \
"Missing values in %s: %s" % (file, ', '.join(missing))
sys.exit(1) sys.exit(1)
if not 'Crash Reporter:serverurl' in appdata: if not 'Crash Reporter:serverurl' in appdata:
@@ -56,4 +57,4 @@ if __name__ == '__main__':
if len(sys.argv) != 1: if len(sys.argv) != 1:
main(sys.stdout, sys.argv[1]) main(sys.stdout, sys.argv[1])
else: else:
print("Usage: %s /path/to/application.ini" % sys.argv[0], file=sys.stderr) print >>sys.stderr, "Usage: %s /path/to/application.ini" % sys.argv[0]
File diff suppressed because it is too large. Load diff
-80
View File
@@ -1,80 +0,0 @@
dnl Map old names of Autoconf macros to new regularized names.
dnl This file is part of Autoconf.
dnl Copyright (C) 1994 Free Software Foundation, Inc.
dnl
dnl This program is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation; either version 2, or (at your option)
dnl any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with this program; if not, write to the Free Software
dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
dnl 02111-1307, USA.
dnl
dnl General macros.
dnl
define(AC_WARN, [indir([AC_MSG_WARN], $@)])dnl
define(AC_ERROR, [indir([AC_MSG_ERROR], $@)])dnl
AC_DEFUN(AC_PROGRAM_CHECK, [indir([AC_CHECK_PROG], $@)])dnl
AC_DEFUN(AC_PROGRAM_PATH, [indir([AC_PATH_PROG], $@)])dnl
AC_DEFUN(AC_PROGRAMS_CHECK, [indir([AC_CHECK_PROGS], $@)])dnl
AC_DEFUN(AC_PROGRAMS_PATH, [indir([AC_PATH_PROGS], $@)])dnl
AC_DEFUN(AC_PREFIX, [indir([AC_PREFIX_PROGRAM], $@)])dnl
AC_DEFUN(AC_HEADER_EGREP, [indir([AC_EGREP_HEADER], $@)])dnl
AC_DEFUN(AC_PROGRAM_EGREP, [indir([AC_EGREP_CPP], $@)])dnl
AC_DEFUN(AC_TEST_PROGRAM, [indir([AC_TRY_RUN], $@)])dnl
AC_DEFUN(AC_TEST_CPP, [indir([AC_TRY_CPP], $@)])dnl
AC_DEFUN(AC_HEADER_CHECK, [indir([AC_CHECK_HEADER], $@)])dnl
AC_DEFUN(AC_FUNC_CHECK, [indir([AC_CHECK_FUNC], $@)])dnl
AC_DEFUN(AC_HAVE_FUNCS, [indir([AC_CHECK_FUNCS], $@)])dnl
AC_DEFUN(AC_HAVE_HEADERS, [indir([AC_CHECK_HEADERS], $@)])dnl
AC_DEFUN(AC_SIZEOF_TYPE, [indir([AC_CHECK_SIZEOF], $@)])dnl
dnl
dnl Specific macros.
dnl
AC_DEFUN(AC_GCC_TRADITIONAL, [indir([AC_PROG_GCC_TRADITIONAL])])dnl
AC_DEFUN(AC_MINUS_C_MINUS_O, [indir([AC_PROG_CC_C_O])])dnl
AC_DEFUN(AC_SET_MAKE, [indir([AC_PROG_MAKE_SET])])dnl
AC_DEFUN(AC_YYTEXT_POINTER, [indir([AC_DECL_YYTEXT])])dnl
AC_DEFUN(AC_LN_S, [indir([AC_PROG_LN_S])])dnl
AC_DEFUN(AC_STDC_HEADERS, [indir([AC_HEADER_STDC])])dnl
AC_DEFUN(AC_MAJOR_HEADER, [indir([AC_HEADER_MAJOR])])dnl
AC_DEFUN(AC_STAT_MACROS_BROKEN, [indir([AC_HEADER_STAT])])dnl
AC_DEFUN(AC_SYS_SIGLIST_DECLARED, [indir([AC_DECL_SYS_SIGLIST])])dnl
AC_DEFUN(AC_GETGROUPS_T, [indir([AC_TYPE_GETGROUPS])])dnl
AC_DEFUN(AC_UID_T, [indir([AC_TYPE_UID_T])])dnl
AC_DEFUN(AC_SIZE_T, [indir([AC_TYPE_SIZE_T])])dnl
AC_DEFUN(AC_PID_T, [indir([AC_TYPE_PID_T])])dnl
AC_DEFUN(AC_OFF_T, [indir([AC_TYPE_OFF_T])])dnl
AC_DEFUN(AC_MODE_T, [indir([AC_TYPE_MODE_T])])dnl
AC_DEFUN(AC_RETSIGTYPE, [indir([AC_TYPE_SIGNAL])])dnl
AC_DEFUN(AC_MMAP, [indir([AC_FUNC_MMAP])])dnl
AC_DEFUN(AC_VPRINTF, [indir([AC_FUNC_VPRINTF])])dnl
AC_DEFUN(AC_VFORK, [indir([AC_FUNC_VFORK])])dnl
AC_DEFUN(AC_WAIT3, [indir([AC_FUNC_WAIT3])])dnl
AC_DEFUN(AC_ALLOCA, [indir([AC_FUNC_ALLOCA])])dnl
AC_DEFUN(AC_GETLOADAVG, [indir([AC_FUNC_GETLOADAVG])])dnl
AC_DEFUN(AC_UTIME_NULL, [indir([AC_FUNC_UTIME_NULL])])dnl
AC_DEFUN(AC_STRCOLL, [indir([AC_FUNC_STRCOLL])])dnl
AC_DEFUN(AC_SETVBUF_REVERSED, [indir([AC_FUNC_SETVBUF_REVERSED])])dnl
AC_DEFUN(AC_TIME_WITH_SYS_TIME, [indir([AC_HEADER_TIME])])dnl
AC_DEFUN(AC_TIMEZONE, [indir([AC_STRUCT_TIMEZONE])])dnl
AC_DEFUN(AC_ST_BLOCKS, [indir([AC_STRUCT_ST_BLOCKS])])dnl
AC_DEFUN(AC_ST_BLKSIZE, [indir([AC_STRUCT_ST_BLKSIZE])])dnl
AC_DEFUN(AC_ST_RDEV, [indir([AC_STRUCT_ST_RDEV])])dnl
AC_DEFUN(AC_CROSS_CHECK, [indir([AC_C_CROSS])])dnl
AC_DEFUN(AC_CHAR_UNSIGNED, [indir([AC_C_CHAR_UNSIGNED])])dnl
AC_DEFUN(AC_LONG_DOUBLE, [indir([AC_C_LONG_DOUBLE])])dnl
AC_DEFUN(AC_WORDS_BIGENDIAN, [indir([AC_C_BIGENDIAN])])dnl
AC_DEFUN(AC_INLINE, [indir([AC_C_INLINE])])dnl
AC_DEFUN(AC_CONST, [indir([AC_C_CONST])])dnl
AC_DEFUN(AC_LONG_FILE_NAMES, [indir([AC_SYS_LONG_FILE_NAMES])])dnl
AC_DEFUN(AC_RESTARTABLE_SYSCALLS, [indir([AC_SYS_RESTARTABLE_SYSCALLS])])dnl
AC_DEFUN(AC_FIND_X, [indir([AC_PATH_X])])dnl
AC_DEFUN(AC_FIND_XTRA, [indir([AC_PATH_XTRA])])dnl
File diff suppressed because it is too large. Load diff
-28
View File
@@ -1,28 +0,0 @@
dnl Driver that loads the Autoconf macro files.
dnl Requires GNU m4.
dnl This file is part of Autoconf.
dnl Copyright (C) 1994 Free Software Foundation, Inc.
dnl
dnl This program is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation; either version 2, or (at your option)
dnl any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with this program; if not, write to the Free Software
dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
dnl 02111-1307, USA.
dnl
dnl Written by David MacKenzie.
dnl
include(acgeneral.m4)dnl
builtin(include, acspecific.m4)dnl
builtin(include, acoldnames.m4)dnl
dnl Do not sinclude acsite.m4 here, because it may not be installed
dnl yet when Autoconf is frozen.
dnl Do not sinclude ./aclocal.m4 here, to prevent it from being frozen.
-159
View File
@@ -1,159 +0,0 @@
#! @SHELL@
# autoconf -- create `configure' using m4 macros
# Copyright (C) 1992, 1993, 1994, 1996 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# If given no args, create `configure' from template file `configure.in'.
# With one arg, create a configure script on standard output from
# the given template file.
usage="\
Usage: autoconf [-h] [--help] [-m dir] [--macrodir=dir]
[-l dir] [--localdir=dir] [--version] [template-file]"
# NLS nuisances.
# Only set these to C if already set. These must not be set unconditionally
# because not all systems understand e.g. LANG=C (notably SCO).
# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
# Non-C LC_CTYPE values break the ctype check.
if test "${LANG+set}" = set; then LANG=C; export LANG; fi
if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
if test "${LC_CTYPE+set}" = set; then LC_CTYPE=C; export LC_CTYPE; fi
: ${AC_MACRODIR=@datadir@}
: ${M4=@M4@}
: ${AWK=@AWK@}
case "${M4}" in
/*) # Handle the case that m4 has moved since we were configured.
# It may have been found originally in a build directory.
test -f "${M4}" || M4=m4 ;;
esac
: ${TMPDIR=/tmp}
tmpout=${TMPDIR}/acout.$$
localdir=
show_version=no
while test $# -gt 0 ; do
case "${1}" in
-h | --help | --h* )
echo "${usage}" 1>&2; exit 0 ;;
--localdir=* | --l*=* )
localdir="`echo \"${1}\" | sed -e 's/^[^=]*=//'`"
shift ;;
-l | --localdir | --l*)
shift
test $# -eq 0 && { echo "${usage}" 1>&2; exit 1; }
localdir="${1}"
shift ;;
--macrodir=* | --m*=* )
AC_MACRODIR="`echo \"${1}\" | sed -e 's/^[^=]*=//'`"
shift ;;
-m | --macrodir | --m* )
shift
test $# -eq 0 && { echo "${usage}" 1>&2; exit 1; }
AC_MACRODIR="${1}"
shift ;;
--version | --v* )
show_version=yes; shift ;;
-- ) # Stop option processing
shift; break ;;
- ) # Use stdin as input.
break ;;
-* )
echo "${usage}" 1>&2; exit 1 ;;
* )
break ;;
esac
done
if test $show_version = yes; then
version=`sed -n 's/define.AC_ACVERSION.[ ]*\([0-9.]*\).*/\1/p' \
$AC_MACRODIR/acgeneral.m4`
echo "Autoconf version $version"
exit 0
fi
case $# in
0) infile=configure.in ;;
1) infile="$1" ;;
*) echo "$usage" >&2; exit 1 ;;
esac
trap 'rm -f $tmpin $tmpout; exit 1' 1 2 15
tmpin=${TMPDIR}/acin.$$ # Always set this, to avoid bogus errors from some rm's.
if test z$infile = z-; then
infile=$tmpin
cat > $infile
elif test ! -r "$infile"; then
echo "autoconf: ${infile}: No such file or directory" >&2
exit 1
fi
if test -n "$localdir"; then
use_localdir="-I$localdir -DAC_LOCALDIR=$localdir"
else
use_localdir=
fi
# Use the frozen version of Autoconf if available.
r= f=
# Some non-GNU m4's don't reject the --help option, so give them /dev/null.
case `$M4 --help < /dev/null 2>&1` in
*reload-state*) test -r $AC_MACRODIR/autoconf.m4f && { r=--reload f=f; } ;;
*traditional*) ;;
*) echo Autoconf requires GNU m4 1.1 or later >&2; rm -f $tmpin; exit 1 ;;
esac
$M4 -I$AC_MACRODIR $use_localdir $r autoconf.m4$f $infile > $tmpout ||
{ rm -f $tmpin $tmpout; exit 2; }
# You could add your own prefixes to pattern if you wanted to check for
# them too, e.g. pattern='\(AC_\|ILT_\)', except that UNIX sed doesn't do
# alternation.
pattern="AC_"
status=0
if grep "^[^#]*${pattern}" $tmpout > /dev/null 2>&1; then
echo "autoconf: Undefined macros:" >&2
sed -n "s/^[^#]*\\(${pattern}[_A-Za-z0-9]*\\).*/\\1/p" $tmpout |
while read macro; do
grep -n "^[^#]*$macro" $infile /dev/null
test $? -eq 1 && echo >&2 "***BUG in Autoconf--please report*** $macro"
done | sort -u >&2
status=1
fi
if test $# -eq 0; then
exec 4> configure; chmod +x configure
else
exec 4>&1
fi
# Put the real line numbers into configure to make config.log more helpful.
$AWK '
/__oline__/ { printf "%d:", NR + 1 }
{ print }
' $tmpout | sed '
/__oline__/s/^\([0-9][0-9]*\):\(.*\)__oline__/\2\1/
' >&4
rm -f $tmpout
exit $status
+8 -10
View File
@@ -179,22 +179,20 @@ if test "$GNU_CC"; then
CFLAGS="$CFLAGS -fno-math-errno -pipe" CFLAGS="$CFLAGS -fno-math-errno -pipe"
CXXFLAGS="$CXXFLAGS -fno-exceptions -fno-math-errno -pipe" CXXFLAGS="$CXXFLAGS -fno-exceptions -fno-math-errno -pipe"
case "${host_cpu}" in if test "$CPU_ARCH" = "x86" -o "$CPU_ARCH" = "x86_64"; then
i*86) CFLAGS="$CFLAGS -msse2 -mfpmath=sse"
CFLAGS="$CFLAGS -msse2 -mfpmath=sse" CXXFLAGS="$CXXFLAGS -msse2 -mfpmath=sse"
CXXFLAGS="$CXXFLAGS -msse2 -mfpmath=sse" fi
;;
esac
if test -z "$CLANG_CC"; then if test -z "$CLANG_CC"; then
case "$CC_VERSION" in case "$CC_VERSION" in
4.* | 5.* | 6.* | 7.* | 8.*) 4.* | 5.* | 6.*)
AC_MSG_ERROR([Unsupported GCC version.]) AC_MSG_ERROR([Unsupported GCC version.])
;; ;;
*) *)
# Lifetime Dead Store Elimination level 2 (default in GCC) breaks Goanna. # Lifetime Dead Store Elimination level 2 (default in GCC6+) breaks Gecko.
# Instead of completely disabling this optimization, we force level 1 # Instead of completely disabling this optimization on newer GCC's,
# optimization instead with -flifetime-dse=1. # we'll force them to use level 1 optimization with -flifetime-dse=1.
# Add it first so that a mozconfig can override by setting CFLAGS/CXXFLAGS. # Add it first so that a mozconfig can override by setting CFLAGS/CXXFLAGS.
CFLAGS="-flifetime-dse=1 $CFLAGS" CFLAGS="-flifetime-dse=1 $CFLAGS"
CXXFLAGS="-flifetime-dse=1 $CXXFLAGS" CXXFLAGS="-flifetime-dse=1 $CXXFLAGS"
-3
View File
@@ -982,9 +982,6 @@ EOF
k1om:Linux:*:*) k1om:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-${LIBC} echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
exit ;; exit ;;
loongarch64:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
exit ;;
m32r*:Linux:*:*) m32r*:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-${LIBC} echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
exit ;; exit ;;
+3 -2
View File
@@ -28,7 +28,9 @@ if test -n "$USE_ICU"; then
fi fi
MOZ_ICU_VERSION="$version" MOZ_ICU_VERSION="$version"
ICU_DATA_FILE_BIG="icudt${version}b.dat" # TODO: the l is actually endian-dependent
# We could make this set as 'l' or 'b' for little or big, respectively,
# but we'd need to check in a big-endian version of the file.
ICU_DATA_FILE="icudt${version}l.dat" ICU_DATA_FILE="icudt${version}l.dat"
dnl We won't build ICU data as a separate file when building dnl We won't build ICU data as a separate file when building
@@ -44,7 +46,6 @@ fi
AC_SUBST(MOZ_ICU_VERSION) AC_SUBST(MOZ_ICU_VERSION)
AC_SUBST(USE_ICU) AC_SUBST(USE_ICU)
AC_SUBST(ICU_DATA_FILE_BIG)
AC_SUBST(ICU_DATA_FILE) AC_SUBST(ICU_DATA_FILE)
AC_SUBST(MOZ_ICU_DATA_ARCHIVE) AC_SUBST(MOZ_ICU_DATA_ARCHIVE)
AC_SUBST(MOZ_SHARED_ICU) AC_SUBST(MOZ_SHARED_ICU)
+4 -4
View File
@@ -34,7 +34,7 @@ def symlink(source, link_name):
def check_run(args): def check_run(args):
global DEBUG global DEBUG
if DEBUG: if DEBUG:
print(' '.join(args), file=sys.stderr) print >> sys.stderr, ' '.join(args)
r = subprocess.call(args) r = subprocess.call(args)
assert r == 0 assert r == 0
@@ -43,11 +43,11 @@ def run_in(path, args):
d = os.getcwd() d = os.getcwd()
global DEBUG global DEBUG
if DEBUG: if DEBUG:
print('cd "%s"' % path, file=sys.stderr) print >> sys.stderr, 'cd "%s"' % path
os.chdir(path) os.chdir(path)
check_run(args) check_run(args)
if DEBUG: if DEBUG:
print('cd "%s"' % d, file=sys.stderr) print >> sys.stderr, 'cd "%s"' % d
os.chdir(d) os.chdir(d)
@@ -377,7 +377,7 @@ if __name__ == "__main__":
extra_cflags2 = ["-fPIC"] extra_cflags2 = ["-fPIC"]
extra_cxxflags2 = ["-fPIC", "-static-libstdc++"] extra_cxxflags2 = ["-fPIC", "-static-libstdc++"]
if 'LD_LIBRARY_PATH' in os.environ: if os.environ.has_key('LD_LIBRARY_PATH'):
os.environ['LD_LIBRARY_PATH'] = '%s/lib64/:%s' % (gcc_dir, os.environ['LD_LIBRARY_PATH']); os.environ['LD_LIBRARY_PATH'] = '%s/lib64/:%s' % (gcc_dir, os.environ['LD_LIBRARY_PATH']);
else: else:
os.environ['LD_LIBRARY_PATH'] = '%s/lib64/' % gcc_dir os.environ['LD_LIBRARY_PATH'] = '%s/lib64/' % gcc_dir
+3 -3
View File
@@ -81,9 +81,9 @@ def process_files(files, output_filename, digests, strip):
short_file = short_file.lstrip('/') short_file = short_file.lstrip('/')
else: else:
short_file = file short_file = file
print('%s %s %s %s' % (hash, digest, print >>output, '%s %s %s %s' % (hash, digest,
os.path.getsize(file), os.path.getsize(file),
short_file), file=output) short_file)
def setup_logging(level=logging.DEBUG): def setup_logging(level=logging.DEBUG):
'''This function sets up the logging module using a speficiable logging '''This function sets up the logging module using a speficiable logging
@@ -140,7 +140,7 @@ def main():
try: try:
for digest in options.digests: for digest in options.digests:
hashlib.new(digest) hashlib.new(digest)
except ValueError as ve: except ValueError, ve:
logger.error('Could not create a "%s" hash object (%s)' % logger.error('Could not create a "%s" hash object (%s)' %
(digest, ve.args[0])) (digest, ve.args[0]))
exit(1) exit(1)
+7
View File
@@ -33,3 +33,10 @@ endif
# correctly. Note that the binary produced here is a host tool and doesn't need # correctly. Note that the binary produced here is a host tool and doesn't need
# to be distributed. # to be distributed.
MACOSX_DEPLOYMENT_TARGET := MACOSX_DEPLOYMENT_TARGET :=
# Temporarily relax the requirements for libstdc++ symbol versions on static
# analysis plugin in order to use a recent clang by accepting libstdc++ from
# gcc 4.4.0 (GLIBCXX_3.4.11).
ifdef CHECK_STDCXX
CHECK_STDCXX = $(call CHECK_SYMBOLS,$(1),GLIBCXX,libstdc++,v[1] > 3 || (v[1] == 3 && v[2] == 4 && v[3] > 11))
endif
@@ -11,7 +11,7 @@ import logging
import os import os
import site import site
import sys import sys
import urllib.request, urllib.error, urllib.parse import urllib2
import difflib import difflib
FAILURE_CODE = 1 FAILURE_CODE = 1
@@ -40,10 +40,10 @@ def make_hg_url(hgHost, repoPath, protocol='https', revision=None,
def readConfig(configfile, keys=[], required=[]): def readConfig(configfile, keys=[], required=[]):
c = {} c = {}
exec(compile(open(configfile, "rb").read(), configfile, 'exec'), c) execfile(configfile, c)
for k in keys: for k in keys:
c = c[k] c = c[k]
items = list(c.keys()) items = c.keys()
err = False err = False
for key in required: for key in required:
if key not in items: if key not in items:
@@ -126,7 +126,7 @@ def get_mozconfig(path, options):
else: else:
url = make_hg_url(options.hghost, options.branch, 'http', url = make_hg_url(options.hghost, options.branch, 'http',
options.revision, path) options.revision, path)
return urllib.request.urlopen(url).readlines() return urllib2.urlopen(url).readlines()
if __name__ == '__main__': if __name__ == '__main__':
from optparse import OptionParser from optparse import OptionParser
+4
View File
@@ -43,6 +43,8 @@ gyp_vars.update({
'arm_neon': 0, 'arm_neon': 0,
'arm_neon_optional': 1, 'arm_neon_optional': 1,
'moz_webrtc_omx': 0,
'moz_webrtc_mediacodec': 0,
# Turn off multi monitor screen share # Turn off multi monitor screen share
'multi_monitor_screenshare%' : 0, 'multi_monitor_screenshare%' : 0,
@@ -71,6 +73,8 @@ if CONFIG['ARM_ARCH']:
if int(CONFIG['ARM_ARCH']) < 7: if int(CONFIG['ARM_ARCH']) < 7:
gyp_vars['armv7'] = 0 gyp_vars['armv7'] = 0
gyp_vars['arm_neon_optional'] = 0 gyp_vars['arm_neon_optional'] = 0
elif os == 'Android':
gyp_vars['armv7'] = 1
else: else:
# CPU detection for ARM works on Android only. armv7 always uses CPU # CPU detection for ARM works on Android only. armv7 always uses CPU
# detection, so we have to set armv7=0 for non-Android target # detection, so we have to set armv7=0 for non-Android target
+1 -1
View File
@@ -18,7 +18,7 @@ flavors = {
'Linux': 'linux', 'Linux': 'linux',
'Darwin': 'mac', 'Darwin': 'mac',
'SunOS': 'solaris', 'SunOS': 'solaris',
'kFreeBSD': 'freebsd', 'GNU/kFreeBSD': 'freebsd',
'DragonFly': 'dragonfly', 'DragonFly': 'dragonfly',
'FreeBSD': 'freebsd', 'FreeBSD': 'freebsd',
'NetBSD': 'netbsd', 'NetBSD': 'netbsd',
+9 -14
View File
@@ -12,7 +12,7 @@ import random
import subprocess import subprocess
import sys import sys
import uuid import uuid
import builtins import __builtin__
from types import ModuleType from types import ModuleType
@@ -170,16 +170,11 @@ def bootstrap(topsrcdir, mozilla_dir=None):
if mozilla_dir is None: if mozilla_dir is None:
mozilla_dir = topsrcdir mozilla_dir = topsrcdir
# Ensure we are not running Python 2. # Ensure we are running Python 2.7+. We put this check here so we generate a
# We put this check here so we generate a user-friendly error message # user-friendly error message rather than a cryptic stack trace on module
# rather than a cryptic stack trace on module import. # import.
if sys.version_info[0] < 3 or sys.version_info[1] < 3: if sys.version_info[0] != 2 or sys.version_info[1] < 7:
print('Python 3.3 or above is required to run mach.') print('Python 2.7 or above (but not Python 3) is required to run mach.')
print('You are running Python', platform.python_version())
sys.exit(1)
# This sanity check is overkill, but why not?
if sys.version_info[0] > 3:
print('Python 4.x or higher not supported. Use Python 3 instead.')
print('You are running Python', platform.python_version()) print('You are running Python', platform.python_version())
sys.exit(1) sys.exit(1)
@@ -340,7 +335,7 @@ def bootstrap(topsrcdir, mozilla_dir=None):
# always load local repository configuration # always load local repository configuration
mach.settings_paths.append(mozilla_dir) mach.settings_paths.append(mozilla_dir)
for category, meta in list(CATEGORIES.items()): for category, meta in CATEGORIES.items():
mach.define_category(category, meta['short'], meta['long'], mach.define_category(category, meta['short'], meta['long'],
meta['priority']) meta['priority'])
@@ -365,7 +360,7 @@ class ImportHook(object):
self._modules = set() self._modules = set()
def __call__(self, name, globals=None, locals=None, fromlist=None, def __call__(self, name, globals=None, locals=None, fromlist=None,
level=0): level=-1):
# name might be a relative import. Instead of figuring out what that # name might be a relative import. Instead of figuring out what that
# resolves to, which is complex, just rely on the real import. # resolves to, which is complex, just rely on the real import.
# Since we don't know the full module name, we can't check sys.modules, # Since we don't know the full module name, we can't check sys.modules,
@@ -414,4 +409,4 @@ class ImportHook(object):
# Install our hook # Install our hook
builtins.__import__ = ImportHook(builtins.__import__) __builtin__.__import__ = ImportHook(__builtin__.__import__)
+1 -1
View File
@@ -11,7 +11,7 @@
# _declare_exceptions template, and add it to the return statement. Then # _declare_exceptions template, and add it to the return statement. Then
# destructure in the assignment below the function declaration. # destructure in the assignment below the function declaration.
@template @template
@imports(_from='builtins', _import='Exception') @imports(_from='__builtin__', _import='Exception')
def _declare_exceptions(): def _declare_exceptions():
class FatalCheckError(Exception): class FatalCheckError(Exception):
'''An exception to throw from a function decorated with @checking. '''An exception to throw from a function decorated with @checking.
+16 -36
View File
@@ -133,8 +133,7 @@ option(env='PYTHON', nargs=1, help='Python interpreter')
@imports(_from='mozbuild.configure.util', _import='LineIO') @imports(_from='mozbuild.configure.util', _import='LineIO')
@imports(_from='mozbuild.virtualenv', _import='VirtualenvManager') @imports(_from='mozbuild.virtualenv', _import='VirtualenvManager')
@imports(_from='mozbuild.virtualenv', _import='verify_python_version') @imports(_from='mozbuild.virtualenv', _import='verify_python_version')
@imports(_from='mozpack.path', _import='normsep') @imports('distutils.sysconfig')
@imports('sysconfig')
def virtualenv_python(env_python, build_env, mozconfig, help): def virtualenv_python(env_python, build_env, mozconfig, help):
if help: if help:
return return
@@ -166,9 +165,6 @@ def virtualenv_python(env_python, build_env, mozconfig, help):
os.path.join(topobjdir, '_virtualenv'), out, os.path.join(topobjdir, '_virtualenv'), out,
os.path.join(topsrcdir, 'build', 'virtualenv_packages.txt')) os.path.join(topsrcdir, 'build', 'virtualenv_packages.txt'))
if normsep(sys.executable) == normsep(manager.python_path):
return normsep(manager.python_path)
if python: if python:
# If we're not in the virtualenv, we need the which module for # If we're not in the virtualenv, we need the which module for
# find_program. # find_program.
@@ -197,10 +193,10 @@ def virtualenv_python(env_python, build_env, mozconfig, help):
sys.exit(subprocess.call([python] + sys.argv)) sys.exit(subprocess.call([python] + sys.argv))
# We are now in the virtualenv # We are now in the virtualenv
if not sysconfig.get_path("purelib"): if not distutils.sysconfig.get_python_lib():
die('Could not determine python site packages directory') die('Could not determine python site packages directory')
return normsep(python) return python
set_config('PYTHON', virtualenv_python) set_config('PYTHON', virtualenv_python)
add_old_configure_assignment('PYTHON', virtualenv_python) add_old_configure_assignment('PYTHON', virtualenv_python)
@@ -216,7 +212,7 @@ def early_options():
def early_options(): def early_options():
return set( return set(
option.env option.env
for option in __sandbox__._options.values() for option in __sandbox__._options.itervalues()
if option.env if option.env
) )
return early_options return early_options
@@ -244,17 +240,17 @@ def mozconfig_options(mozconfig, help):
log.info(' %s' % arg) log.info(' %s' % arg)
helper.add(arg, origin='mozconfig', args=helper._args) helper.add(arg, origin='mozconfig', args=helper._args)
for key, value in mozconfig['env']['added'].items(): for key, value in mozconfig['env']['added'].iteritems():
add(key, value) add(key, value)
os.environ[key] = value os.environ[key] = value
for key, (_, value) in mozconfig['env']['modified'].items(): for key, (_, value) in mozconfig['env']['modified'].iteritems():
add(key, value) add(key, value)
os.environ[key] = value os.environ[key] = value
for key, value in mozconfig['vars']['added'].items(): for key, value in mozconfig['vars']['added'].iteritems():
# mozconfig_loader adds _IS_SET variables that are irrelevant # mozconfig_loader adds _IS_SET variables that are irrelevant
if not key.endswith('_IS_SET'): if not key.endswith('_IS_SET'):
add(key, value) add(key, value)
for key, (_, value) in mozconfig['vars']['modified'].items(): for key, (_, value) in mozconfig['vars']['modified'].iteritems():
add(key, value) add(key, value)
@@ -294,7 +290,6 @@ option('--target', nargs=1,
@imports(_from='mozbuild.configure.constants', _import='Endianness') @imports(_from='mozbuild.configure.constants', _import='Endianness')
@imports(_from='mozbuild.configure.constants', _import='Kernel') @imports(_from='mozbuild.configure.constants', _import='Kernel')
@imports(_from='mozbuild.configure.constants', _import='OS') @imports(_from='mozbuild.configure.constants', _import='OS')
@imports(_from='mozbuild.configure.constants', _import='OS_and_Kernel')
def split_triplet(triplet): def split_triplet(triplet):
# The standard triplet is defined as # The standard triplet is defined as
# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
@@ -344,7 +339,7 @@ def split_triplet(triplet):
if cpu.endswith('86') or (cpu.startswith('i') and '86' in cpu): if cpu.endswith('86') or (cpu.startswith('i') and '86' in cpu):
canonical_cpu = 'x86' canonical_cpu = 'x86'
endianness = 'little' endianness = 'little'
elif cpu == 'x86_64': elif cpu in ('x86_64', 'ia64'):
canonical_cpu = cpu canonical_cpu = cpu
endianness = 'little' endianness = 'little'
elif cpu in ('s390', 's390x'): elif cpu in ('s390', 's390x'):
@@ -380,9 +375,6 @@ def split_triplet(triplet):
elif cpu.startswith('aarch64'): elif cpu.startswith('aarch64'):
canonical_cpu = 'aarch64' canonical_cpu = 'aarch64'
endianness = 'little' endianness = 'little'
elif cpu.startswith('loongarch64'):
canonical_cpu = 'loongarch64'
endianness = 'little'
else: else:
die('Unknown CPU type: %s' % cpu) die('Unknown CPU type: %s' % cpu)
@@ -390,8 +382,8 @@ def split_triplet(triplet):
alias=triplet, alias=triplet,
cpu=CPU(canonical_cpu), cpu=CPU(canonical_cpu),
bitness=CPU_bitness[canonical_cpu], bitness=CPU_bitness[canonical_cpu],
kernel=OS_and_Kernel(canonical_kernel), kernel=Kernel(canonical_kernel),
os=OS_and_Kernel(canonical_os), os=OS(canonical_os),
endianness=Endianness(endianness), endianness=Endianness(endianness),
raw_cpu=cpu, raw_cpu=cpu,
raw_os=os, raw_os=os,
@@ -405,8 +397,7 @@ def split_triplet(triplet):
def config_sub(shell, triplet): def config_sub(shell, triplet):
config_sub = os.path.join(os.path.dirname(__file__), '..', config_sub = os.path.join(os.path.dirname(__file__), '..',
'autoconf', 'config.sub') 'autoconf', 'config.sub')
return subprocess.check_output([shell, config_sub, triplet], return subprocess.check_output([shell, config_sub, triplet]).strip()
universal_newlines=True).strip()
@depends('--host', shell) @depends('--host', shell)
@@ -416,8 +407,7 @@ def host(value, shell):
if not value: if not value:
config_guess = os.path.join(os.path.dirname(__file__), '..', config_guess = os.path.join(os.path.dirname(__file__), '..',
'autoconf', 'config.guess') 'autoconf', 'config.guess')
host = subprocess.check_output([shell, config_guess], host = subprocess.check_output([shell, config_guess]).strip()
universal_newlines=True).strip()
else: else:
host = value[0] host = value[0]
@@ -509,14 +499,6 @@ set_config('INTEL_ARCHITECTURE', delayed_getattr(target_variables,
'INTEL_ARCHITECTURE')) 'INTEL_ARCHITECTURE'))
set_config('TARGET_CPU', delayed_getattr(target, 'raw_cpu')) set_config('TARGET_CPU', delayed_getattr(target, 'raw_cpu'))
set_config('TARGET_OS', delayed_getattr(target, 'raw_os')) set_config('TARGET_OS', delayed_getattr(target, 'raw_os'))
set_config('TARGET_ENDIANNESS', delayed_getattr(target, 'endianness'))
@depends(target)
def target_is_big_endian(target):
if target.endianness == 'big':
return True
set_define('TARGET_ENDIAN_BIG', target_is_big_endian)
@depends(host) @depends(host)
@@ -609,9 +591,7 @@ imply_option('--enable-project', application)
@depends(check_build_environment, '--help') @depends(check_build_environment, '--help')
def default_project(build_env, help): def default_project(build_env, help):
if build_env.topobjdir.endswith('/js/src'): return 'js'
return 'js'
return 'xulrunner'
option('--enable-project', nargs=1, default=default_project, option('--enable-project', nargs=1, default=default_project,
help='Project to build') help='Project to build')
@@ -658,7 +638,7 @@ def build_project(noncomm_build, project, external_source_dir, build_env, help):
build_app = project[0] build_app = project[0]
if not external_source_dir and build_app not in ('xulrunner', 'js'): if not external_source_dir and build_app not in ('js'):
if noncomm_build: if noncomm_build:
log.info("=====WARNING WARNING WARNING=====") log.info("=====WARNING WARNING WARNING=====")
log.info("UNSUPPORTED NONCOMM-BUILD: Application code SHOULD NOT be put inside the platform tree, and doing so may have unforseen consequences if/when platform code is changed.") log.info("UNSUPPORTED NONCOMM-BUILD: Application code SHOULD NOT be put inside the platform tree, and doing so may have unforseen consequences if/when platform code is changed.")
@@ -768,7 +748,7 @@ def enabled_in_nightly(milestone, _):
def all_configure_options(_): def all_configure_options(_):
result = [] result = []
previous = None previous = None
for option in __sandbox__._options.values(): for option in __sandbox__._options.itervalues():
# __sandbox__._options contains items for both option.name and # __sandbox__._options contains items for both option.name and
# option.env. But it's also an OrderedDict, meaning both are # option.env. But it's also an OrderedDict, meaning both are
# consecutive. # consecutive.
+2 -34
View File
@@ -11,14 +11,9 @@ def moz_jemalloc4(value):
option('--enable-jemalloc', env='MOZ_MEMORY', option('--enable-jemalloc', env='MOZ_MEMORY',
help='Replace system memory allocator with jemalloc') help='Replace system memory allocator with jemalloc')
option('--enable-mimalloc',
help='Replace system memory allocator with mimalloc')
@depends('--enable-jemalloc', '--enable-mimalloc', target, build_project, @depends('--enable-jemalloc', target, build_project, c_compiler)
c_compiler) def jemalloc(value, target, build_project, c_compiler):
def jemalloc(value, mimalloc, target, build_project, c_compiler):
if value and mimalloc:
die('--enable-jemalloc and --enable-mimalloc cannot be used together')
if value.origin != 'default': if value.origin != 'default':
return bool(value) or None return bool(value) or None
@@ -35,38 +30,11 @@ def jemalloc(value, mimalloc, target, build_project, c_compiler):
if target.kernel == 'Linux': if target.kernel == 'Linux':
return True return True
@depends('--enable-mimalloc', '--enable-jemalloc', target)
def mimalloc(value, jemalloc, target):
if value and jemalloc:
die('--enable-jemalloc and --enable-mimalloc cannot be used together')
if value.origin != 'default':
if not value:
return None
if target.kernel not in ('Darwin', 'WINNT', 'Linux', 'kFreeBSD', 'FreeBSD',
'NetBSD', 'OpenBSD', 'DragonFly'):
die('--enable-mimalloc is not supported on %s', target.kernel)
return True
@depends('--enable-mimalloc', '--enable-jemalloc')
def mimalloc_requires_disable(mimalloc, jemalloc):
if not mimalloc:
return
if jemalloc or jemalloc.origin not in ('command-line', 'mozconfig'):
die('--enable-mimalloc requires --disable-jemalloc to be passed explicitly')
set_config('MOZ_MEMORY', jemalloc) set_config('MOZ_MEMORY', jemalloc)
set_define('MOZ_MEMORY', jemalloc) set_define('MOZ_MEMORY', jemalloc)
add_old_configure_assignment('MOZ_MEMORY', jemalloc) add_old_configure_assignment('MOZ_MEMORY', jemalloc)
@depends(mimalloc)
def mimalloc_config(mimalloc):
return True if mimalloc else False
set_config('MOZ_MIMALLOC', mimalloc_config)
set_define('MOZ_MIMALLOC', mimalloc)
add_old_configure_assignment('MOZ_MIMALLOC', mimalloc_config)
# Because --enable-jemalloc doesn't use a default because of the dependency # Because --enable-jemalloc doesn't use a default because of the dependency
# on the target, we can't use a js_option for it to propagate to js/src # on the target, we can't use a js_option for it to propagate to js/src
+74 -36
View File
@@ -3,31 +3,74 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this # License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
m4 = check_prog( @imports('codecs')
"M4", @imports('sys')
( def encoded_open(path, mode):
"gm4", encoding = 'mbcs' if sys.platform == 'win32' else 'utf-8'
"m4", return codecs.open(path, mode, encoding)
),
)
@depends('OLD_CONFIGURE', mozconfig, awk, m4, check_build_environment, shell,
option(env='AUTOCONF', nargs=1, help='Path to autoconf 2.13')
@depends(mozconfig, 'AUTOCONF')
@checking('for autoconf')
@imports(_from='os.path', _import='exists')
@imports('re')
def autoconf(mozconfig, autoconf):
mozconfig_autoconf = None
if mozconfig['path']:
make_extra = mozconfig['make_extra']
if make_extra:
for assignment in make_extra:
m = re.match('(?:export\s+)?AUTOCONF\s*:?=\s*(.+)$',
assignment)
if m:
mozconfig_autoconf = m.group(1)
autoconf = autoconf[0] if autoconf else None
for ac in (mozconfig_autoconf, autoconf, 'autoconf-2.13', 'autoconf2.13',
'autoconf213'):
if ac:
autoconf = find_program(ac)
if autoconf:
break
else:
fink = find_program('fink')
if fink:
autoconf = os.path.normpath(os.path.join(
fink, '..', '..', 'lib', 'autoconf2.13', 'bin', 'autoconf'))
else:
brew = find_program('brew')
if brew:
autoconf = os.path.normpath(os.path.join(
brew, '..', '..', 'Cellar', 'autoconf213', '2.13', 'bin',
'autoconf213'))
if not autoconf:
die('Could not find autoconf 2.13')
if not exists(autoconf):
die('Could not find autoconf 2.13 at %s', autoconf)
return autoconf
set_config('AUTOCONF', autoconf)
@depends('OLD_CONFIGURE', mozconfig, autoconf, check_build_environment, shell,
old_configure_assignments, build_project) old_configure_assignments, build_project)
@imports(_from='__builtin__', _import='open') @imports(_from='__builtin__', _import='open')
@imports(_from='__builtin__', _import='print') @imports(_from='__builtin__', _import='print')
@imports('glob') @imports('glob')
@imports('sys')
@imports('itertools') @imports('itertools')
@imports('subprocess') @imports('subprocess')
# Import getmtime without overwriting the sandbox os.path. # Import getmtime without overwriting the sandbox os.path.
@imports(_from='os.path', _import='getmtime') @imports(_from='os.path', _import='getmtime')
@imports(_from='os.path', _import='exists') @imports(_from='os.path', _import='exists')
@imports(_from='mozbuild.shellutil', _import='quote') @imports(_from='mozbuild.shellutil', _import='quote')
@imports(_from='os', _import='environ') def prepare_configure(old_configure, mozconfig, autoconf, build_env, shell,
@imports(_from='mozbuild.getencoding', _import='getencoding')
def prepare_configure(old_configure, mozconfig, awk, m4, build_env, shell,
old_configure_assignments, build_project): old_configure_assignments, build_project):
encoding = getencoding()
# os.path.abspath in the sandbox will ensure forward slashes on Windows, # os.path.abspath in the sandbox will ensure forward slashes on Windows,
# which is actually necessary because this path actually ends up literally # which is actually necessary because this path actually ends up literally
# as $0, and backslashes there breaks autoconf's detection of the source # as $0, and backslashes there breaks autoconf's detection of the source
@@ -38,6 +81,7 @@ def prepare_configure(old_configure, mozconfig, awk, m4, build_env, shell,
if not old_configure_dir.endswith('/js/src'): if not old_configure_dir.endswith('/js/src'):
old_configure = os.path.join(old_configure_dir, 'js', 'src', old_configure = os.path.join(old_configure_dir, 'js', 'src',
os.path.basename(old_configure)) os.path.basename(old_configure))
refresh = True refresh = True
if exists(old_configure): if exists(old_configure):
mtime = getmtime(old_configure) mtime = getmtime(old_configure)
@@ -54,28 +98,21 @@ def prepare_configure(old_configure, mozconfig, awk, m4, build_env, shell,
refresh = False refresh = False
if refresh: if refresh:
autoconf = os.path.join(build_env.topsrcdir, 'build', 'autoconf', 'autoconf.sh')
log.info('Refreshing %s with %s', old_configure, autoconf) log.info('Refreshing %s with %s', old_configure, autoconf)
env = dict(environ)
env['M4'] = m4
env['AWK'] = awk
env['AC_MACRODIR'] = os.path.join(build_env.topsrcdir, 'build', 'autoconf')
my_env = env
script = subprocess.check_output([ script = subprocess.check_output([
shell, autoconf, shell, autoconf,
'--localdir=%s' % os.path.dirname(old_configure), '--localdir=%s' % os.path.dirname(old_configure),
old_configure + '.in'], env=my_env) old_configure + '.in'])
script = script.decode(encoding, errors='replace')
# Make old-configure append to config.log, where we put our own log. # Make old-configure append to config.log, where we put our own log.
# This could be done with a m4 macro, but it's way easier this way # This could be done with a m4 macro, but it's way easier this way
script = script.replace('>./config.log', '>>./config.log') script = script.replace('>./config.log', '>>./config.log')
with open(old_configure, 'w', encoding=encoding, errors='replace') as fh: with open(old_configure, 'wb') as fh:
fh.write(script) fh.write(script)
cmd = [shell, old_configure] cmd = [shell, old_configure]
with open('old-configure.vars', 'w', encoding=encoding, errors='replace') as out: with encoded_open('old-configure.vars', 'w') as out:
log.debug('Injecting the following to old-configure:') log.debug('Injecting the following to old-configure:')
def inject(command): def inject(command):
print(command, file=out) print(command, file=out)
@@ -90,6 +127,10 @@ def prepare_configure(old_configure, mozconfig, awk, m4, build_env, shell,
for key in mozconfig[t]['removed'].keys(): for key in mozconfig[t]['removed'].keys():
inject("unset %s" % key) inject("unset %s" % key)
# Autoconf is special, because it might be passed from
# mozconfig['make_extra'], which we don't pass automatically above.
inject('export AUTOCONF=%s' % quote(autoconf))
for assignment in old_configure_assignments: for assignment in old_configure_assignments:
inject(assignment) inject(assignment)
@@ -117,6 +158,7 @@ def old_configure_options(*options):
'--enable-alsa', '--enable-alsa',
'--enable-appcompat-guid', '--enable-appcompat-guid',
'--enable-av1', '--enable-av1',
'--enable-jxl',
'--enable-b2g-bt', '--enable-b2g-bt',
'--enable-b2g-camera', '--enable-b2g-camera',
'--enable-b2g-ril', '--enable-b2g-ril',
@@ -142,7 +184,10 @@ def old_configure_options(*options):
'--enable-faststripe', '--enable-faststripe',
'--enable-feeds', '--enable-feeds',
'--enable-gamepad', '--enable-gamepad',
'--enable-gconf',
'--enable-gczeal', '--enable-gczeal',
'--enable-gio',
'--enable-gnomeui',
'--enable-gold', '--enable-gold',
'--enable-hardware-aec-ns', '--enable-hardware-aec-ns',
'--enable-icf', '--enable-icf',
@@ -152,7 +197,6 @@ def old_configure_options(*options):
'--enable-jitspew', '--enable-jitspew',
'--enable-js-lto', '--enable-js-lto',
'--enable-leak-sanitizer', '--enable-leak-sanitizer',
'--enable-libaom',
'--enable-libjpeg-turbo', '--enable-libjpeg-turbo',
'--enable-libproxy', '--enable-libproxy',
'--enable-llvm-hacks', '--enable-llvm-hacks',
@@ -163,8 +207,6 @@ def old_configure_options(*options):
'--enable-necko-wifi', '--enable-necko-wifi',
'--enable-negotiateauth', '--enable-negotiateauth',
'--enable-nfc', '--enable-nfc',
'--enable-npapi',
'--enable-npapi-gtk2',
'--enable-nspr-build', '--enable-nspr-build',
'--enable-official-branding', '--enable-official-branding',
'--enable-official-vendor', '--enable-official-vendor',
@@ -193,6 +235,7 @@ def old_configure_options(*options):
'--enable-small-chunk-size', '--enable-small-chunk-size',
'--enable-startup-notification', '--enable-startup-notification',
'--enable-startupcache', '--enable-startupcache',
'--enable-stdcxx-compat',
'--enable-strip', '--enable-strip',
'--enable-synth-pico', '--enable-synth-pico',
'--enable-system-cairo', '--enable-system-cairo',
@@ -256,7 +299,6 @@ def old_configure_options(*options):
'--with-thumb-interwork', '--with-thumb-interwork',
'--with-unify-dist', '--with-unify-dist',
'--with-user-appdir', '--with-user-appdir',
'--with-xulrunner-stub-name',
'--x-includes', '--x-includes',
'--x-libraries', '--x-libraries',
@@ -269,7 +311,6 @@ def old_configure_options(*options):
'--enable-incomplete-external-linkage', '--enable-incomplete-external-linkage',
'--enable-mailnews', '--enable-mailnews',
'--enable-mailnews-oauth2', '--enable-mailnews-oauth2',
'--enable-classic-account-wizard',
# Below are configure flags used by Pale Moon # Below are configure flags used by Pale Moon
'--disable-browser-statusbar', '--disable-browser-statusbar',
@@ -286,11 +327,8 @@ def old_configure_options(*options):
@imports('subprocess') @imports('subprocess')
@imports('sys') @imports('sys')
@imports(_from='mozbuild.shellutil', _import='quote') @imports(_from='mozbuild.shellutil', _import='quote')
@imports(_from='mozbuild.util', _import='exec_')
@imports(_from='mozbuild.getencoding', _import='getencoding')
def old_configure(prepare_configure, extra_old_configure_args, all_options, def old_configure(prepare_configure, extra_old_configure_args, all_options,
*options): *options):
encoding = getencoding()
cmd = prepare_configure cmd = prepare_configure
# old-configure only supports the options listed in @old_configure_options # old-configure only supports the options listed in @old_configure_options
@@ -327,7 +365,7 @@ def old_configure(prepare_configure, extra_old_configure_args, all_options,
ret = subprocess.call(cmd) ret = subprocess.call(cmd)
if ret: if ret:
with log.queue_debug(): with log.queue_debug():
with open('config.log', 'r', encoding=encoding, errors='replace') as fh: with encoded_open('config.log', 'r') as fh:
fh.seek(log_size) fh.seek(log_size)
for line in fh: for line in fh:
log.debug(line.rstrip()) log.debug(line.rstrip())
@@ -335,12 +373,12 @@ def old_configure(prepare_configure, extra_old_configure_args, all_options,
sys.exit(ret) sys.exit(ret)
raw_config = {} raw_config = {}
with open('config.data', 'r', encoding=encoding, errors='replace') as fh: with encoded_open('config.data', 'r') as fh:
code = compile(fh.read(), 'config.data', 'exec') code = compile(fh.read(), 'config.data', 'exec')
# Every variation of the exec() function I tried led to: # Every variation of the exec() function I tried led to:
# SyntaxError: unqualified exec is not allowed in function 'main' it # SyntaxError: unqualified exec is not allowed in function 'main' it
# contains a nested function with free variables # contains a nested function with free variables
exec_(code, raw_config) exec code in raw_config
# Ensure all the flags known to old-configure appear in the # Ensure all the flags known to old-configure appear in the
# @old_configure_options above. # @old_configure_options above.
@@ -374,9 +412,9 @@ def set_old_configure_define(name, value):
def post_old_configure(raw_config): def post_old_configure(raw_config):
for k, v in raw_config['substs']: for k, v in raw_config['substs']:
set_old_configure_config( set_old_configure_config(
k[1:-1], v[1:-1] if isinstance(v, str) else v) k[1:-1], v[1:-1] if isinstance(v, types.StringTypes) else v)
for k, v in dict(raw_config['defines']).items(): for k, v in dict(raw_config['defines']).iteritems():
set_old_configure_define(k[1:-1], v[1:-1]) set_old_configure_define(k[1:-1], v[1:-1])
set_old_configure_config('non_global_defines', set_old_configure_config('non_global_defines',
+8 -47
View File
@@ -61,44 +61,6 @@ set_config('HAVE_YASM', have_yasm)
# Until the YASM variable is not necessary in old-configure. # Until the YASM variable is not necessary in old-configure.
add_old_configure_assignment('YASM', have_yasm) add_old_configure_assignment('YASM', have_yasm)
# nasm detection
# ==============================================================
nasm = check_prog('NASM', ['nasm'], allow_missing=True)
@depends_if(nasm)
@checking('nasm version')
def nasm_version(nasm):
version = check_cmd_output(
nasm, '-v',
onerror=lambda: die('Failed to get nasm version.')
).splitlines()[0].split()[2]
return Version(version)
@depends(nasm, nasm_version)
def have_nasm(nasm, version):
if nasm and version >= Version('2.14'):
return True
set_config('HAVE_NASM', have_nasm)
@depends(have_nasm, target)
def nasm_asflags(have_nasm, target):
if have_nasm:
asflags = {
('OSX', 'x86'): '-f macho32',
('OSX', 'x86_64'): '-f macho64',
('WINNT', 'x86'): '-f win32',
('WINNT', 'x86_64'): '-f win64',
}.get((target.os, target.cpu), None)
if asflags is None:
if target.cpu == 'x86':
asflags = '-f elf32'
elif target.cpu == 'x86_64':
asflags = '-f elf64'
return asflags
set_config('NASM_ASFLAGS', nasm_asflags)
# MacOS deployment target version # MacOS deployment target version
# ============================================================== # ==============================================================
# This needs to happen before any compilation test is done. # This needs to happen before any compilation test is done.
@@ -274,7 +236,7 @@ def get_compiler_info(compiler, language):
('CPU', CPU_preprocessor_checks), ('CPU', CPU_preprocessor_checks),
('KERNEL', kernel_preprocessor_checks), ('KERNEL', kernel_preprocessor_checks),
): ):
for n, (value, condition) in enumerate(preprocessor_checks.items()): for n, (value, condition) in enumerate(preprocessor_checks.iteritems()):
check += dedent('''\ check += dedent('''\
#%(if)s %(condition)s #%(if)s %(condition)s
%%%(name)s "%(value)s" %%%(name)s "%(value)s"
@@ -307,7 +269,7 @@ def get_compiler_info(compiler, language):
# have non-ASCII characters. Treat the output as bytearray. # have non-ASCII characters. Treat the output as bytearray.
data = {} data = {}
for line in result.splitlines(): for line in result.splitlines():
if line.startswith('%'): if line.startswith(b'%'):
k, _, v = line.partition(' ') k, _, v = line.partition(' ')
k = k.lstrip('%') k = k.lstrip('%')
data[k] = v.replace(' ', '').lstrip('"').rstrip('"') data[k] = v.replace(' ', '').lstrip('"').rstrip('"')
@@ -435,11 +397,10 @@ def check_compiler(compiler, language, target):
@imports('json') @imports('json')
@imports('subprocess') @imports('subprocess')
@imports('sys') @imports('sys')
@imports(_from='locale', _import='getpreferredencoding')
def get_vc_paths(topsrcdir): def get_vc_paths(topsrcdir):
encoding = getpreferredencoding(False)
def vswhere(args): def vswhere(args):
return json.loads(subprocess.check_output([os.path.join(topsrcdir, 'build/win32/vswhere.exe'), '-format', 'json'] + args).decode(encoding, errors='replace')) encoding = 'mbcs' if sys.platform == 'win32' else 'utf-8'
return json.loads(subprocess.check_output([os.path.join(topsrcdir, 'build/win32/vswhere.exe'), '-format', 'json'] + args).decode(encoding, 'replace'))
# Can't pass -requires with -legacy, so query each separately. # Can't pass -requires with -legacy, so query each separately.
# Legacy versions first (VS2015) # Legacy versions first (VS2015)
@@ -458,7 +419,7 @@ def get_vc_paths(topsrcdir):
# Then VS2017 and newer. # Then VS2017 and newer.
for install in vswhere(['-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64']): for install in vswhere(['-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64']):
path = install['installationPath'] path = install['installationPath']
tools_version = open(os.path.join(path, r'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt'), 'r', encoding=encoding, errors='replace').read().strip() tools_version = open(os.path.join(path, r'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt'), 'rb').read().strip()
tools_path = os.path.join(path, r'VC\Tools\MSVC', tools_version, r'bin\HostX64') tools_path = os.path.join(path, r'VC\Tools\MSVC', tools_version, r'bin\HostX64')
yield (Version(install['installationVersion']), { yield (Version(install['installationVersion']), {
'x64': [os.path.join(tools_path, 'x64')], 'x64': [os.path.join(tools_path, 'x64')],
@@ -640,7 +601,7 @@ def compiler(language, host_or_target, c_compiler=None, other_compiler=None,
if cross_compiling and other_compiler.type == 'clang': if cross_compiling and other_compiler.type == 'clang':
return namespace(**{ return namespace(**{
k: [] if k == 'flags' else v k: [] if k == 'flags' else v
for k, v in other_compiler.__dict__.items() for k, v in other_compiler.__dict__.iteritems()
}) })
# Normally, we'd use `var` instead of `_var`, but the interaction with # Normally, we'd use `var` instead of `_var`, but the interaction with
@@ -734,9 +695,9 @@ def compiler(language, host_or_target, c_compiler=None, other_compiler=None,
# Check the compiler version here instead of in `compiler_version` so # Check the compiler version here instead of in `compiler_version` so
# that the `checking` message doesn't pretend the compiler can be used # that the `checking` message doesn't pretend the compiler can be used
# to then bail out one line later. # to then bail out one line later.
if info.type == 'gcc' and info.version < '9.1.0': if info.type == 'gcc' and info.version < '7.1.0':
raise FatalCheckError( raise FatalCheckError(
'Only GCC 9.1 or newer is supported (found version %s).' 'Only GCC 7.1 or newer is supported (found version %s).'
% info.version) % info.version)
# If you want to bump the version check here search for # If you want to bump the version check here search for
+3 -10
View File
@@ -25,22 +25,15 @@ def configure_error(message):
@imports('sys') @imports('sys')
@imports(_from='mozbuild.configure.util', _import='LineIO') @imports(_from='mozbuild.configure.util', _import='LineIO')
@imports(_from='mozbuild.shellutil', _import='quote') @imports(_from='mozbuild.shellutil', _import='quote')
@imports(_from='mozbuild.getencoding', _import='getencoding')
def check_cmd_output(*args, **kwargs): def check_cmd_output(*args, **kwargs):
encoding = getencoding()
onerror = kwargs.pop('onerror', None) onerror = kwargs.pop('onerror', None)
with log.queue_debug(): with log.queue_debug():
log.debug('Executing: `%s`', quote(*args)) log.debug('Executing: `%s`', quote(*args))
proc = subprocess.Popen(args, stdout=subprocess.PIPE, proc = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
stdout, stderr = proc.communicate() stdout, stderr = proc.communicate()
retcode = proc.wait() retcode = proc.wait()
stdout = stdout.decode(encoding, errors='replace')
stderr = stderr.decode(encoding, errors='replace')
if retcode == 0: if retcode == 0:
return stdout return stdout
@@ -77,7 +70,7 @@ def windows_binary_type(path):
Returns WindowsBinaryType constant. Returns WindowsBinaryType constant.
""" """
GetBinaryTypeW = ctypes.windll.kernel32.GetBinaryTypeW GetBinaryTypeW = ctypes.windll.kernel32.GetBinaryTypeW
GetBinaryTypeW.argtypes = [wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)] GetBinaryTypeW.argtypes = [wintypes.LPWSTR, wintypes.POINTER(wintypes.DWORD)]
GetBinaryTypeW.restype = wintypes.BOOL GetBinaryTypeW.restype = wintypes.BOOL
bin_type = wintypes.DWORD() bin_type = wintypes.DWORD()
@@ -239,7 +232,7 @@ def unique_list(l):
# ('19.0', 'arm', r'C:\...\amd64_arm\cl.exe') # ('19.0', 'arm', r'C:\...\amd64_arm\cl.exe')
# ('19.0', 'x64', r'C:\...\amd64\cl.exe') # ('19.0', 'x64', r'C:\...\amd64\cl.exe')
# ('19.0', 'x86', r'C:\...\amd64_x86\cl.exe') # ('19.0', 'x86', r'C:\...\amd64_x86\cl.exe')
@imports(_import='winreg', _as='winreg') @imports(_import='_winreg', _as='winreg')
@imports(_from='__builtin__', _import='WindowsError') @imports(_from='__builtin__', _import='WindowsError')
@imports(_from='fnmatch', _import='fnmatch') @imports(_from='fnmatch', _import='fnmatch')
def get_registry_values(pattern): def get_registry_values(pattern):
@@ -302,7 +295,7 @@ def get_registry_values(pattern):
keys = next_keys keys = next_keys
@imports(_from='mozbuild.version', _import='RichVersion', _as='_Version') @imports(_from='mozbuild.configure.util', _import='Version', _as='_Version')
def Version(v): def Version(v):
'A version number that can be compared usefully.' 'A version number that can be compared usefully.'
return _Version(v) return _Version(v)
+1 -4
View File
@@ -408,12 +408,9 @@ mt = check_prog('MT', depends_win()(lambda: ('mt.exe',)), input='MT',
@depends_win(mt) @depends_win(mt)
@checking('whether MT is really Microsoft Manifest Tool', lambda x: bool(x)) @checking('whether MT is really Microsoft Manifest Tool', lambda x: bool(x))
@imports('subprocess') @imports('subprocess')
@imports(_from='locale', _import='getpreferredencoding')
def valid_mt(path): def valid_mt(path):
encoding = getpreferredencoding(False)
try: try:
out = subprocess.check_output([path]) out = subprocess.check_output([path]).splitlines()
out = out.decode(encoding, errors='replace').splitlines()
out = '\n'.join(l for l in out out = '\n'.join(l for l in out
if 'Microsoft (R) Manifest Tool' in l) if 'Microsoft (R) Manifest Tool' in l)
if out: if out:
+13 -13
View File
@@ -58,7 +58,7 @@ def runUtil(util, args, inputdata = None):
def createRandomFile(randomFile): def createRandomFile(randomFile):
for count in range(0, 2048): for count in xrange(0, 2048):
randomFile.write(chr(random.randint(0, 255))) randomFile.write(chr(random.randint(0, 255)))
@@ -125,7 +125,7 @@ def createSSLServerCertificate(build, srcDir):
iterator = iter(locations) iterator = iter(locations)
# Skips the first entry, I don't know why: bug 879740 # Skips the first entry, I don't know why: bug 879740
next(iterator) iterator.next()
locationsParam = "" locationsParam = ""
firstLocation = "" firstLocation = ""
@@ -148,7 +148,7 @@ def createSSLServerCertificate(build, srcDir):
firstLocation = loc.host firstLocation = loc.host
if not firstLocation: if not firstLocation:
print("Nothing to generate, no automatic secure hosts specified") print "Nothing to generate, no automatic secure hosts specified"
else: else:
createRandomFile(rndfile) createRandomFile(rndfile)
@@ -162,7 +162,7 @@ def createSSLServerCertificate(build, srcDir):
return 0 return 0
if len(sys.argv) == 1: if len(sys.argv) == 1:
print("Specify --gen-server or --gen-ca") print "Specify --gen-server or --gen-ca"
sys.exit(1) sys.exit(1)
build = MozbuildObject.from_environment() build = MozbuildObject.from_environment()
@@ -170,23 +170,23 @@ certdir = os.path.join(build.topsrcdir, "build", "pgo", "certs")
if sys.argv[1] == "--gen-server": if sys.argv[1] == "--gen-server":
certificateStatus = createSSLServerCertificate(build, certdir) certificateStatus = createSSLServerCertificate(build, certdir)
if certificateStatus: if certificateStatus:
print("TEST-UNEXPECTED-FAIL | SSL Server Certificate generation") print "TEST-UNEXPECTED-FAIL | SSL Server Certificate generation"
sys.exit(certificateStatus) sys.exit(certificateStatus)
if sys.argv[1] == "--gen-ca": if sys.argv[1] == "--gen-ca":
certificateStatus = createCertificateAuthority(build, certdir) certificateStatus = createCertificateAuthority(build, certdir)
if certificateStatus: if certificateStatus:
print("TEST-UNEXPECTED-FAIL | Certificate Authority generation") print "TEST-UNEXPECTED-FAIL | Certificate Authority generation"
else: else:
print("\n\n") print "\n\n"
print("===================================================") print "==================================================="
print(" IMPORTANT:") print " IMPORTANT:"
print(" To use this new certificate authority in tests") print " To use this new certificate authority in tests"
print(" run 'make' at testing/mochitest") print " run 'make' at testing/mochitest"
print("===================================================") print "==================================================="
sys.exit(certificateStatus) sys.exit(certificateStatus)
print("Invalid option specified") print "Invalid option specified"
sys.exit(1) sys.exit(1)
@@ -88,7 +88,7 @@ var decompressedJQuery = function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(par
for documentation and information on getting the source. for documentation and information on getting the source.
*/ */
var decompressedDojo = function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('if(V z=="1k"){(B(){if(V D["1o"]=="1k"){D.1o={}}if((!D["1z"])||(!1z["ca"])){D.1z={}}A cn=["rA","rz","1K","ry","rx","9f","rw","rv","ru","rt","rs","rr","rq","ro","rn","rm"];A i=0,24;1s(24=cn[i++]){if(!1z[24]){1z[24]=B(){}}}if(V D["z"]=="1k"){D.z={}}z.1W=D;A d3={im:U,rl:U,rk:"",rj:"",ri:"",rh:K,rg:U};R(A 8z in d3){if(V 1o[8z]=="1k"){1o[8z]=d3[8z]}}A jK=["rf","rd","rc","rb"];A t;1s(t=jK.3a()){z["is"+t]=U}})();z.8h=1o.8h;z.cY={jJ:0,jI:9,jH:0,jG:"",jF:2V("$ra: r9 $".1f(/[0-9]+/)[0]),2i:B(){4G(z.cY){C jJ+"."+jI+"."+jH+jG+" ("+jF+")"}}};z.d1=B(jE,jD,1V){A 2h=1V||z.1W;R(A i=0,p;2h&&(p=jE[i]);i++){2h=(p in 2h?2h[p]:(jD?2h[p]={}:1k))}C 2h};z.88=B(jC,jA,jB){A d2=jC.1A("."),p=d2.8q(),M=z.d1(d2,K,jB);C(M&&p?(M[p]=jA):1k)};z.6q=B(jz,jy,jx){C z.d1(jz.1A("."),jy,jx)};z.r8=B(jw,M){C!!z.6q(jw,U,M)};z["3u"]=B(d0){C z.1W.3u?z.1W.3u(d0):3u(d0)};z.ia=B(jv,cZ,cX){A 8y="r7: "+jv;if(cZ){8y+=" "+cZ}if(cX){8y+=" -- r6 be r5 in cY: "+cX}1z.1K(8y)};z.r4=B(ju,cW){A cV="r3: "+ju+" -- r2 r1 4F r0 qZ qY.";if(cW){cV+=" "+cW}1z.1K(cV)};(B(){A cR={53:{},6p:0,1h:{},8k:{z:{1p:"z",1Z:"."},cU:{1p:"cU",1Z:"../qX/cU"},cT:{1p:"cT",1Z:"cT"}},cN:B(cS){A mp=D.8k;C jp(mp[cS]&&mp[cS].1Z)},jk:B(8x){A mp=D.8k;if(D.cN(8x)){C mp[8x].1Z}C 8x},8v:[],6t:U,56:[],8t:[],8u:U};R(A cQ in cR){z[cQ]=cR[cQ]}})();z.jg=B(8w,cP,cb){A 1g=(((8w.2s(0)=="/"||8w.1f(/^\\w+:/)))?"":D.51)+8w;if(1o.jt&&z.c8){1g+="?"+67(1o.jt).2f(/\\W+/g,"")}1u{C!cP?D.cO(1g,cb):D.jq(1g,cP,cb)}1y(e){1z.1K(e);C U}};z.cO=B(1g,cb){if(D.8v[1g]){C K}A 6u=D.iR(1g,K);if(!6u){C U}D.8v[1g]=K;D.8v.Y(1g);if(cb){6u="("+6u+")"}A jr=z["3u"](6u+"\\r\\n//@ qW="+1g);if(cb){cb(jr)}C K};z.jq=B(1g,jo,cb){A ok=U;1u{ok=D.cO(1g,cb)}1y(e){1z.1K("qV je ",1g," 4G 9f: ",e)}C jp(ok&&D.53[jo])};z.6m=B(){D.8u=K;D.6t=K;A 57=D.56;D.56=[];R(A x=0;x<57.G;x++){57[x]()}D.8u=U;if(z.6t&&z.6p==0&&D.56.G>0){z.8s()}};z.ck=B(){A 57=D.8t;1s(57.G){(57.8q())()}};z.qU=B(M,jn){A d=z;if(P.G==1){d.56.Y(M)}I{if(P.G>1){d.56.Y(B(){M[jn]()})}}if(d.6t&&d.6p==0&&!d.8u){d.8s()}};z.dW=B(M,jm){A d=z;if(P.G==1){d.8t.Y(M)}I{if(P.G>1){d.8t.Y(B(){M[jm]()})}}};z.iM=B(){if(D.6t){C}if(D.6p>0){1z.1K("qT qS in qR!");C}z.8s()};z.8s=B(){if(V 5c=="8b"||(1o["qQ"]&&z.2M)){5c("z.6m();",0)}I{z.6m()}};z.cF=B(jl){A 4v=jl.1A(".");R(A i=4v.G;i>0;i--){A 8r=4v.2w(0,i).22(".");if((i==1)&&!D.cN(8r)){4v[0]="../"+4v[0]}I{A cM=D.jk(8r);if(cM!=8r){4v.3S(0,i,cM);3f}}}C 4v};z.jj=U;z.8m=B(2T,qP,55){55=D.jj||55;A 54=D.53[2T];if(54){C 54}A cL=2T.1A(".");A 3L=D.cF(2T);A jh=((3L[0].2s(0)!="/")&&!3L[0].1f(/^\\w+:/));A ji=3L[3L.G-1];A 3m;if(ji=="*"){2T=cL.2w(0,-1).22(".");3L.8q();3m=3L.22("/")+"/"+(1o["qO"]||"qN")+".js";if(jh&&3m.2s(0)=="/"){3m=3m.2w(1)}}I{3m=3L.22("/")+".js";2T=cL.22(".")}A jf=(!55)?2T:L;A ok=D.jg(3m,jf);if((!ok)&&(!55)){2m S 1O("qM 3O 4E \'"+2T+"\'; 72 qL \'"+3m+"\'")}if((!55)&&(!D["qK"])){54=D.53[2T];if(!54){2m S 1O("qJ \'"+2T+"\' is 3O qI a8 je \'"+3m+"\'")}}C 54};z.8c=z.8m;z.1Q=B(cK){A cJ=cK+"";A 8p=cJ;A 6s=cK.1A(/\\./);if(6s[6s.G-1]=="*"){6s.8q();8p=6s.22(".")}A 8o=z.6q(8p,K);D.53[cJ]=8o;D.53[8p]=8o;C 8o};z.qH=B(8n){A jd=8n["qG"]||[];A cI=jd.3U(8n[z.j4]||8n["aY"]||[]);R(A x=0;x<cI.G;x++){A 8l=cI[x];if(8l.1P==4e){z.8m.14(z,8l)}I{z.8m(8l)}}};z.jb=B(jc,qF){if(jc===K){A cH=[];R(A i=1;i<P.G;i++){cH.Y(P[i])}z.8c.14(z,cH)}};z.qE=z.jb;z.io=B(cG,ja){D.8k[cG]={1p:cG,1Z:ja}};z.qD=B(qC,qB,qA,qz){z.8c("z.j9");z.j9.qy.14(z.qx,P)};(B(){A j7=S 9G("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\\\?([^#]*))?(#(.*))?$");A j6=S 9G("^((([^:]+:)?([^@]+))@)?([^:]*)(:([0-9]+))?$");z.4r=B(){A n=L;A 1V=P;A 1g=1V[0];R(A i=1;i<1V.G;i++){if(!1V[i]){6c}A 1t=S z.4r(1V[i]+"");A 4u=S z.4r(1g+"");if((1t.28=="")&&(!1t.4t)&&(!1t.3l)&&(!1t.1r)){if(1t.52!=n){4u.52=1t.52}1t=4u}I{if(!1t.4t){1t.4t=4u.4t;if(!1t.3l){1t.3l=4u.3l;if(1t.28.2s(0)!="/"){A j8=4u.28.21(0,4u.28.31("/")+1)+1t.28;A 1X=j8.1A("/");R(A j=0;j<1X.G;j++){if(1X[j]=="."){if(j==1X.G-1){1X[j]=""}I{1X.3S(j,1);j--}}I{if(j>0&&!(j==1&&1X[0]=="")&&1X[j]==".."&&1X[j-1]!=".."){if(j==(1X.G-1)){1X.3S(j,1);1X[j-1]=""}I{1X.3S(j-1,2);j-=2}}}}1t.28=1X.22("/")}}}}1g="";if(1t.4t){1g+=1t.4t+":"}if(1t.3l){1g+="//"+1t.3l}1g+=1t.28;if(1t.1r){1g+="?"+1t.1r}if(1t.52){1g+="#"+1t.52}}D.1g=1g.2i();A r=D.1g.1f(j7);D.4t=r[2]||(r[1]?"":n);D.3l=r[4]||(r[3]?"":n);D.28=r[5];D.1r=r[7]||(r[6]?"":n);D.52=r[9]||(r[8]?"":n);if(D.3l!=n){r=D.3l.1f(j6);D.8X=r[3]||n;D.8W=r[4]||n;D.qw=r[5];D.qv=r[7]||n}};z.4r.1C.2i=B(){C D.1g}})();z.qu=B(j5,2E){A 2B=z.cF(j5).22("/");if(!2B){C L}if(2B.31("/")!=2B.G-1){2B+="/"}A cE=2B.T(":");if(2B.2s(0)!="/"&&(cE==-1||cE>2B.T("/"))){2B=z.51+2B}C S z.4r(2B,2E)};if(V 26!="1k"){z.c8=K;z.j4="qt";(B(){A d=z;if(1q&&1q.4I){A 8j=1q.4I("ak");A j3=/z(\\.qs)?\\.js([\\?\\.]|$)/i;R(A i=0;i<8j.G;i++){A 4X=8j[i].5t("4X");if(!4X){6c}A m=4X.1fLine truncated var decompressedDojo = function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('if(V z=="1k"){(B(){if(V D["1o"]=="1k"){D.1o={}}if((!D["1z"])||(!1z["ca"])){D.1z={}}A cn=["rA","rz","1K","ry","rx","9f","rw","rv","ru","rt","rs","rr","rq","ro","rn","rm"];A i=0,24;1s(24=cn[i++]){if(!1z[24]){1z[24]=B(){}}}if(V D["z"]=="1k"){D.z={}}z.1W=D;A d3={im:U,rl:U,rk:"",rj:"",ri:"",rh:K,rg:U};R(A 8z in d3){if(V 1o[8z]=="1k"){1o[8z]=d3[8z]}}A jK=["rf","rd","rc","rb"];A t;1s(t=jK.3a()){z["is"+t]=U}})();z.8h=1o.8h;z.cY={jJ:0,jI:9,jH:0,jG:"",jF:2V("$ra: r9 $".1f(/[0-9]+/)[0]),2i:B(){4G(z.cY){C jJ+"."+jI+"."+jH+jG+" ("+jF+")"}}};z.d1=B(jE,jD,1V){A 2h=1V||z.1W;R(A i=0,p;2h&&(p=jE[i]);i++){2h=(p in 2h?2h[p]:(jD?2h[p]={}:1k))}C 2h};z.88=B(jC,jA,jB){A d2=jC.1A("."),p=d2.8q(),M=z.d1(d2,K,jB);C(M&&p?(M[p]=jA):1k)};z.6q=B(jz,jy,jx){C z.d1(jz.1A("."),jy,jx)};z.r8=B(jw,M){C!!z.6q(jw,U,M)};z["3u"]=B(d0){C z.1W.3u?z.1W.3u(d0):3u(d0)};z.ia=B(jv,cZ,cX){A 8y="r7: "+jv;if(cZ){8y+=" "+cZ}if(cX){8y+=" -- r6 be r5 in cY: "+cX}1z.1K(8y)};z.r4=B(ju,cW){A cV="r3: "+ju+" -- r2 r1 4F r0 qZ qY.";if(cW){cV+=" "+cW}1z.1K(cV)};(B(){A cR={53:{},6p:0,1h:{},8k:{z:{1p:"z",1Z:"."},cU:{1p:"cU",1Z:"../qX/cU"},cT:{1p:"cT",1Z:"cT"}},cN:B(cS){A mp=D.8k;C jp(mp[cS]&&mp[cS].1Z)},jk:B(8x){A mp=D.8k;if(D.cN(8x)){C mp[8x].1Z}C 8x},8v:[],6t:U,56:[],8t:[],8u:U};R(A cQ in cR){z[cQ]=cR[cQ]}})();z.jg=B(8w,cP,cb){A 1g=(((8w.2s(0)=="/"||8w.1f(/^\\w+:/)))?"":D.51)+8w;if(1o.jt&&z.c8){1g+="?"+67(1o.jt).2f(/\\W+/g,"")}1u{C!cP?D.cO(1g,cb):D.jq(1g,cP,cb)}1y(e){1z.1K(e);C U}};z.cO=B(1g,cb){if(D.8v[1g]){C K}A 6u=D.iR(1g,K);if(!6u){C U}D.8v[1g]=K;D.8v.Y(1g);if(cb){6u="("+6u+")"}A jr=z["3u"](6u+"\\r\\n//@ qW="+1g);if(cb){cb(jr)}C K};z.jq=B(1g,jo,cb){A ok=U;1u{ok=D.cO(1g,cb)}1y(e){1z.1K("qV je ",1g," 4G 9f: ",e)}C jp(ok&&D.53[jo])};z.6m=B(){D.8u=K;D.6t=K;A 57=D.56;D.56=[];R(A x=0;x<57.G;x++){57[x]()}D.8u=U;if(z.6t&&z.6p==0&&D.56.G>0){z.8s()}};z.ck=B(){A 57=D.8t;1s(57.G){(57.8q())()}};z.qU=B(M,jn){A d=z;if(P.G==1){d.56.Y(M)}I{if(P.G>1){d.56.Y(B(){M[jn]()})}}if(d.6t&&d.6p==0&&!d.8u){d.8s()}};z.dW=B(M,jm){A d=z;if(P.G==1){d.8t.Y(M)}I{if(P.G>1){d.8t.Y(B(){M[jm]()})}}};z.iM=B(){if(D.6t){C}if(D.6p>0){1z.1K("qT qS in qR!");C}z.8s()};z.8s=B(){if(V 5c=="8b"||(1o["qQ"]&&z.2M)){5c("z.6m();",0)}I{z.6m()}};z.cF=B(jl){A 4v=jl.1A(".");R(A i=4v.G;i>0;i--){A 8r=4v.2w(0,i).22(".");if((i==1)&&!D.cN(8r)){4v[0]="../"+4v[0]}I{A cM=D.jk(8r);if(cM!=8r){4v.3S(0,i,cM);3f}}}C 4v};z.jj=U;z.8m=B(2T,qP,55){55=D.jj||55;A 54=D.53[2T];if(54){C 54}A cL=2T.1A(".");A 3L=D.cF(2T);A jh=((3L[0].2s(0)!="/")&&!3L[0].1f(/^\\w+:/));A ji=3L[3L.G-1];A 3m;if(ji=="*"){2T=cL.2w(0,-1).22(".");3L.8q();3m=3L.22("/")+"/"+(1o["qO"]||"qN")+".js";if(jh&&3m.2s(0)=="/"){3m=3m.2w(1)}}I{3m=3L.22("/")+".js";2T=cL.22(".")}A jf=(!55)?2T:L;A ok=D.jg(3m,jf);if((!ok)&&(!55)){2m S 1O("qM 3O 4E \'"+2T+"\'; 72 qL \'"+3m+"\'")}if((!55)&&(!D["qK"])){54=D.53[2T];if(!54){2m S 1O("qJ \'"+2T+"\' is 3O qI a8 je \'"+3m+"\'")}}C 54};z.8c=z.8m;z.1Q=B(cK){A cJ=cK+"";A 8p=cJ;A 6s=cK.1A(/\\./);if(6s[6s.G-1]=="*"){6s.8q();8p=6s.22(".")}A 8o=z.6q(8p,K);D.53[cJ]=8o;D.53[8p]=8o;C 8o};z.qH=B(8n){A jd=8n["qG"]||[];A cI=jd.3U(8n[z.j4]||8n["aY"]||[]);R(A x=0;x<cI.G;x++){A 8l=cI[x];if(8l.1P==4e){z.8m.14(z,8l)}I{z.8m(8l)}}};z.jb=B(jc,qF){if(jc===K){A cH=[];R(A i=1;i<P.G;i++){cH.Y(P[i])}z.8c.14(z,cH)}};z.qE=z.jb;z.io=B(cG,ja){D.8k[cG]={1p:cG,1Z:ja}};z.qD=B(qC,qB,qA,qz){z.8c("z.j9");z.j9.qy.14(z.qx,P)};(B(){A j7=S 9G("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\\\?([^#]*))?(#(.*))?$");A j6=S 9G("^((([^:]+:)?([^@]+))@)?([^:]*)(:([0-9]+))?$");z.4r=B(){A n=L;A 1V=P;A 1g=1V[0];R(A i=1;i<1V.G;i++){if(!1V[i]){6c}A 1t=S z.4r(1V[i]+"");A 4u=S z.4r(1g+"");if((1t.28=="")&&(!1t.4t)&&(!1t.3l)&&(!1t.1r)){if(1t.52!=n){4u.52=1t.52}1t=4u}I{if(!1t.4t){1t.4t=4u.4t;if(!1t.3l){1t.3l=4u.3l;if(1t.28.2s(0)!="/"){A j8=4u.28.21(0,4u.28.31("/")+1)+1t.28;A 1X=j8.1A("/");R(A j=0;j<1X.G;j++){if(1X[j]=="."){if(j==1X.G-1){1X[j]=""}I{1X.3S(j,1);j--}}I{if(j>0&&!(j==1&&1X[0]=="")&&1X[j]==".."&&1X[j-1]!=".."){if(j==(1X.G-1)){1X.3S(j,1);1X[j-1]=""}I{1X.3S(j-1,2);j-=2}}}}1t.28=1X.22("/")}}}}1g="";if(1t.4t){1g+=1t.4t+":"}if(1t.3l){1g+="//"+1t.3l}1g+=1t.28;if(1t.1r){1g+="?"+1t.1r}if(1t.52){1g+="#"+1t.52}}D.1g=1g.2i();A r=D.1g.1f(j7);D.4t=r[2]||(r[1]?"":n);D.3l=r[4]||(r[3]?"":n);D.28=r[5];D.1r=r[7]||(r[6]?"":n);D.52=r[9]||(r[8]?"":n);if(D.3l!=n){r=D.3l.1f(j6);D.8X=r[3]||n;D.8W=r[4]||n;D.qw=r[5];D.qv=r[7]||n}};z.4r.1C.2i=B(){C D.1g}})();z.qu=B(j5,2E){A 2B=z.cF(j5).22("/");if(!2B){C L}if(2B.31("/")!=2B.G-1){2B+="/"}A cE=2B.T(":");if(2B.2s(0)!="/"&&(cE==-1||cE>2B.T("/"))){2B=z.51+2B}C S z.4r(2B,2E)};if(V 26!="1k"){z.c8=K;z.j4="qt";(B(){A d=z;if(1q&&1q.4I){A 8j=1q.4I("ak");A j3=/z(\\.qs)?\\.js([\\?\\.]|$)/i;R(A i=0;i<8j.G;i++){A 4X=8j[i].5t("4X");if(!4X){6c}A m=4X.1fLine truncated
/* /*
+1 -1
View File
@@ -77,7 +77,7 @@ if __name__ == '__main__':
jarlog = os.getenv("JARLOG_FILE") jarlog = os.getenv("JARLOG_FILE")
if jarlog: if jarlog:
env["MOZ_JAR_LOG_FILE"] = os.path.abspath(jarlog) env["MOZ_JAR_LOG_FILE"] = os.path.abspath(jarlog)
print("jarlog: %s" % env["MOZ_JAR_LOG_FILE"]) print "jarlog: %s" % env["MOZ_JAR_LOG_FILE"]
cmdargs = ["http://localhost:%d/index.html" % PORT] cmdargs = ["http://localhost:%d/index.html" % PORT]
runner = FirefoxRunner(profile=profile, runner = FirefoxRunner(profile=profile,
+11 -22
View File
@@ -3,7 +3,7 @@
from __future__ import print_function from __future__ import print_function
import os, sys import os, sys
if not len(sys.argv) == 2 or not os.path.exists(sys.argv[1]): if not len(sys.argv) is 2 or not os.path.exists(sys.argv[1]):
print("\nYou did not supply a valid path to check.") print("\nYou did not supply a valid path to check.")
exit(1) exit(1)
else: else:
@@ -44,8 +44,7 @@ PP_DIRECTIVES = [
] ]
PP_FILES = [] PP_FILES = []
PP_BAD_DIRECTIVE_FILES = [] PP_BAD_FILES = []
PP_BAD_ENCODING_FILES = []
for root, directories, filenames in os.walk(DIST_PATH): for root, directories, filenames in os.walk(DIST_PATH):
for filename in filenames: for filename in filenames:
@@ -53,31 +52,21 @@ for root, directories, filenames in os.walk(DIST_PATH):
PP_FILES += [ os.path.join(root, filename).replace(os.sep, '/') ] PP_FILES += [ os.path.join(root, filename).replace(os.sep, '/') ]
for file in PP_FILES: for file in PP_FILES:
with open(file, encoding='utf-8') as fp: with open(file) as fp:
marker = '%' if file.endswith(PP_SPECIAL_TYPES) else '#' marker = '%' if file.endswith(PP_SPECIAL_TYPES) else '#'
directives = tuple(marker + directive for directive in PP_DIRECTIVES) directives = tuple(marker + directive for directive in PP_DIRECTIVES)
try: for line in fp:
for line in fp: if line.startswith(directives):
if line.startswith(directives): PP_BAD_FILES += [ file.replace(DIST_PATH + '/', '') ]
PP_BAD_DIRECTIVE_FILES += [ file.replace(DIST_PATH + '/', '') ]
except UnicodeDecodeError:
PP_BAD_ENCODING_FILES += [ file.replace(DIST_PATH+ '/' , '') ]
fp.close() fp.close()
PP_BAD_DIRECTIVE_FILES = list(dict.fromkeys(PP_BAD_DIRECTIVE_FILES)) PP_BAD_FILES = list(dict.fromkeys(PP_BAD_FILES))
PP_BAD_ENCODING_FILES = list(dict.fromkeys(PP_BAD_ENCODING_FILES))
print('Done!') print('Done!')
if len(PP_BAD_DIRECTIVE_FILES) > 0: if len(PP_BAD_FILES) > 0:
print("\nWARNING: The following {0} file(s) in {1} may require preprocessing:\n".format(len(PP_BAD_DIRECTIVE_FILES), DIST_PATH)) print("\nWARNING: The following {0} file(s) in {1} may require preprocessing:\n".format(len(PP_BAD_FILES), DIST_PATH))
for file in PP_BAD_DIRECTIVE_FILES: for file in PP_BAD_FILES:
print(file) print(file)
if len(PP_BAD_ENCODING_FILES) > 0: exit(0)
print("\nWARNING: The following {0} file(s) in {1} are not valid UTF-8:\n".format(len(PP_BAD_ENCODING_FILES), DIST_PATH))
for file in PP_BAD_ENCODING_FILES:
print(file)
sys.exit(0)
+1 -1
View File
@@ -10,4 +10,4 @@ with open(filename, 'rU') as fh:
source = fh.read() source = fh.read()
statements = pymake.parser.parsestring(source, filename) statements = pymake.parser.parsestring(source, filename)
print(statements.to_source()) print statements.to_source()
+2 -2
View File
@@ -4,9 +4,9 @@ import sys
import pymake.parser import pymake.parser
for f in sys.argv[1:]: for f in sys.argv[1:]:
print("Parsing %s" % f) print "Parsing %s" % f
fd = open(f, 'rU') fd = open(f, 'rU')
s = fd.read() s = fd.read()
fd.close() fd.close()
stmts = pymake.parser.parsestring(s, f) stmts = pymake.parser.parsestring(s, f)
print(stmts) print stmts
+15 -15
View File
@@ -2,7 +2,7 @@
import errno, sys, os, shutil, time import errno, sys, os, shutil, time
from getopt import getopt, GetoptError from getopt import getopt, GetoptError
from .process import PythonException from process import PythonException
__all__ = ["mkdir", "rm", "sleep", "touch"] __all__ = ["mkdir", "rm", "sleep", "touch"]
@@ -13,8 +13,8 @@ def mkdir(args):
""" """
try: try:
opts, args = getopt(args, "p", ["parents"]) opts, args = getopt(args, "p", ["parents"])
except GetoptError as e: except GetoptError, e:
raise PythonException("mkdir: %s" % e, 1) raise PythonException, ("mkdir: %s" % e, 1)
parents = False parents = False
for o, a in opts: for o, a in opts:
if o in ('-p', '--parents'): if o in ('-p', '--parents'):
@@ -25,11 +25,11 @@ def mkdir(args):
os.makedirs(f) os.makedirs(f)
else: else:
os.mkdir(f) os.mkdir(f)
except OSError as e: except OSError, e:
if e.errno == errno.EEXIST and parents: if e.errno == errno.EEXIST and parents:
pass pass
else: else:
raise PythonException("mkdir: %s" % e, 1) raise PythonException, ("mkdir: %s" % e, 1)
def rm(args): def rm(args):
""" """
@@ -38,8 +38,8 @@ def rm(args):
""" """
try: try:
opts, args = getopt(args, "rRf", ["force", "recursive"]) opts, args = getopt(args, "rRf", ["force", "recursive"])
except GetoptError as e: except GetoptError, e:
raise PythonException("rm: %s" % e, 1) raise PythonException, ("rm: %s" % e, 1)
force = False force = False
recursive = False recursive = False
for o, a in opts: for o, a in opts:
@@ -50,7 +50,7 @@ def rm(args):
for f in args: for f in args:
if os.path.isdir(f): if os.path.isdir(f):
if not recursive: if not recursive:
raise PythonException("rm: cannot remove '%s': Is a directory" % f, 1) raise PythonException, ("rm: cannot remove '%s': Is a directory" % f, 1)
else: else:
shutil.rmtree(f, force) shutil.rmtree(f, force)
elif os.path.exists(f): elif os.path.exists(f):
@@ -58,9 +58,9 @@ def rm(args):
os.unlink(f) os.unlink(f)
except: except:
if not force: if not force:
raise PythonException("rm: failed to remove '%s': %s" % (f, sys.exc_info()[0]), 1) raise PythonException, ("rm: failed to remove '%s': %s" % (f, sys.exc_info()[0]), 1)
elif not force: elif not force:
raise PythonException("rm: cannot remove '%s': No such file or directory" % f, 1) raise PythonException, ("rm: cannot remove '%s': No such file or directory" % f, 1)
def sleep(args): def sleep(args):
""" """
@@ -70,7 +70,7 @@ def sleep(args):
values = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400} values = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
for a in args: for a in args:
multiplier = 1 multiplier = 1
for k, v in values.items(): for k, v in values.iteritems():
if a.endswith(k): if a.endswith(k):
a = a[:-1] a = a[:-1]
multiplier = v multiplier = v
@@ -79,7 +79,7 @@ def sleep(args):
f = float(a) f = float(a)
total += f * multiplier total += f * multiplier
except ValueError: except ValueError:
raise PythonException("sleep: invalid time interval '%s'" % a, 1) raise PythonException, ("sleep: invalid time interval '%s'" % a, 1)
time.sleep(total) time.sleep(total)
def touch(args): def touch(args):
@@ -88,8 +88,8 @@ def touch(args):
""" """
try: try:
opts, args = getopt(args, "t:") opts, args = getopt(args, "t:")
except GetoptError as e: except GetoptError, e:
raise PythonException("touch: %s" % e, 1) raise PythonException, ("touch: %s" % e, 1)
opts = dict(opts) opts = dict(opts)
times = None times = None
if '-t' in opts: if '-t' in opts:
@@ -97,7 +97,7 @@ def touch(args):
from time import mktime, localtime from time import mktime, localtime
m = re.match('^(?P<Y>(?:\d\d)?\d\d)?(?P<M>\d\d)(?P<D>\d\d)(?P<h>\d\d)(?P<m>\d\d)(?:\.(?P<s>\d\d))?$', opts['-t']) m = re.match('^(?P<Y>(?:\d\d)?\d\d)?(?P<M>\d\d)(?P<D>\d\d)(?P<h>\d\d)(?P<m>\d\d)(?:\.(?P<s>\d\d))?$', opts['-t'])
if not m: if not m:
raise PythonException("touch: invalid date format '%s'" % opts['-t'], 1) raise PythonException, ("touch: invalid date format '%s'" % opts['-t'], 1)
def normalized_field(m, f): def normalized_field(m, f):
if f == 'Y': if f == 'Y':
if m.group(f) is None: if m.group(f) is None:
+13 -13
View File
@@ -11,7 +11,7 @@ except when a submake specifies -j1 when the parent make is building in parallel
import os, subprocess, sys, logging, time, traceback, re import os, subprocess, sys, logging, time, traceback, re
from optparse import OptionParser from optparse import OptionParser
from . import data, parserdata, process, util import data, parserdata, process, util
# TODO: If this ever goes from relocatable package to system-installed, this may need to be # TODO: If this ever goes from relocatable package to system-installed, this may need to be
# a configured-in path. # a configured-in path.
@@ -62,7 +62,7 @@ def parsemakeflags(env):
return opts return opts
def _version(*args): def _version(*args):
print("""pymake: GNU-compatible make program print """pymake: GNU-compatible make program
Copyright (C) 2009 The Mozilla Foundation <http://www.mozilla.org/> Copyright (C) 2009 The Mozilla Foundation <http://www.mozilla.org/>
This is free software; see the source for copying conditions. This is free software; see the source for copying conditions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
@@ -71,7 +71,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.""") DEALINGS IN THE SOFTWARE."""
_log = logging.getLogger('pymake.execution') _log = logging.getLogger('pymake.execution')
@@ -95,7 +95,7 @@ class _MakeContext(object):
def remakecb(self, remade, error=None): def remakecb(self, remade, error=None):
if error is not None: if error is not None:
print(error) print error
self.context.defer(self.cb, 2) self.context.defer(self.cb, 2)
return return
@@ -124,15 +124,15 @@ class _MakeContext(object):
self.makefile.include(f) self.makefile.include(f)
self.makefile.finishparsing() self.makefile.finishparsing()
self.makefile.remakemakefiles(self.remakecb) self.makefile.remakemakefiles(self.remakecb)
except util.MakeError as e: except util.MakeError, e:
print(e) print e
self.context.defer(self.cb, 2) self.context.defer(self.cb, 2)
return return
if len(self.targets) == 0: if len(self.targets) == 0:
if self.makefile.defaulttarget is None: if self.makefile.defaulttarget is None:
print("No target specified and no default target found.") print "No target specified and no default target found."
self.context.defer(self.cb, 2) self.context.defer(self.cb, 2)
return return
@@ -154,7 +154,7 @@ class _MakeContext(object):
if not len(self.realtargets): if not len(self.realtargets):
if self.options.printdir: if self.options.printdir:
print("make.py[%i]: Leaving directory '%s'" % (self.makelevel, self.workdir)) print "make.py[%i]: Leaving directory '%s'" % (self.makelevel, self.workdir)
sys.stdout.flush() sys.stdout.flush()
self.context.defer(self.cb, 0) self.context.defer(self.cb, 0)
@@ -255,24 +255,24 @@ def main(args, env, cwd, cb):
context = process.getcontext(options.jobcount) context = process.getcontext(options.jobcount)
if options.printdir: if options.printdir:
print("make.py[%i]: Entering directory '%s'" % (makelevel, workdir)) print "make.py[%i]: Entering directory '%s'" % (makelevel, workdir)
sys.stdout.flush() sys.stdout.flush()
if len(options.makefiles) == 0: if len(options.makefiles) == 0:
if os.path.exists(util.normaljoin(workdir, 'Makefile')): if os.path.exists(util.normaljoin(workdir, 'Makefile')):
options.makefiles.append('Makefile') options.makefiles.append('Makefile')
else: else:
print("No makefile found") print "No makefile found"
cb(2) cb(2)
return return
ostmts, targets, overrides = parserdata.parsecommandlineargs(arguments) ostmts, targets, overrides = parserdata.parsecommandlineargs(arguments)
_MakeContext(makeflags, makelevel, workdir, context, env, targets, options, ostmts, overrides, cb) _MakeContext(makeflags, makelevel, workdir, context, env, targets, options, ostmts, overrides, cb)
except (util.MakeError) as e: except (util.MakeError), e:
print(e) print e
if options.printdir: if options.printdir:
print("make.py[%i]: Leaving directory '%s'" % (makelevel, workdir)) print "make.py[%i]: Leaving directory '%s'" % (makelevel, workdir)
sys.stdout.flush() sys.stdout.flush()
cb(2) cb(2)
return return
+18 -18
View File
@@ -3,9 +3,8 @@ A representation of makefile data structures.
""" """
import logging, re, os, sys import logging, re, os, sys
from . import parserdata, parser, functions, process, util, implicit import parserdata, parser, functions, process, util, implicit
from io import StringIO from cStringIO import StringIO
from functools import reduce
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
str_type = basestring str_type = basestring
@@ -406,7 +405,7 @@ class Expansion(BaseExpansion, list):
if len(a) != len(b): if len(a) != len(b):
return False return False
for i in range(len(self)): for i in xrange(len(self)):
e1, is_func1 = a[i] e1, is_func1 = a[i]
e2, is_func2 = b[i] e2, is_func2 = b[i]
@@ -448,7 +447,7 @@ class Variables(object):
self.parent = parent self.parent = parent
def readfromenvironment(self, env): def readfromenvironment(self, env):
for k, v in env.items(): for k, v in env.iteritems():
self.set(k, self.FLAVOR_RECURSIVE, self.SOURCE_ENVIRONMENT, v) self.set(k, self.FLAVOR_RECURSIVE, self.SOURCE_ENVIRONMENT, v)
def get(self, name, expand=True): def get(self, name, expand=True):
@@ -548,7 +547,7 @@ class Variables(object):
self.set(k, flavor, source, value) self.set(k, flavor, source, value)
def __iter__(self): def __iter__(self):
for k, (flavor, source, value, valueexp) in self._map.items(): for k, (flavor, source, value, valueexp) in self._map.iteritems():
yield k, flavor, source, value yield k, flavor, source, value
def __contains__(self, item): def __contains__(self, item):
@@ -865,7 +864,7 @@ class RemakeRuleContext(object):
assert error in (True, False) assert error in (True, False)
if error: if error:
print("<%s>: Found error" % self.target.target) print "<%s>: Found error" % self.target.target
self.error = True self.error = True
if didanything: if didanything:
self.didanything = True self.didanything = True
@@ -950,8 +949,8 @@ class RemakeRuleContext(object):
self.target.didanything = True self.target.didanything = True
try: try:
self.commands = [c for c in self.rule.getcommands(self.target, self.makefile)] self.commands = [c for c in self.rule.getcommands(self.target, self.makefile)]
except util.MakeError as e: except util.MakeError, e:
print(e) print e
sys.stdout.flush() sys.stdout.flush()
cb(error=True) cb(error=True)
return return
@@ -1284,9 +1283,9 @@ class Target(object):
try: try:
self.resolvedeps(makefile, targetstack, [], False) self.resolvedeps(makefile, targetstack, [], False)
except util.MakeError as e: except util.MakeError, e:
if printerror: if printerror:
print(e) print e
self.error = True self.error = True
self.notifydone(makefile) self.notifydone(makefile)
return return
@@ -1398,7 +1397,7 @@ class _CommandWrapper(object):
def _cb(self, res): def _cb(self, res):
if res != 0 and not self.ignoreErrors: if res != 0 and not self.ignoreErrors:
print("%s: command '%s' failed, return code %i" % (self.loc, self.cline, res)) print "%s: command '%s' failed, return code %i" % (self.loc, self.cline, res)
self.usercb(error=True) self.usercb(error=True)
else: else:
self.usercb(error=False) self.usercb(error=False)
@@ -1592,7 +1591,7 @@ class _RemakeContext(object):
assert error in (True, False) assert error in (True, False)
if error and self.required: if error and self.required:
print("Error remaking makefiles (ignored)") print "Error remaking makefiles (ignored)"
if len(self.toremake): if len(self.toremake):
target, self.required = self.toremake.pop(0) target, self.required = self.toremake.pop(0)
@@ -1679,7 +1678,7 @@ class Makefile(object):
self.variables.set('MAKECMDGOALS', Variables.FLAVOR_SIMPLE, self.variables.set('MAKECMDGOALS', Variables.FLAVOR_SIMPLE,
Variables.SOURCE_AUTOMATIC, ' '.join(targets)) Variables.SOURCE_AUTOMATIC, ' '.join(targets))
for vname, val in implicit.variables.items(): for vname, val in implicit.variables.iteritems():
self.variables.set(vname, self.variables.set(vname,
Variables.FLAVOR_SIMPLE, Variables.FLAVOR_SIMPLE,
Variables.SOURCE_IMPLICIT, val) Variables.SOURCE_IMPLICIT, val)
@@ -1751,10 +1750,11 @@ class Makefile(object):
if value is None: if value is None:
self._vpath = [] self._vpath = []
else: else:
self._vpath = [e for e in re.split('[%s\s]+' % os.pathsep, self._vpath = filter(lambda e: e != '',
value.resolvestr(self, self.variables, ['VPATH'])) if e != ''] re.split('[%s\s]+' % os.pathsep,
value.resolvestr(self, self.variables, ['VPATH'])))
targets = list(self._targets.values()) targets = list(self._targets.itervalues())
for t in targets: for t in targets:
t.explicit = True t.explicit = True
for r in t.rules: for r in t.rules:
@@ -1825,7 +1825,7 @@ class Makefile(object):
def getsubenvironment(self, variables): def getsubenvironment(self, variables):
env = dict(self.env) env = dict(self.env)
for vname, v in self.exportedvars.items(): for vname, v in self.exportedvars.iteritems():
if v: if v:
flavor, source, val = variables.get(vname) flavor, source, val = variables.get(vname)
if val is None: if val is None:
+11 -11
View File
@@ -2,10 +2,10 @@
Makefile functions. Makefile functions.
""" """
from . import parser, util import parser, util
import subprocess, os, logging, sys import subprocess, os, logging, sys
from .globrelative import glob from globrelative import glob
from io import StringIO from cStringIO import StringIO
log = logging.getLogger('pymake.data') log = logging.getLogger('pymake.data')
@@ -135,7 +135,7 @@ class Function(object):
if len(self._arguments) != len(other._arguments): if len(self._arguments) != len(other._arguments):
return False return False
for i in range(len(self._arguments)): for i in xrange(len(self._arguments)):
# According to the GNU make manual Section 8.1, whitespace around # According to the GNU make manual Section 8.1, whitespace around
# arguments is *not* part of the argument's value. So, we do a # arguments is *not* part of the argument's value. So, we do a
# whitespace-agnostic comparison. # whitespace-agnostic comparison.
@@ -525,7 +525,7 @@ class JoinFunction(Function):
@staticmethod @staticmethod
def iterjoin(l1, l2): def iterjoin(l1, l2):
for i in range(0, max(len(l1), len(l2))): for i in xrange(0, max(len(l1), len(l2))):
i1 = i < len(l1) and l1[i] or '' i1 = i < len(l1) and l1[i] or ''
i2 = i < len(l2) and l2[i] or '' i2 = i < len(l2) and l2[i] or ''
yield i1 + i2 yield i1 + i2
@@ -670,7 +670,7 @@ class CallFunction(Function):
v = data.Variables(parent=variables) v = data.Variables(parent=variables)
v.set('0', data.Variables.FLAVOR_SIMPLE, data.Variables.SOURCE_AUTOMATIC, vname) v.set('0', data.Variables.FLAVOR_SIMPLE, data.Variables.SOURCE_AUTOMATIC, vname)
for i in range(1, len(self._arguments)): for i in xrange(1, len(self._arguments)):
param = self._arguments[i].resolvestr(makefile, variables, setting) param = self._arguments[i].resolvestr(makefile, variables, setting)
v.set(str(i), data.Variables.FLAVOR_SIMPLE, data.Variables.SOURCE_AUTOMATIC, param) v.set(str(i), data.Variables.FLAVOR_SIMPLE, data.Variables.SOURCE_AUTOMATIC, param)
@@ -770,7 +770,7 @@ class ShellFunction(Function):
__slots__ = Function.__slots__ __slots__ = Function.__slots__
def resolve(self, makefile, variables, fd, setting): def resolve(self, makefile, variables, fd, setting):
from .process import prepare_command from process import prepare_command
cline = self._arguments[0].resolvestr(makefile, variables, setting) cline = self._arguments[0].resolvestr(makefile, variables, setting)
executable, cline = prepare_command(cline, makefile.workdir, self.loc) executable, cline = prepare_command(cline, makefile.workdir, self.loc)
@@ -785,8 +785,8 @@ class ShellFunction(Function):
try: try:
p = subprocess.Popen(cline, executable=executable, env=makefile.env, shell=False, p = subprocess.Popen(cline, executable=executable, env=makefile.env, shell=False,
stdout=subprocess.PIPE, cwd=makefile.workdir) stdout=subprocess.PIPE, cwd=makefile.workdir)
except OSError as e: except OSError, e:
print("Error executing command %s" % cline[0], e, file=sys.stderr) print >>sys.stderr, "Error executing command %s" % cline[0], e
return return
finally: finally:
os.environ['PATH'] = oldpath os.environ['PATH'] = oldpath
@@ -830,7 +830,7 @@ class InfoFunction(Function):
def resolve(self, makefile, variables, fd, setting): def resolve(self, makefile, variables, fd, setting):
v = self._arguments[0].resolvestr(makefile, variables, setting) v = self._arguments[0].resolvestr(makefile, variables, setting)
print(v) print v
functionmap = { functionmap = {
'subst': SubstFunction, 'subst': SubstFunction,
@@ -870,4 +870,4 @@ functionmap = {
'info': InfoFunction, 'info': InfoFunction,
} }
from . import data import data
+2 -2
View File
@@ -7,7 +7,7 @@ Filename globbing like the python glob module with minor differences:
""" """
import os, re, fnmatch import os, re, fnmatch
from . import util import util
_globcheck = re.compile('[[*?]') _globcheck = re.compile('[[*?]')
@@ -62,7 +62,7 @@ def globpattern(dir, pattern):
if not leaf.startswith('.')] if not leaf.startswith('.')]
leaves = fnmatch.filter(leaves, pattern) leaves = fnmatch.filter(leaves, pattern)
leaves = [l for l in leaves if os.path.exists(util.normaljoin(dir, l))] leaves = filter(lambda l: os.path.exists(util.normaljoin(dir, l)), leaves)
leaves.sort() leaves.sort()
return leaves return leaves
+4 -4
View File
@@ -34,7 +34,7 @@ coming.
""" """
import logging, re, os, sys import logging, re, os, sys
from . import data, functions, util, parserdata import data, functions, util, parserdata
_log = logging.getLogger('pymake.parser') _log = logging.getLogger('pymake.parser')
@@ -108,7 +108,7 @@ _alltokens = re.compile(r'''\\*\# | # hash mark preceeded by any number of backs
:: | :: |
(?:\$(?:$|[\(\{](?:%s)\s+|.)) | # dollar sign followed by EOF, a function keyword with whitespace, or any character (?:\$(?:$|[\(\{](?:%s)\s+|.)) | # dollar sign followed by EOF, a function keyword with whitespace, or any character
:(?![\\/]) | # colon followed by anything except a slash (Windows path detection) :(?![\\/]) | # colon followed by anything except a slash (Windows path detection)
[=#{}();,|'"]''' % '|'.join(iter(functions.functionmap.keys())), re.VERBOSE) [=#{}();,|'"]''' % '|'.join(functions.functionmap.iterkeys()), re.VERBOSE)
def iterdata(d, offset, tokenlist, it): def iterdata(d, offset, tokenlist, it):
""" """
@@ -336,7 +336,7 @@ _conditionkeywords = {
'ifndef': ifndef 'ifndef': ifndef
} }
_conditiontokens = tuple(_conditionkeywords.keys()) _conditiontokens = tuple(_conditionkeywords.iterkeys())
_conditionre = re.compile(r'(%s)(?:$|\s+)' % '|'.join(_conditiontokens)) _conditionre = re.compile(r'(%s)(?:$|\s+)' % '|'.join(_conditiontokens))
_directivestokenlist = _conditiontokens + \ _directivestokenlist = _conditiontokens + \
@@ -691,7 +691,7 @@ def parsemakesyntax(d, offset, stopon, iterfunc):
while True: # this is not a for loop because `di` changes during the function while True: # this is not a for loop because `di` changes during the function
assert stacktop is not None assert stacktop is not None
try: try:
s, token, tokenoffset, offset = next(di) s, token, tokenoffset, offset = di.next()
except StopIteration: except StopIteration:
break break
+19 -19
View File
@@ -1,6 +1,6 @@
import logging, re, os import logging, re, os
from . import data, parser, functions, util import data, parser, functions, util
from io import StringIO from cStringIO import StringIO
from pymake.globrelative import hasglob, glob from pymake.globrelative import hasglob, glob
_log = logging.getLogger('pymake.data') _log = logging.getLogger('pymake.data')
@@ -76,7 +76,7 @@ def parsecommandlineargs(args):
overrides = [] overrides = []
stmts = StatementList() stmts = StatementList()
r = [] r = []
for i in range(0, len(args)): for i in xrange(0, len(args)):
a = args[i] a = args[i]
vname, t, val = util.strpartition(a, ':=') vname, t, val = util.strpartition(a, ':=')
@@ -195,7 +195,7 @@ class Rule(Statement):
deps = list(_expandwildcards(makefile, data.stripdotslashes(self.depexp.resolvesplit(makefile, makefile.variables)))) deps = list(_expandwildcards(makefile, data.stripdotslashes(self.depexp.resolvesplit(makefile, makefile.variables))))
if ispattern: if ispattern:
rule = data.PatternRule(targets, list(map(data.Pattern, deps)), self.doublecolon, loc=self.targetexp.loc) rule = data.PatternRule(targets, map(data.Pattern, deps), self.doublecolon, loc=self.targetexp.loc)
makefile.appendimplicitrule(rule) makefile.appendimplicitrule(rule)
else: else:
rule = data.Rule(deps, self.doublecolon, loc=self.targetexp.loc, weakdeps=False) rule = data.Rule(deps, self.doublecolon, loc=self.targetexp.loc, weakdeps=False)
@@ -207,7 +207,7 @@ class Rule(Statement):
context.currule = rule context.currule = rule
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sRule %s: %s" % (indent, self.targetexp, self.depexp), file=fd) print >>fd, "%sRule %s: %s" % (indent, self.targetexp, self.depexp)
def to_source(self): def to_source(self):
sep = ':' sep = ':'
@@ -285,7 +285,7 @@ class StaticPatternRule(Statement):
context.currule = rule context.currule = rule
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sStaticPatternRule %s: %s: %s" % (indent, self.targetexp, self.patternexp, self.depexp), file=fd) print >>fd, "%sStaticPatternRule %s: %s: %s" % (indent, self.targetexp, self.patternexp, self.depexp)
def to_source(self): def to_source(self):
sep = ':' sep = ':'
@@ -339,7 +339,7 @@ class Command(Statement):
context.currule.addcommand(self.exp) context.currule.addcommand(self.exp)
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sCommand %s" % (indent, self.exp,), file=fd) print >>fd, "%sCommand %s" % (indent, self.exp,)
def to_source(self): def to_source(self):
# Commands have some interesting quirks when it comes to source # Commands have some interesting quirks when it comes to source
@@ -438,7 +438,7 @@ class SetVariable(Statement):
v.set(vname, flavor, self.source, value) v.set(vname, flavor, self.source, value)
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sSetVariable<%s> %s %s\n%s %r" % (indent, self.valueloc, self.vnameexp, self.token, indent, self.value), file=fd) print >>fd, "%sSetVariable<%s> %s %s\n%s %r" % (indent, self.valueloc, self.vnameexp, self.token, indent, self.value)
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, SetVariable): if not isinstance(other, SetVariable):
@@ -452,7 +452,7 @@ class SetVariable(Statement):
def to_source(self): def to_source(self):
chars = [] chars = []
for i in range(0, len(self.value)): for i in xrange(0, len(self.value)):
c = self.value[i] c = self.value[i]
# Literal # is escaped in variable assignment otherwise it would be # Literal # is escaped in variable assignment otherwise it would be
@@ -651,14 +651,14 @@ class ConditionBlock(Statement):
i += 1 i += 1
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sConditionBlock" % (indent,), file=fd) print >>fd, "%sConditionBlock" % (indent,)
indent2 = indent + ' ' indent2 = indent + ' '
for c, statements in self._groups: for c, statements in self._groups:
print("%s Condition %s" % (indent, c), file=fd) print >>fd, "%s Condition %s" % (indent, c)
statements.dump(fd, indent2) statements.dump(fd, indent2)
print("%s ~Condition" % (indent,), file=fd) print >>fd, "%s ~Condition" % (indent,)
print("%s~ConditionBlock" % (indent,), file=fd) print >>fd, "%s~ConditionBlock" % (indent,)
def to_source(self): def to_source(self):
lines = [] lines = []
@@ -681,7 +681,7 @@ class ConditionBlock(Statement):
if len(self) != len(other): if len(self) != len(other):
return False return False
for i in range(0, len(self)): for i in xrange(0, len(self)):
our_condition, our_statements = self[i] our_condition, our_statements = self[i]
other_condition, other_statements = other[i] other_condition, other_statements = other[i]
@@ -793,7 +793,7 @@ class Include(Statement):
makefile.include(f, self.required, loc=self.exp.loc, weak=self.weak) makefile.include(f, self.required, loc=self.exp.loc, weak=self.weak)
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sInclude %s" % (indent, self.exp), file=fd) print >>fd, "%sInclude %s" % (indent, self.exp)
def to_source(self): def to_source(self):
prefix = '' prefix = ''
@@ -840,7 +840,7 @@ class VPathDirective(Statement):
makefile.addvpath(pattern, dirs) makefile.addvpath(pattern, dirs)
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sVPath %s" % (indent, self.exp), file=fd) print >>fd, "%sVPath %s" % (indent, self.exp)
def to_source(self): def to_source(self):
return 'vpath %s' % self.exp.to_source() return 'vpath %s' % self.exp.to_source()
@@ -885,7 +885,7 @@ class ExportDirective(Statement):
makefile.exportedvars[v] = True makefile.exportedvars[v] = True
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sExport (single=%s) %s" % (indent, self.single, self.exp), file=fd) print >>fd, "%sExport (single=%s) %s" % (indent, self.single, self.exp)
def to_source(self): def to_source(self):
return ('export %s' % self.exp.to_source()).rstrip() return ('export %s' % self.exp.to_source()).rstrip()
@@ -915,7 +915,7 @@ class UnexportDirective(Statement):
makefile.exportedvars[v] = False makefile.exportedvars[v] = False
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sUnexport %s" % (indent, self.exp), file=fd) print >>fd, "%sUnexport %s" % (indent, self.exp)
def to_source(self): def to_source(self):
return 'unexport %s' % self.exp.to_source() return 'unexport %s' % self.exp.to_source()
@@ -947,7 +947,7 @@ class EmptyDirective(Statement):
raise data.DataError("Line expands to non-empty value", self.exp.loc) raise data.DataError("Line expands to non-empty value", self.exp.loc)
def dump(self, fd, indent): def dump(self, fd, indent):
print("%sEmptyDirective: %s" % (indent, self.exp), file=fd) print >>fd, "%sEmptyDirective: %s" % (indent, self.exp)
def to_source(self): def to_source(self):
return self.exp.to_source() return self.exp.to_source()
+25 -25
View File
@@ -10,9 +10,9 @@ import site
from collections import deque from collections import deque
# XXXkhuey Work around http://bugs.python.org/issue1731717 # XXXkhuey Work around http://bugs.python.org/issue1731717
subprocess._cleanup = lambda: None subprocess._cleanup = lambda: None
from . import command, util import command, util
if sys.platform=='win32': if sys.platform=='win32':
from . import win32process import win32process
_log = logging.getLogger('pymake.process') _log = logging.getLogger('pymake.process')
@@ -28,7 +28,7 @@ def tokens2re(tokens):
# which matches the pattern and captures it in a named match group. # which matches the pattern and captures it in a named match group.
# The group names and patterns come are given as a dict in the function # The group names and patterns come are given as a dict in the function
# argument. # argument.
nonescaped = r'(?<!\\)(?:%s)' % '|'.join('(?P<%s>%s)' % (name, value) for name, value in tokens.items()) nonescaped = r'(?<!\\)(?:%s)' % '|'.join('(?P<%s>%s)' % (name, value) for name, value in tokens.iteritems())
# The final pattern matches either the above pattern, or an escaped # The final pattern matches either the above pattern, or an escaped
# backslash, captured in the "escape" match group. # backslash, captured in the "escape" match group.
return re.compile('(?:%s|%s)' % (nonescaped, r'(?P<escape>\\\\)')) return re.compile('(?:%s|%s)' % (nonescaped, r'(?P<escape>\\\\)'))
@@ -115,7 +115,7 @@ class ClineSplitter(list):
self._push(self.cline[:m.start()]) self._push(self.cline[:m.start()])
self.cline = self.cline[m.end():] self.cline = self.cline[m.end():]
match = dict([(name, value) for name, value in list(m.groupdict().items()) if value]) match = dict([(name, value) for name, value in m.groupdict().items() if value])
if 'quote' in match: if 'quote' in match:
# " or ' start a quoted string # " or ' start a quoted string
if match['quote'] == '"': if match['quote'] == '"':
@@ -129,7 +129,7 @@ class ClineSplitter(list):
elif 'special' in match: elif 'special' in match:
# Unquoted, non-escaped special characters need to be sent to a # Unquoted, non-escaped special characters need to be sent to a
# shell. # shell.
raise MetaCharacterException(match['special']) raise MetaCharacterException, match['special']
elif 'whitespace' in match: elif 'whitespace' in match:
# Whitespaces terminate current argument. # Whitespaces terminate current argument.
self._next() self._next()
@@ -145,7 +145,7 @@ class ClineSplitter(list):
self.glob = True self.glob = True
self._push(m.group(0)) self._push(m.group(0))
else: else:
raise Exception("Shouldn't reach here") raise Exception, "Shouldn't reach here"
if self.arg: if self.arg:
self._next() self._next()
@@ -153,20 +153,20 @@ class ClineSplitter(list):
# Single quoted strings are preserved, except for the final quote # Single quoted strings are preserved, except for the final quote
index = self.cline.find("'") index = self.cline.find("'")
if index == -1: if index == -1:
raise Exception('Unterminated quoted string in command') raise Exception, 'Unterminated quoted string in command'
self._push(self.cline[:index]) self._push(self.cline[:index])
self.cline = self.cline[index+1:] self.cline = self.cline[index+1:]
def _parse_doubly_quoted(self): def _parse_doubly_quoted(self):
if not self.cline: if not self.cline:
raise Exception('Unterminated quoted string in command') raise Exception, 'Unterminated quoted string in command'
while self.cline: while self.cline:
m = _doubly_quoted_tokens.search(self.cline) m = _doubly_quoted_tokens.search(self.cline)
if not m: if not m:
raise Exception('Unterminated quoted string in command') raise Exception, 'Unterminated quoted string in command'
self._push(self.cline[:m.start()]) self._push(self.cline[:m.start()])
self.cline = self.cline[m.end():] self.cline = self.cline[m.end():]
match = dict([(name, value) for name, value in list(m.groupdict().items()) if value]) match = dict([(name, value) for name, value in m.groupdict().items() if value])
if 'quote' in match: if 'quote' in match:
# a double quote ends the quoted string, so go back to # a double quote ends the quoted string, so go back to
# unquoted parsing # unquoted parsing
@@ -175,7 +175,7 @@ class ClineSplitter(list):
# Unquoted, non-escaped special characters in a doubly quoted # Unquoted, non-escaped special characters in a doubly quoted
# string still have a special meaning and need to be sent to a # string still have a special meaning and need to be sent to a
# shell. # shell.
raise MetaCharacterException(match['special']) raise MetaCharacterException, match['special']
elif 'escape' in match: elif 'escape' in match:
# Escaped backslashes turn into a single backslash # Escaped backslashes turn into a single backslash
self._push('\\') self._push('\\')
@@ -194,7 +194,7 @@ def clinetoargv(cline, cwd):
str = _escapednewlines.sub('', cline) str = _escapednewlines.sub('', cline)
try: try:
args = ClineSplitter(str, cwd) args = ClineSplitter(str, cwd)
except MetaCharacterException as e: except MetaCharacterException, e:
return None, e.char return None, e.char
if len(args) and args[0].find('=') != -1: if len(args) and args[0].find('=') != -1:
@@ -327,12 +327,12 @@ class PopenJob(Job):
# general overview of "subprocess PATH semantics and portability". # general overview of "subprocess PATH semantics and portability".
oldpath = os.environ['PATH'] oldpath = os.environ['PATH']
try: try:
if self.env is not None and 'PATH' in self.env: if self.env is not None and self.env.has_key('PATH'):
os.environ['PATH'] = self.env['PATH'] os.environ['PATH'] = self.env['PATH']
p = subprocess.Popen(self.argv, executable=self.executable, shell=self.shell, env=self.env, cwd=self.cwd) p = subprocess.Popen(self.argv, executable=self.executable, shell=self.shell, env=self.env, cwd=self.cwd)
return p.wait() return p.wait()
except OSError as e: except OSError, e:
print(e, file=sys.stderr) print >>sys.stderr, e
return -127 return -127
finally: finally:
os.environ['PATH'] = oldpath os.environ['PATH'] = oldpath
@@ -383,30 +383,30 @@ class PythonJob(Job):
try: try:
__import__(self.module) __import__(self.module)
except Exception as e: except Exception as e:
print('Error importing %s: %s' % ( print >>sys.stderr, 'Error importing %s: %s' % (
self.module, e), file=sys.stderr) self.module, e)
return -127 return -127
m = sys.modules[self.module] m = sys.modules[self.module]
if self.method not in m.__dict__: if self.method not in m.__dict__:
print("No method named '%s' in module %s" % (self.method, self.module), file=sys.stderr) print >>sys.stderr, "No method named '%s' in module %s" % (self.method, self.module)
return -127 return -127
rv = m.__dict__[self.method](self.argv) rv = m.__dict__[self.method](self.argv)
if rv != 0 and rv is not None: if rv != 0 and rv is not None:
print(( print >>sys.stderr, (
"Native command '%s %s' returned value '%s'" % "Native command '%s %s' returned value '%s'" %
(self.module, self.method, rv)), file=sys.stderr) (self.module, self.method, rv))
return (rv if isinstance(rv, int) else 1) return (rv if isinstance(rv, int) else 1)
except PythonException as e: except PythonException, e:
print(e, file=sys.stderr) print >>sys.stderr, e
return e.exitcode return e.exitcode
except: except:
e = sys.exc_info()[1] e = sys.exc_info()[1]
if isinstance(e, SystemExit) and (e.code == 0 or e.code is None): if isinstance(e, SystemExit) and (e.code == 0 or e.code is None):
pass # sys.exit(0) is not a failure pass # sys.exit(0) is not a failure
else: else:
print(e, file=sys.stderr) print >>sys.stderr, e
traceback.print_exc() traceback.print_exc()
return -127 return -127
finally: finally:
@@ -461,7 +461,7 @@ class ParallelContext(object):
def _docall_generic(self, pool, job, cb, echo, justprint): def _docall_generic(self, pool, job, cb, echo, justprint):
if echo is not None: if echo is not None:
print(echo) print echo
processcb = job.get_callback(ParallelContext._condition) processcb = job.get_callback(ParallelContext._condition)
if justprint: if justprint:
processcb(0) processcb(0)
@@ -491,7 +491,7 @@ class ParallelContext(object):
def _checkdone(): def _checkdone():
jobs = [] jobs = []
for c in ParallelContext._allcontexts: for c in ParallelContext._allcontexts:
for i in range(0, len(c.running)): for i in xrange(0, len(c.running)):
if c.running[i][0].done: if c.running[i][0].done:
jobs.append(c.running[i]) jobs.append(c.running[i])
for j in jobs: for j in jobs:
+2 -2
View File
@@ -82,7 +82,7 @@ else:
return str[:offset], token, str[offset + len(token):] return str[:offset], token, str[offset + len(token):]
try: try:
from builtins import any from __builtin__ import any
except ImportError: except ImportError:
def any(it): def any(it):
for i in it: for i in it:
@@ -138,7 +138,7 @@ class MostUsedCache(object):
return item.o return item.o
def verify(self): def verify(self):
for k, v in self.d.items(): for k, v in self.d.iteritems():
if v.o: if v.o:
assert v in self.active assert v in self.active
else: else:
+3 -3
View File
@@ -1,10 +1,10 @@
import pymake.data, pymake.functions, pymake.util import pymake.data, pymake.functions, pymake.util
import unittest import unittest
import re import re
from io import StringIO from cStringIO import StringIO
def multitest(cls): def multitest(cls):
for name in cls.testdata.keys(): for name in cls.testdata.iterkeys():
def m(self, name=name): def m(self, name=name):
return self.runSingle(*self.testdata[name]) return self.runSingle(*self.testdata[name])
@@ -63,7 +63,7 @@ class LRUTest(unittest.TestCase):
c = pymake.util.LRUCache(3, self.spaceFunc, lambda k, v: k % 2) c = pymake.util.LRUCache(3, self.spaceFunc, lambda k, v: k % 2)
self.assertEqual(tuple(c.debugitems()), ()) self.assertEqual(tuple(c.debugitems()), ())
for i in range(0, len(self.expected)): for i in xrange(0, len(self.expected)):
k, e, fc, di = self.expected[i] k, e, fc, di = self.expected[i]
v = c.get(k) v = c.get(k)
+1 -1
View File
@@ -277,7 +277,7 @@ class MakefileCorupusTest(TestBase):
self.assertEqual(len(statements), len(new_statements)) self.assertEqual(len(statements), len(new_statements))
for i in range(0, len(statements)): for i in xrange(0, len(statements)):
original = statements[i] original = statements[i]
formatted = new_statements[i] formatted = new_statements[i]
+6 -6
View File
@@ -2,10 +2,10 @@ import pymake.data, pymake.parser, pymake.parserdata, pymake.functions
import unittest import unittest
import logging import logging
from io import StringIO from cStringIO import StringIO
def multitest(cls): def multitest(cls):
for name in cls.testdata.keys(): for name in cls.testdata.iterkeys():
def m(self, name=name): def m(self, name=name):
return self.runSingle(*self.testdata[name]) return self.runSingle(*self.testdata[name])
@@ -134,7 +134,7 @@ class IterTest(TestBase):
self.assertEqual(actual, expected) self.assertEqual(actual, expected)
if ifunc == pymake.parser.itermakefilechars: if ifunc == pymake.parser.itermakefilechars:
print("testing %r" % expected) print "testing %r" % expected
self.assertEqual(pymake.parser.flattenmakesyntax(d, 0), expected) self.assertEqual(pymake.parser.flattenmakesyntax(d, 0), expected)
multitest(IterTest) multitest(IterTest)
@@ -207,7 +207,7 @@ class MakeSyntaxTest(TestBase):
def compareRecursive(self, actual, expected, path): def compareRecursive(self, actual, expected, path):
self.assertEqual(len(actual), len(expected), self.assertEqual(len(actual), len(expected),
"compareRecursive: %s %r" % (path, actual)) "compareRecursive: %s %r" % (path, actual))
for i in range(0, len(actual)): for i in xrange(0, len(actual)):
ipath = path + [i] ipath = path + [i]
a, isfunc = actual[i] a, isfunc = actual[i]
@@ -217,7 +217,7 @@ class MakeSyntaxTest(TestBase):
else: else:
self.assertEqual(type(a), getattr(pymake.functions, e['type']), self.assertEqual(type(a), getattr(pymake.functions, e['type']),
"compareRecursive: %s" % (ipath,)) "compareRecursive: %s" % (ipath,))
for k, v in e.items(): for k, v in e.iteritems():
if k == 'type': if k == 'type':
pass pass
elif k[0] == '[': elif k[0] == '[':
@@ -264,7 +264,7 @@ class VariableTest(TestBase):
m = pymake.data.Makefile() m = pymake.data.Makefile()
stmts.execute(m) stmts.execute(m)
for k, v in self.expected.items(): for k, v in self.expected.iteritems():
flavor, source, val = m.variables.get(k) flavor, source, val = m.variables.get(k)
if val is None: if val is None:
self.assertEqual(val, v, 'variable named %s' % k) self.assertEqual(val, v, 'variable named %s' % k)
+13 -13
View File
@@ -63,7 +63,7 @@ def runTest(makefile, make, logfile, options):
""" """
if os.path.exists(opts.tempdir): shutil.rmtree(opts.tempdir) if os.path.exists(opts.tempdir): shutil.rmtree(opts.tempdir)
os.mkdir(opts.tempdir, 0o755) os.mkdir(opts.tempdir, 0755)
logfd = open(logfile, 'w') logfd = open(logfile, 'w')
p = Popen(make + options['commandline'], stdout=logfd, stderr=STDOUT, env=options['env']) p = Popen(make + options['commandline'], stdout=logfd, stderr=STDOUT, env=options['env'])
@@ -78,15 +78,15 @@ def runTest(makefile, make, logfile, options):
logfd.close() logfd.close()
if stdout.find('TEST-FAIL') != -1: if stdout.find('TEST-FAIL') != -1:
print(stdout) print stdout
return False, "FAIL (TEST-FAIL printed)" return False, "FAIL (TEST-FAIL printed)"
if options['grepfor'] and stdout.find(options['grepfor']) == -1: if options['grepfor'] and stdout.find(options['grepfor']) == -1:
print(stdout) print stdout
return False, "FAIL (%s not in output)" % options['grepfor'] return False, "FAIL (%s not in output)" % options['grepfor']
if options['returncode'] == 0 and stdout.find('TEST-PASS') == -1: if options['returncode'] == 0 and stdout.find('TEST-PASS') == -1:
print(stdout) print stdout
return False, 'FAIL (No TEST-PASS printed)' return False, 'FAIL (No TEST-PASS printed)'
if options['returncode'] != 0: if options['returncode'] != 0:
@@ -94,7 +94,7 @@ def runTest(makefile, make, logfile, options):
return True, 'PASS' return True, 'PASS'
print("%-30s%-28s%-28s" % ("Test:", "gmake:", "pymake:")) print "%-30s%-28s%-28s" % ("Test:", "gmake:", "pymake:")
gmakefails = 0 gmakefails = 0
pymakefails = 0 pymakefails = 0
@@ -144,7 +144,7 @@ for makefile in makefiles:
if sys.platform in data: if sys.platform in data:
d['returncode'] = data[sys.platform] d['returncode'] = data[sys.platform]
elif key == 'environment': elif key == 'environment':
for k, v in data.items(): for k, v in data.iteritems():
d['env'][k] = v d['env'][k] = v
elif key == 'grep-for': elif key == 'grep-for':
d['grepfor'] = data d['grepfor'] = data
@@ -153,7 +153,7 @@ for makefile in makefiles:
elif key == 'skip': elif key == 'skip':
d['skip'] = True d['skip'] = True
else: else:
print("%s: Unexpected #T key: %s" % (makefile, key), file=sys.stderr) print >>sys.stderr, "%s: Unexpected #T key: %s" % (makefile, key)
sys.exit(1) sys.exit(1)
mdata.close() mdata.close()
@@ -190,12 +190,12 @@ for makefile in makefiles:
else: else:
pymakemsg = "OK (known fail)" pymakemsg = "OK (known fail)"
print("%-30.30s%-28.28s%-28.28s" % (os.path.basename(makefile), print "%-30.30s%-28.28s%-28.28s" % (os.path.basename(makefile),
gmakemsg, pymakemsg)) gmakemsg, pymakemsg)
print() print
print("Summary:") print "Summary:"
print("%-30s%-28s%-28s" % ("", "gmake:", "pymake:")) print "%-30s%-28s%-28s" % ("", "gmake:", "pymake:")
if gmakefails == 0: if gmakefails == 0:
gmakemsg = 'PASS' gmakemsg = 'PASS'
@@ -207,7 +207,7 @@ if pymakefails == 0:
else: else:
pymakemsg = 'FAIL (%i failures)' % pymakefails pymakemsg = 'FAIL (%i failures)' % pymakefails
print("%-30.30s%-28.28s%-28.28s" % ('', gmakemsg, pymakemsg)) print "%-30.30s%-28.28s%-28.28s" % ('', gmakemsg, pymakemsg)
shutil.rmtree(opts.tempdir) shutil.rmtree(opts.tempdir)
+5 -5
View File
@@ -4,7 +4,7 @@ from os import path
import re import re
import shutil import shutil
import sys import sys
from urllib.request import urlopen from urllib2 import urlopen
from release.paths import makeCandidatesDir from release.paths import makeCandidatesDir
@@ -50,7 +50,7 @@ def findOldBuildIDs(product, version, buildNumber, platforms,
id = getBuildID(platform, product, version, n, nightlyDir, id = getBuildID(platform, product, version, n, nightlyDir,
server) server)
ids[platform].append(id) ids[platform].append(id)
except Exception as e: except Exception, e:
log.error("Hit exception: %s" % e) log.error("Hit exception: %s" % e)
return ids return ids
@@ -87,10 +87,10 @@ def readBranchConfig(dir, localconfig, branch, required=[]):
def readConfig(configfile, keys=[], required=[]): def readConfig(configfile, keys=[], required=[]):
c = {} c = {}
exec(compile(open(configfile, "rb").read(), configfile, 'exec'), c) execfile(configfile, c)
for k in keys: for k in keys:
c = c[k] c = c[k]
items = list(c.keys()) items = c.keys()
err = False err = False
for key in required: for key in required:
if key not in items: if key not in items:
@@ -137,7 +137,7 @@ def getReleaseName(product, version, buildNumber):
def getRepoMatchingBranch(branch, sourceRepositories): def getRepoMatchingBranch(branch, sourceRepositories):
for sr in list(sourceRepositories.values()): for sr in sourceRepositories.values():
if branch in sr['path']: if branch in sr['path']:
return sr return sr
return None return None
+1 -1
View File
@@ -1,7 +1,7 @@
import difflib import difflib
import logging import logging
import re import re
import urllib.request, urllib.error, urllib.parse import urllib2
from util.commands import run_cmd, get_output from util.commands import run_cmd, get_output
from util.hg import get_repo_name, make_hg_url from util.hg import get_repo_name, make_hg_url
from subprocess import CalledProcessError from subprocess import CalledProcessError
+24 -29
View File
@@ -13,11 +13,9 @@ import re
import subprocess import subprocess
import sys import sys
import pickle import pickle
from locale import getpreferredencoding
import mozpack.path as mozpath import mozpack.path as mozpath
encoding = getpreferredencoding(False)
class Pool(object): class Pool(object):
def __new__(cls, size): def __new__(cls, size):
@@ -29,7 +27,7 @@ class Pool(object):
return super(Pool, cls).__new__(cls) return super(Pool, cls).__new__(cls)
def imap_unordered(self, fn, iterable): def imap_unordered(self, fn, iterable):
return map(fn, iterable) return itertools.imap(fn, iterable)
def close(self): def close(self):
pass pass
@@ -62,7 +60,7 @@ class File(object):
modified = True modified = True
if os.path.exists(self._path): if os.path.exists(self._path):
if open(self._path, 'r', encoding=encoding, errors='replace').read() == self._content: if open(self._path, 'rb').read() == self._content:
modified = False modified = False
self._modified = modified self._modified = modified
return modified return modified
@@ -133,11 +131,11 @@ def maybe_clear_cache(data):
is_set = cache.get('ac_cv_env_%s_set' % precious) == 'set' is_set = cache.get('ac_cv_env_%s_set' % precious) == 'set'
value = cache.get('ac_cv_env_%s_value' % precious) if is_set else None value = cache.get('ac_cv_env_%s_value' % precious) if is_set else None
if value != env.get(precious): if value != env.get(precious):
print('Removing %s because of %s value change from:' \ print 'Removing %s because of %s value change from:' \
% (data['cache-file'], precious)) % (data['cache-file'], precious)
print(' %s' % (value if value is not None else 'undefined')) print ' %s' % (value if value is not None else 'undefined')
print('to:') print 'to:'
print(' %s' % env.get(precious, 'undefined')) print ' %s' % env.get(precious, 'undefined')
os.remove(data['cache-file']) os.remove(data['cache-file'])
return True return True
return False return False
@@ -162,11 +160,9 @@ def get_config_files(data):
# Scan the config.status output for information about configuration files # Scan the config.status output for information about configuration files
# it generates. # it generates.
raw_output = subprocess.check_output( config_status_output = subprocess.check_output(
[data['shell'], '-c', '%s --help' % config_status], [data['shell'], '-c', '%s --help' % config_status],
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT).splitlines()
config_status_output = raw_output.decode(encoding,
errors='replace').splitlines()
state = None state = None
for line in config_status_output: for line in config_status_output:
if line.startswith('Configuration') and line.endswith(':'): if line.startswith('Configuration') and line.endswith(':'):
@@ -187,6 +183,7 @@ def get_config_files(data):
return config_files, command_files return config_files, command_files
def prepare(srcdir, objdir, shell, args): def prepare(srcdir, objdir, shell, args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--target', type=str) parser.add_argument('--target', type=str)
@@ -235,7 +232,7 @@ def prepare(srcdir, objdir, shell, args):
'args': others, 'args': others,
'shell': shell, 'shell': shell,
'srcdir': srcdir, 'srcdir': srcdir,
'env': {str(k): str(v) for k, v in environ.items()}, 'env': environ,
} }
if args.cache_file: if args.cache_file:
@@ -252,9 +249,9 @@ def prepare(srcdir, objdir, shell, args):
except OSError as e: except OSError as e:
if e.errno != errno.EEXIST: if e.errno != errno.EEXIST:
raise raise
for k, v in data.items():
with open(data_file, 'wb') as f: with open(data_file, 'wb') as f:
pickle.dump(data, f) pickle.dump(data, f)
def prefix_lines(text, prefix): def prefix_lines(text, prefix):
@@ -264,6 +261,7 @@ def prefix_lines(text, prefix):
def run(objdir): def run(objdir):
ret = 0 ret = 0
output = '' output = ''
with open(os.path.join(objdir, CONFIGURE_DATA), 'rb') as f: with open(os.path.join(objdir, CONFIGURE_DATA), 'rb') as f:
data = pickle.load(f) data = pickle.load(f)
@@ -335,16 +333,14 @@ def run(objdir):
# We're going to run it ourselves. # We're going to run it ourselves.
command += ['--no-create'] command += ['--no-create']
print(prefix_lines('configuring', relobjdir)) print prefix_lines('configuring', relobjdir)
print(prefix_lines('running %s' % ' '.join(command[:-1]), relobjdir)) print prefix_lines('running %s' % ' '.join(command[:-1]), relobjdir)
sys.stdout.flush() sys.stdout.flush()
try: try:
raw_output = subprocess.check_output(command, output += subprocess.check_output(command,
stderr=subprocess.STDOUT, cwd=objdir, env=data['env']) stderr=subprocess.STDOUT, cwd=objdir, env=data['env'])
output += raw_output.decode(encoding, errors='replace')
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
err = e.output.decode(encoding, errors='replace') return relobjdir, e.returncode, e.output
return relobjdir, e.returncode, err
# Leave config.status with a new timestamp if configure is newer than # Leave config.status with a new timestamp if configure is newer than
# its original mtime. # its original mtime.
@@ -372,13 +368,12 @@ def run(objdir):
if not skip_config_status: if not skip_config_status:
if skip_configure: if skip_configure:
print(prefix_lines('running config.status', relobjdir)) print prefix_lines('running config.status', relobjdir)
sys.stdout.flush() sys.stdout.flush()
try: try:
raw_output = subprocess.check_output([data['shell'], '-c', output += subprocess.check_output([data['shell'], '-c',
'./config.status'], stderr=subprocess.STDOUT, cwd=objdir, './config.status'], stderr=subprocess.STDOUT, cwd=objdir,
env=data['env']) env=data['env'])
output += raw_output.decode(encoding, errors='replace')
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
ret = e.returncode ret = e.returncode
output += e.output output += e.output
@@ -400,9 +395,9 @@ def subconfigure(args):
args, others = parser.parse_known_args(args) args, others = parser.parse_known_args(args)
subconfigures = args.subconfigures subconfigures = args.subconfigures
if args.list: if args.list:
subconfigures.extend(open(args.list, 'r', encoding=encoding, errors='replace').read().splitlines()) subconfigures.extend(open(args.list, 'rb').read().splitlines())
if args.skip: if args.skip:
skips = set(open(args.skip, 'r', encoding=encoding, errors='replace').read().splitlines()) skips = set(open(args.skip, 'rb').read().splitlines())
subconfigures = [s for s in subconfigures if s not in skips] subconfigures = [s for s in subconfigures if s not in skips]
if not subconfigures: if not subconfigures:
@@ -415,7 +410,7 @@ def subconfigure(args):
pool = Pool(len(subconfigures)) pool = Pool(len(subconfigures))
for relobjdir, returncode, output in \ for relobjdir, returncode, output in \
pool.imap_unordered(run, subconfigures): pool.imap_unordered(run, subconfigures):
print(prefix_lines(output, relobjdir)) print prefix_lines(output, relobjdir)
sys.stdout.flush() sys.stdout.flush()
ret = max(returncode, ret) ret = max(returncode, ret)
if ret: if ret:
+21
View File
@@ -8,6 +8,9 @@ def Binary():
'''Generic template for target binaries. Meant to be used by other '''Generic template for target binaries. Meant to be used by other
templates.''' templates.'''
if CONFIG['MOZ_LIBSTDCXX_TARGET_VERSION']:
USE_LIBS += ['stdc++compat']
# Ideally, we'd support not adding this to the LIB_IS_C_ONLY case, # Ideally, we'd support not adding this to the LIB_IS_C_ONLY case,
# but that variable is actually only set in db/sqlite/src, which # but that variable is actually only set in db/sqlite/src, which
# doesn't build a shared library on the relevant platforms anyways. # doesn't build a shared library on the relevant platforms anyways.
@@ -74,11 +77,27 @@ def Framework(name):
IS_FRAMEWORK = True IS_FRAMEWORK = True
@template
def HostStdCppCompat():
'''Template for libstdc++ compatibility for host binaries.'''
if CONFIG['MOZ_LIBSTDCXX_HOST_VERSION']:
HOST_USE_LIBS += ['host_stdc++compat']
@template @template
def HostProgram(name, c_only=False): def HostProgram(name, c_only=False):
'''Template for build tools executables.''' '''Template for build tools executables.'''
HOST_PROGRAM = name HOST_PROGRAM = name
# With context-based templates, this won't be needed anymore, and will
# work better than relying on the caller setting it, but at the moment,
# this is the best we have. And it doesn't matter /that/ much, so there's
# really only one place using this, where it does matter to avoid the
# extra dependency (because it creates a circular one).
if not c_only:
HostStdCppCompat()
@template @template
def HostSimplePrograms(names, ext='.cpp'): def HostSimplePrograms(names, ext='.cpp'):
@@ -90,6 +109,8 @@ def HostSimplePrograms(names, ext='.cpp'):
HOST_SOURCES += ['%s%s' % (name.replace('host_', ''), ext) HOST_SOURCES += ['%s%s' % (name.replace('host_', ''), ext)
for name in names] for name in names]
HostStdCppCompat()
@template @template
def HostLibrary(name): def HostLibrary(name):
+3
View File
@@ -3,6 +3,9 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this # License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
if CONFIG['MOZ_LIBSTDCXX_TARGET_VERSION'] or CONFIG['MOZ_LIBSTDCXX_HOST_VERSION']:
DIRS += ['stdc++compat']
if CONFIG['USE_ELF_HACK']: if CONFIG['USE_ELF_HACK']:
DIRS += ['elfhack'] DIRS += ['elfhack']
+15
View File
@@ -0,0 +1,15 @@
# Avoid dependency on libstdc++ 4.7
ac_add_options --enable-stdcxx-compat
TOOLTOOL_DIR=${TOOLTOOL_DIR:-$topsrcdir}
if [ -f "$TOOLTOOL_DIR/clang/lib/libstdc++.so" ]; then
LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$TOOLTOOL_DIR/clang/lib
elif [ -f "$TOOLTOOL_DIR/gcc/lib/libstdc++.so" ]; then
# We put both 32-bits and 64-bits library path in LD_LIBRARY_PATH: ld.so
# will prefer the files in the 32-bits path when loading 32-bits executables,
# and the files in the 64-bits path when loading 64-bits executables.
LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$TOOLTOOL_DIR/gcc/lib64:$TOOLTOOL_DIR/gcc/lib
fi
mk_add_options "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
+2
View File
@@ -30,3 +30,5 @@ ac_add_options --enable-pie
ac_add_options --disable-install-strip ac_add_options --disable-install-strip
# -gline-tables-only results in significantly smaller binaries. # -gline-tables-only results in significantly smaller binaries.
ac_add_options --enable-debug-symbols="-gline-tables-only" ac_add_options --enable-debug-symbols="-gline-tables-only"
. "$topsrcdir/build/unix/mozconfig.stdcxx"
+7 -1
View File
@@ -290,6 +290,11 @@ fi
if [ -n "$LD_LIBRARY_PATH_64" ]; then if [ -n "$LD_LIBRARY_PATH_64" ]; then
LD_LIBRARY_PATH_64=${MOZ_DIST_BIN}:${MOZ_DIST_BIN}/plugins:${MRE_HOME}${LD_LIBRARY_PATH_64:+":$LD_LIBRARY_PATH_64"} LD_LIBRARY_PATH_64=${MOZ_DIST_BIN}:${MOZ_DIST_BIN}/plugins:${MRE_HOME}${LD_LIBRARY_PATH_64:+":$LD_LIBRARY_PATH_64"}
fi fi
#
#
## Set SHLIB_PATH for HPUX
SHLIB_PATH=${MOZ_DIST_BIN}:${MRE_HOME}${SHLIB_PATH:+":$SHLIB_PATH"}
#
## Set LIBPATH for AIX ## Set LIBPATH for AIX
LIBPATH=${MOZ_DIST_BIN}:${MRE_HOME}${LIBPATH:+":$LIBPATH"} LIBPATH=${MOZ_DIST_BIN}:${MRE_HOME}${LIBPATH:+":$LIBPATH"}
# #
@@ -334,6 +339,7 @@ then
fi fi
echo "DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH" echo "DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH"
echo " LIBRARY_PATH=$LIBRARY_PATH" echo " LIBRARY_PATH=$LIBRARY_PATH"
echo " SHLIB_PATH=$SHLIB_PATH"
echo " LIBPATH=$LIBPATH" echo " LIBPATH=$LIBPATH"
echo " ADDON_PATH=$ADDON_PATH" echo " ADDON_PATH=$ADDON_PATH"
echo " MOZ_PROGRAM=$MOZ_PROGRAM" echo " MOZ_PROGRAM=$MOZ_PROGRAM"
@@ -344,7 +350,7 @@ then
fi fi
# #
export MOZILLA_FIVE_HOME LD_LIBRARY_PATH export MOZILLA_FIVE_HOME LD_LIBRARY_PATH
export LIBPATH LIBRARY_PATH ADDON_PATH DYLD_LIBRARY_PATH export SHLIB_PATH LIBPATH LIBRARY_PATH ADDON_PATH DYLD_LIBRARY_PATH
if [ $moz_debug -eq 1 ] if [ $moz_debug -eq 1 ]
then then
+7
View File
@@ -0,0 +1,7 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
ENABLE_CLANG_PLUGIN :=
include $(topsrcdir)/config/rules.mk
+23
View File
@@ -0,0 +1,23 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
if CONFIG['MOZ_LIBSTDCXX_TARGET_VERSION']:
Library('stdc++compat')
SOURCES += ['stdc++compat.cpp']
if CONFIG['MOZ_LIBSTDCXX_HOST_VERSION']:
HostLibrary('host_stdc++compat')
HOST_SOURCES += [
'stdc++compat.cpp',
]
FORCE_STATIC_LIB = True
NO_PGO = True
DISABLE_STL_WRAPPING = True
DEFINES['MOZ_LIBSTDCXX_VERSION'] = CONFIG['MOZ_LIBSTDCXX_TARGET_VERSION']
HOST_DEFINES['MOZ_LIBSTDCXX_VERSION'] = CONFIG['MOZ_LIBSTDCXX_HOST_VERSION']
+78
View File
@@ -0,0 +1,78 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <ostream>
#include <istream>
#include <string>
#include <stdarg.h>
#include <stdio.h>
#include <mozilla/Assertions.h>
/* GLIBCXX_3.4.8 is from gcc 4.1.1 (111691)
GLIBCXX_3.4.9 is from gcc 4.2.0 (111690)
GLIBCXX_3.4.10 is from gcc 4.3.0 (126287)
GLIBCXX_3.4.11 is from gcc 4.4.0 (133006)
GLIBCXX_3.4.12 is from gcc 4.4.1 (147138)
GLIBCXX_3.4.13 is from gcc 4.4.2 (151127)
GLIBCXX_3.4.14 is from gcc 4.5.0 (151126)
GLIBCXX_3.4.15 is from gcc 4.6.0 (160071)
GLIBCXX_3.4.16 is from gcc 4.6.1 (172240)
GLIBCXX_3.4.17 is from gcc 4.7.0 (174383)
GLIBCXX_3.4.18 is from gcc 4.8.0 (190787)
GLIBCXX_3.4.19 is from gcc 4.8.1 (199309)
GLIBCXX_3.4.20 is from gcc 4.9.0 (199307)
GLIBCXX_3.4.21 is from gcc 5.0 (210290)
This file adds the necessary compatibility tricks to avoid symbols with
version GLIBCXX_3.4.16 and bigger, keeping binary compatibility with
libstdc++ 4.6.1.
*/
#define GLIBCXX_VERSION(a, b, c) (((a) << 16) | ((b) << 8) | (c))
#if MOZ_LIBSTDCXX_VERSION >= GLIBCXX_VERSION(3, 4, 20)
namespace std {
/* We shouldn't be throwing exceptions at all, but it sadly turns out
we call STL (inline) functions that do. */
void __throw_out_of_range_fmt(char const* fmt, ...)
{
va_list ap;
char buf[1024]; // That should be big enough.
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
buf[sizeof(buf) - 1] = 0;
va_end(ap);
__throw_range_error(buf);
}
}
#endif
#if MOZ_LIBSTDCXX_VERSION >= GLIBCXX_VERSION(3, 4, 20)
/* Technically, this symbol is not in GLIBCXX_3.4.20, but in CXXABI_1.3.8,
but that's equivalent, version-wise. Those calls are added by the compiler
itself on `new Class[n]` calls. */
extern "C" void
__cxa_throw_bad_array_new_length()
{
MOZ_CRASH();
}
#endif
#if MOZ_LIBSTDCXX_VERSION >= GLIBCXX_VERSION(3, 4, 21)
/* While we generally don't build with exceptions, we have some host tools
* that do use them. libstdc++ from GCC 5.0 added exception constructors with
* char const* argument. Older versions only have a constructor with
* std::string. */
namespace std {
runtime_error::runtime_error(char const* s)
: runtime_error(std::string(s))
{
}
}
#endif
+17 -17
View File
@@ -104,10 +104,10 @@ def DoSSHCommand(command, user, host, port=None, ssh_key=None):
try: try:
output = f(cmdline, stderr=STDOUT).strip() output = f(cmdline, stderr=STDOUT).strip()
except CalledProcessError as e: except CalledProcessError as e:
print("failed ssh command output:") print "failed ssh command output:"
print('=' * 20) print '=' * 20
print(e.output) print e.output
print('=' * 20) print '=' * 20
raise raise
return output return output
@@ -118,7 +118,7 @@ def DoSCPFile(file, remote_path, user, host, port=None, ssh_key=None,
"""Upload file to user@host:remote_path using scp. Optionally use """Upload file to user@host:remote_path using scp. Optionally use
port and ssh_key, if provided.""" port and ssh_key, if provided."""
if log: if log:
print('Uploading %s' % file) print 'Uploading %s' % file
cmdline = ["scp"] cmdline = ["scp"]
AppendOptionalArgsToSSHCommandline(cmdline, port, ssh_key) AppendOptionalArgsToSSHCommandline(cmdline, port, ssh_key)
cmdline.extend([WindowsPathToMsysPath(file), cmdline.extend([WindowsPathToMsysPath(file),
@@ -221,8 +221,8 @@ def UploadFiles(user, host, path, files, verbose=False, port=None, ssh_key=None,
if not host or not user: if not host or not user:
return {} return {}
if (not path and not upload_to_temp_dir) or (path and upload_to_temp_dir): if (not path and not upload_to_temp_dir) or (path and upload_to_temp_dir):
print("One (and only one of UPLOAD_PATH or UPLOAD_TO_TEMP must be " + \ print "One (and only one of UPLOAD_PATH or UPLOAD_TO_TEMP must be " + \
"defined.") "defined."
sys.exit(1) sys.exit(1)
if upload_to_temp_dir: if upload_to_temp_dir:
@@ -269,18 +269,18 @@ def UploadFiles(user, host, path, files, verbose=False, port=None, ssh_key=None,
if post_upload_command is not None: if post_upload_command is not None:
if verbose: if verbose:
print("Running post-upload command: " + post_upload_command) print "Running post-upload command: " + post_upload_command
file_list = '"' + '" "'.join(remote_files) + '"' file_list = '"' + '" "'.join(remote_files) + '"'
output = DoSSHCommand('%s "%s" %s' % (post_upload_command, path, file_list), user, host, port=port, ssh_key=ssh_key) output = DoSSHCommand('%s "%s" %s' % (post_upload_command, path, file_list), user, host, port=port, ssh_key=ssh_key)
# We print since mozharness may parse URLs from the output stream. # We print since mozharness may parse URLs from the output stream.
print(output) print output
properties = GetUrlProperties(output, package) properties = GetUrlProperties(output, package)
finally: finally:
if upload_to_temp_dir: if upload_to_temp_dir:
DoSSHCommand("rm -rf %s" % path, user, host, port=port, DoSSHCommand("rm -rf %s" % path, user, host, port=port,
ssh_key=ssh_key) ssh_key=ssh_key)
if verbose: if verbose:
print("Upload complete") print "Upload complete"
return properties return properties
def CopyFilesLocally(path, files, verbose=False, base_path=None, package=None): def CopyFilesLocally(path, files, verbose=False, base_path=None, package=None):
@@ -299,7 +299,7 @@ def CopyFilesLocally(path, files, verbose=False, base_path=None, package=None):
if not os.path.exists(target_path): if not os.path.exists(target_path):
os.makedirs(target_path) os.makedirs(target_path)
if verbose: if verbose:
print("Copying " + file + " to " + target_path) print "Copying " + file + " to " + target_path
shutil.copy(file, target_path) shutil.copy(file, target_path)
def WriteProperties(files, properties_file, url_properties, package): def WriteProperties(files, properties_file, url_properties, package):
@@ -341,20 +341,20 @@ if __name__ == '__main__':
help="Name of the main package.") help="Name of the main package.")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if len(args) < 1: if len(args) < 1:
print("You must specify at least one file to upload") print "You must specify at least one file to upload"
sys.exit(1) sys.exit(1)
if not options.properties_file: if not options.properties_file:
print("You must specify a --properties-file") print "You must specify a --properties-file"
sys.exit(1) sys.exit(1)
if host == "localhost": if host == "localhost":
if upload_to_temp_dir: if upload_to_temp_dir:
print("Cannot use UPLOAD_TO_TEMP with UPLOAD_HOST=localhost") print "Cannot use UPLOAD_TO_TEMP with UPLOAD_HOST=localhost"
sys.exit(1) sys.exit(1)
if post_upload_command: if post_upload_command:
# POST_UPLOAD_COMMAND is difficult to extract from the mozharness # POST_UPLOAD_COMMAND is difficult to extract from the mozharness
# scripts, so just ignore it until it's no longer used anywhere # scripts, so just ignore it until it's no longer used anywhere
print("Ignoring POST_UPLOAD_COMMAND with UPLOAD_HOST=localhost") print "Ignoring POST_UPLOAD_COMMAND with UPLOAD_HOST=localhost"
try: try:
if host == "localhost": if host == "localhost":
@@ -370,6 +370,6 @@ if __name__ == '__main__':
package=options.package, verbose=True) package=options.package, verbose=True)
WriteProperties(args, options.properties_file, url_properties, options.package) WriteProperties(args, options.properties_file, url_properties, options.package)
except IOError as strerror: except IOError, (strerror):
print(strerror) print strerror
sys.exit(1) sys.exit(1)
+3 -3
View File
@@ -36,7 +36,7 @@ def count_ctors(filename):
# Even if we have .ctors, we shouldn't have any constructors in .ctors. # Even if we have .ctors, we shouldn't have any constructors in .ctors.
# Complain if .ctors does not look how we expect it to. # Complain if .ctors does not look how we expect it to.
if have_ctors and n_ctors_ctors != 0: if have_ctors and n_ctors_ctors != 0:
print("Unexpected .ctors contents for", filename, file=sys.stderr) print >>sys.stderr, "Unexpected .ctors contents for", filename
sys.exit(1) sys.exit(1)
return n_init_array_ctors return n_init_array_ctors
if have_ctors: if have_ctors:
@@ -44,7 +44,7 @@ def count_ctors(filename):
# We didn't find anything; somebody switched initialization mechanisms on # We didn't find anything; somebody switched initialization mechanisms on
# us, or the binary is completely busted. Complain either way. # us, or the binary is completely busted. Complain either way.
print("Couldn't find .init_array or .ctors in", filename, file=sys.stderr) print >>sys.stderr, "Couldn't find .init_array or .ctors in", filename
sys.exit(1) sys.exit(1)
if __name__ == '__main__': if __name__ == '__main__':
@@ -60,5 +60,5 @@ if __name__ == '__main__':
}]} }]}
] ]
} }
print("PERFHERDER_DATA: %s" % json.dumps(perfherder_data)) print "PERFHERDER_DATA: %s" % json.dumps(perfherder_data)
+7 -7
View File
@@ -2,8 +2,8 @@
import os import os
import re import re
import subprocess import subprocess
from urllib.parse import urlsplit from urlparse import urlsplit
from configparser import RawConfigParser from ConfigParser import RawConfigParser
from util.commands import run_cmd, get_output, remove_path from util.commands import run_cmd, get_output, remove_path
from util.retry import retry from util.retry import retry
@@ -105,7 +105,7 @@ def purge(dest):
try: try:
run_cmd(['hg', '--config', 'extensions.purge=', 'purge', run_cmd(['hg', '--config', 'extensions.purge=', 'purge',
'-a', '--all', dest], cwd=dest) '-a', '--all', dest], cwd=dest)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError, e:
log.debug('purge failed: %s' % e) log.debug('purge failed: %s' % e)
raise raise
@@ -306,7 +306,7 @@ def out(src, remote, **kwargs):
branch = "default" branch = "default"
revs.append((rev, branch)) revs.append((rev, branch))
return revs return revs
except subprocess.CalledProcessError as inst: except subprocess.CalledProcessError, inst:
# In some situations, some versions of Mercurial return "1" # In some situations, some versions of Mercurial return "1"
# if no changes are found, so we need to ignore this return code # if no changes are found, so we need to ignore this return code
if inst.returncode == 1: if inst.returncode == 1:
@@ -500,7 +500,7 @@ def apply_and_push(localrepo, remote, changer, max_attempts=10,
push(src=localrepo, remote=remote, ssh_username=ssh_username, push(src=localrepo, remote=remote, ssh_username=ssh_username,
ssh_key=ssh_key, force=force) ssh_key=ssh_key, force=force)
return return
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError, e:
log.debug("Hit error when trying to push: %s" % str(e)) log.debug("Hit error when trying to push: %s" % str(e))
if n == max_attempts: if n == max_attempts:
log.debug("Tried %d times, giving up" % max_attempts) log.debug("Tried %d times, giving up" % max_attempts)
@@ -515,7 +515,7 @@ def apply_and_push(localrepo, remote, changer, max_attempts=10,
try: try:
run_cmd(['hg', '--config', 'ui.merge=internal:merge', run_cmd(['hg', '--config', 'ui.merge=internal:merge',
'rebase'], cwd=localrepo) 'rebase'], cwd=localrepo)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError, e:
log.debug("Failed to rebase: %s" % str(e)) log.debug("Failed to rebase: %s" % str(e))
update(localrepo, branch=branch) update(localrepo, branch=branch)
for r in reversed(new_revs): for r in reversed(new_revs):
@@ -578,7 +578,7 @@ def adjust_paths(dest, **paths):
config.add_section('paths') config.add_section('paths')
changed = False changed = False
for path_name, path_value in list(paths.items()): for path_name, path_value in paths.items():
if (not config.has_option('paths', path_name) or if (not config.has_option('paths', path_name) or
config.get('paths', path_name) != path_value): config.get('paths', path_name) != path_value):
changed = True changed = True
+1 -1
View File
@@ -11,6 +11,7 @@ mozbuild.pth:python/mozbuild
mozversioncontrol.pth:python/mozversioncontrol mozversioncontrol.pth:python/mozversioncontrol
mozlint.pth:python/mozlint mozlint.pth:python/mozlint
pymake.pth:build/pymake pymake.pth:build/pymake
optional:setup.py:python/psutil:build_ext:--inplace
optional:psutil.pth:python/psutil optional:psutil.pth:python/psutil
which.pth:python/which which.pth:python/which
ply.pth:other-licenses/ply/ ply.pth:other-licenses/ply/
@@ -28,7 +29,6 @@ moztreedocs.pth:tools/docs
packages.txt:testing/mozbase/packages.txt packages.txt:testing/mozbase/packages.txt
objdir:build objdir:build
gyp.pth:media/webrtc/trunk/tools/gyp/pylib gyp.pth:media/webrtc/trunk/tools/gyp/pylib
six.pth:python/requests/requests/packages/urllib3/packages
pyasn1.pth:python/pyasn1 pyasn1.pth:python/pyasn1
pyasn1_modules.pth:python/pyasn1-modules pyasn1_modules.pth:python/pyasn1-modules
bitstring.pth:python/bitstring bitstring.pth:python/bitstring
+11 -13
View File
@@ -23,8 +23,8 @@ BINSCOPE_OUTPUT_LOGFILE = r".\binscope_xml_output.log"
# usage # usage
if len(sys.argv) < 3: if len(sys.argv) < 3:
print("""usage : autobinscope.by path_to_binary path_to_symbols [log_file_path]" print """usage : autobinscope.by path_to_binary path_to_symbols [log_file_path]"
log_file_path is optional, log will be written to .\binscope_xml_output.log by default""") log_file_path is optional, log will be written to .\binscope_xml_output.log by default"""
sys.exit(0) sys.exit(0)
binary_path = sys.argv[1] binary_path = sys.argv[1]
@@ -40,7 +40,7 @@ else:
try: try:
binscope_path = os.environ['BINSCOPE'] binscope_path = os.environ['BINSCOPE']
except KeyError: except KeyError:
print("BINSCOPE environment variable is not set, can't check DEP/ASLR etc. status.") print "BINSCOPE environment variable is not set, can't check DEP/ASLR etc. status."
sys.exit(0) sys.exit(0)
try: try:
@@ -51,15 +51,13 @@ try:
"/c", "CompilerVersionCheck", "/c", "SafeSEHCheck", "/c", "SNCheck", "/c", "CompilerVersionCheck", "/c", "SafeSEHCheck", "/c", "SNCheck",
"/c", "DBCheck"], stdout=subprocess.PIPE) "/c", "DBCheck"], stdout=subprocess.PIPE)
except OSError as e: except WindowsError, (errno, strerror):
errno = e.errno
strerror = e.strerror or str(e)
if errno != 2 and errno != 3: if errno != 2 and errno != 3:
print("Unexpected error ! \nError " + str(errno) + " : " + strerror + "\nExiting !\n") print "Unexpected error ! \nError " + str(errno) + " : " + strerror + "\nExiting !\n"
sys.exit(0) sys.exit(0)
else: else:
print("Could not locate binscope at location : %s\n" % binscope_path) print "Could not locate binscope at location : %s\n" % binscope_path
print("Binscope wasn't installed or the BINSCOPE env variable wasn't set correctly, skipping this check and exiting...") print "Binscope wasn't installed or the BINSCOPE env variable wasn't set correctly, skipping this check and exiting..."
sys.exit(0) sys.exit(0)
proc.wait() proc.wait()
@@ -68,10 +66,10 @@ output = proc.communicate()[0]
# is this a PASS or a FAIL ? # is this a PASS or a FAIL ?
if proc.returncode != 0: if proc.returncode != 0:
print("Error count: %d" % proc.returncode) print "Error count: %d" % proc.returncode
print("TEST-UNEXPECTED-FAIL | autobinscope.py | %s is missing a needed Windows protection, such as /GS or ASLR" % binary_path) print "TEST-UNEXPECTED-FAIL | autobinscope.py | %s is missing a needed Windows protection, such as /GS or ASLR" % binary_path
logfile = open(log_file_path, "r") logfile = open(log_file_path, "r")
for line in logfile: for line in logfile:
print((line), end=' ') print(line),
else: else:
print("TEST-PASS | autobinscope.py | %s succeeded" % binary_path) print "TEST-PASS | autobinscope.py | %s succeeded" % binary_path
+1 -1
View File
@@ -39,6 +39,6 @@ def MergePGOFiles(basename, pgddir, pgcdir):
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) != 3: if len(sys.argv) != 3:
print("Usage: pgomerge.py <binary basename> <dist/bin>", file=sys.stderr) print >>sys.stderr, "Usage: pgomerge.py <binary basename> <dist/bin>"
sys.exit(1) sys.exit(1)
MergePGOFiles(sys.argv[1], os.getcwd(), sys.argv[2]) MergePGOFiles(sys.argv[1], os.getcwd(), sys.argv[2])
+3 -3
View File
@@ -40,9 +40,9 @@ if __name__ == '__main__':
0, # no inherit 0, # no inherit
int(pid)) int(pid))
if handle: if handle:
print("Process %s:" % pid) print "Process %s:" % pid
vsize, peak_vsize = get_vmsize(handle) vsize, peak_vsize = get_vmsize(handle)
print("peak vsize: %d" % peak_vsize) print "peak vsize: %d" % peak_vsize
ctypes.windll.kernel32.CloseHandle(handle) ctypes.windll.kernel32.CloseHandle(handle)
else: else:
print("Couldn't open process %s" % pid) print "Couldn't open process %s" % pid
+6 -6
View File
@@ -200,7 +200,7 @@ def format_manifest(manifest):
def write_zip(zip_path, prefix=None): def write_zip(zip_path, prefix=None):
"""Write toolchain data to a zip file.""" """Write toolchain data to a zip file."""
if isinstance(prefix, str): if isinstance(prefix, unicode):
prefix = prefix.encode('utf-8') prefix = prefix.encode('utf-8')
with JarWriter(file=zip_path, optimize=False, compress=5) as zip: with JarWriter(file=zip_path, optimize=False, compress=5) as zip:
@@ -226,7 +226,7 @@ def write_zip(zip_path, prefix=None):
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) != 3: if len(sys.argv) != 3:
print(('usage: %s create-zip <path-prefix>' % sys.argv[0])) print('usage: %s create-zip <path-prefix>' % sys.argv[0])
sys.exit(1) sys.exit(1)
assert sys.argv[1] == 'create-zip' assert sys.argv[1] == 'create-zip'
@@ -244,7 +244,7 @@ if __name__ == '__main__':
sha256.update(data) sha256.update(data)
sha512.update(data) sha512.update(data)
print(('Hashes of %s (size=%d)' % (destzip, len(data)))) print('Hashes of %s (size=%d)' % (destzip, len(data)))
print(('SHA-1: %s' % sha1.hexdigest())) print('SHA-1: %s' % sha1.hexdigest())
print(('SHA-256: %s' % sha256.hexdigest())) print('SHA-256: %s' % sha256.hexdigest())
print(('SHA-512: %s' % sha512.hexdigest())) print('SHA-512: %s' % sha512.hexdigest())
+8 -21
View File
@@ -343,8 +343,7 @@ OriginAttributes::IsFirstPartyEnabled()
return sFirstPartyIsolation; return sFirstPartyIsolation;
} }
BasePrincipal::BasePrincipal(PrincipalKind aKind) BasePrincipal::BasePrincipal()
: mKind(aKind)
{} {}
BasePrincipal::~BasePrincipal() BasePrincipal::~BasePrincipal()
@@ -561,23 +560,6 @@ BasePrincipal::GetCspJSON(nsAString& outCSPinJSON)
return mCSP->ToJSON(outCSPinJSON); return mCSP->ToJSON(outCSPinJSON);
} }
NS_IMETHODIMP
BasePrincipal::IsSameOrigin(nsIURI* aURI, bool aIsPrivateWin, bool* aRes) {
*aRes = false;
nsCOMPtr<nsIURI> prinURI;
nsresult rv = GetURI(getter_AddRefs(prinURI));
if (NS_FAILED(rv) || !prinURI) {
return NS_OK;
}
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
if (!ssm) {
return NS_ERROR_UNEXPECTED;
;
}
*aRes = NS_SUCCEEDED(ssm->CheckSameOriginURI(prinURI, aURI, aIsPrivateWin));
return NS_OK;
}
NS_IMETHODIMP NS_IMETHODIMP
BasePrincipal::GetIsNullPrincipal(bool* aResult) BasePrincipal::GetIsNullPrincipal(bool* aResult)
{ {
@@ -625,8 +607,13 @@ BasePrincipal::GetOriginSuffix(nsACString& aOriginAttributes)
NS_IMETHODIMP NS_IMETHODIMP
BasePrincipal::GetAppStatus(uint16_t* aAppStatus) BasePrincipal::GetAppStatus(uint16_t* aAppStatus)
{ {
// TODO: Remove GetAppStatus. if (AppId() == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
*aAppStatus = nsIPrincipal::APP_STATUS_NOT_INSTALLED; NS_WARNING("Asking for app status on a principal with an unknown app id");
*aAppStatus = nsIPrincipal::APP_STATUS_NOT_INSTALLED;
return NS_OK;
}
*aAppStatus = nsScriptSecurityManager::AppStatusForPrincipal(this);
return NS_OK; return NS_OK;
} }
+9 -20
View File
@@ -251,14 +251,7 @@ public:
class BasePrincipal : public nsJSPrincipals class BasePrincipal : public nsJSPrincipals
{ {
public: public:
enum PrincipalKind { BasePrincipal();
eNullPrincipal,
eCodebasePrincipal,
eExpandedPrincipal,
eSystemPrincipal
};
explicit BasePrincipal(PrincipalKind aKind);
enum DocumentDomainConsideration { DontConsiderDocumentDomain, ConsiderDocumentDomain}; enum DocumentDomainConsideration { DontConsiderDocumentDomain, ConsiderDocumentDomain};
bool Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration); bool Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration);
@@ -289,7 +282,6 @@ public:
NS_IMETHOD GetUnknownAppId(bool* aUnknownAppId) final; NS_IMETHOD GetUnknownAppId(bool* aUnknownAppId) final;
NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final; NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final; NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool aIsPrivateWin, bool* aRes) override;
bool EqualsIgnoringAddonId(nsIPrincipal *aOther); bool EqualsIgnoringAddonId(nsIPrincipal *aOther);
@@ -308,19 +300,17 @@ public:
uint32_t PrivateBrowsingId() const { return mOriginAttributes.mPrivateBrowsingId; } uint32_t PrivateBrowsingId() const { return mOriginAttributes.mPrivateBrowsingId; }
bool IsInIsolatedMozBrowserElement() const { return mOriginAttributes.mInIsolatedMozBrowser; } bool IsInIsolatedMozBrowserElement() const { return mOriginAttributes.mInIsolatedMozBrowser; }
PrincipalKind Kind() const { return mKind; } enum PrincipalKind {
eNullPrincipal,
eCodebasePrincipal,
eExpandedPrincipal,
eSystemPrincipal
};
virtual PrincipalKind Kind() = 0;
already_AddRefed<BasePrincipal> CloneStrippingUserContextIdAndFirstPartyDomain(); already_AddRefed<BasePrincipal> CloneStrippingUserContextIdAndFirstPartyDomain();
/**
* Returns true if this principal's CSP should override a document's CSP for
* loads that it triggers. Currently true only for expanded principals which
* subsume the document principal.
*/
bool OverridesCSP(nsIPrincipal* aDocumentPrincipal) {
return mKind == eExpandedPrincipal && Subsumes(aDocumentPrincipal, DontConsiderDocumentDomain);
}
protected: protected:
virtual ~BasePrincipal(); virtual ~BasePrincipal();
@@ -342,7 +332,6 @@ protected:
nsCOMPtr<nsIContentSecurityPolicy> mCSP; nsCOMPtr<nsIContentSecurityPolicy> mCSP;
nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP; nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
PrincipalOriginAttributes mOriginAttributes; PrincipalOriginAttributes mOriginAttributes;
PrincipalKind mKind;
}; };
} // namespace mozilla } // namespace mozilla
+9 -6
View File
@@ -223,12 +223,6 @@ interface nsIPrincipal : nsISerializable
*/ */
readonly attribute AUTF8String originSuffix; readonly attribute AUTF8String originSuffix;
/**
* Uses NS_Security Compare to determine if the
* other URI is same-origin as the uri of the Principal
*/
bool IsSameOrigin(in nsIURI otherURI, in bool aIsPrivateWin);
/** /**
* The base domain of the codebase URI to which this principal pertains * The base domain of the codebase URI to which this principal pertains
* (generally the document URI), handling null principals and * (generally the document URI), handling null principals and
@@ -303,6 +297,15 @@ interface nsIPrincipal : nsISerializable
*/ */
[infallible] readonly attribute unsigned long privateBrowsingId; [infallible] readonly attribute unsigned long privateBrowsingId;
/**
* Returns true iff the principal is inside an isolated mozbrowser element.
* <iframe mozbrowser mozapp> and <xul:browser> are not considered to be
* mozbrowser elements. <iframe mozbrowser noisolation> does not count as
* isolated since isolation is disabled. Isolation can only be disabled if
* the containing document is chrome.
*/
[infallible] readonly attribute boolean isInIsolatedMozBrowserElement;
/** /**
* Returns true if this principal has an unknown appId. This shouldn't * Returns true if this principal has an unknown appId. This shouldn't
* generally be used. We only expose it due to not providing the correct * generally be used. We only expose it due to not providing the correct
+3 -3
View File
@@ -36,9 +36,7 @@ public:
// This should only be used by deserialization, and the factory constructor. // This should only be used by deserialization, and the factory constructor.
// Other consumers should use the Create and CreateWithInheritedAttributes // Other consumers should use the Create and CreateWithInheritedAttributes
// methods. // methods.
nsNullPrincipal() nsNullPrincipal() {}
: BasePrincipal(eNullPrincipal)
{}
NS_DECL_NSISERIALIZABLE NS_DECL_NSISERIALIZABLE
@@ -62,6 +60,8 @@ public:
virtual nsresult GetScriptLocation(nsACString &aStr) override; virtual nsresult GetScriptLocation(nsACString &aStr) override;
PrincipalKind Kind() override { return eNullPrincipal; }
protected: protected:
virtual ~nsNullPrincipal() {} virtual ~nsNullPrincipal() {}
+4 -16
View File
@@ -31,6 +31,8 @@
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "mozilla/HashFunctions.h" #include "mozilla/HashFunctions.h"
#include "nsIAppsService.h"
using namespace mozilla; using namespace mozilla;
static bool gCodeBasePrincipalSupport = false; static bool gCodeBasePrincipalSupport = false;
@@ -64,11 +66,10 @@ nsPrincipal::InitializeStatics()
} }
nsPrincipal::nsPrincipal() nsPrincipal::nsPrincipal()
: BasePrincipal(eCodebasePrincipal) : mCodebaseImmutable(false)
, mCodebaseImmutable(false)
, mDomainImmutable(false) , mDomainImmutable(false)
, mInitialized(false) , mInitialized(false)
{} { }
nsPrincipal::~nsPrincipal() nsPrincipal::~nsPrincipal()
{ {
@@ -464,18 +465,6 @@ nsPrincipal::Write(nsIObjectOutputStream* aStream)
rv = aStream->WriteStringZ(suffix.get()); rv = aStream->WriteStringZ(suffix.get());
NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_SUCCESS(rv, rv);
// This is an ugly hack to prevent re-entrancy calls into nsPrincipal::Write()
// because of repeat CSP processing.
// We refcount the context and if found 3+ refcounts on the same, skip writing
// the mCSP compound object.
// TODO: figure out exactly why this happens and fix the root cause.
nsCSPContext* CSPContext = static_cast<nsCSPContext*>(mCSP.get());
if(CSPContext) {
auto CSPDepth = CSPContext->AddRef();
CSPContext->Release();
if(CSPDepth > 2) return NS_OK;
}
rv = NS_WriteOptionalCompoundObject(aStream, mCSP, rv = NS_WriteOptionalCompoundObject(aStream, mCSP,
NS_GET_IID(nsIContentSecurityPolicy), NS_GET_IID(nsIContentSecurityPolicy),
true); true);
@@ -527,7 +516,6 @@ struct OriginComparator
nsExpandedPrincipal::nsExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList, nsExpandedPrincipal::nsExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList,
const PrincipalOriginAttributes& aAttrs) const PrincipalOriginAttributes& aAttrs)
: BasePrincipal(eExpandedPrincipal)
{ {
// We force the principals to be sorted by origin so that nsExpandedPrincipal // We force the principals to be sorted by origin so that nsExpandedPrincipal
// origins can have a canonical form. // origins can have a canonical form.
+4
View File
@@ -46,6 +46,8 @@ public:
*/ */
static void InitializeStatics(); static void InitializeStatics();
PrincipalKind Kind() override { return eCodebasePrincipal; }
nsCOMPtr<nsIURI> mDomain; nsCOMPtr<nsIURI> mDomain;
nsCOMPtr<nsIURI> mCodebase; nsCOMPtr<nsIURI> mCodebase;
// If mCodebaseImmutable is true, mCodebase is non-null and immutable // If mCodebaseImmutable is true, mCodebase is non-null and immutable
@@ -80,6 +82,8 @@ public:
virtual nsresult GetScriptLocation(nsACString &aStr) override; virtual nsresult GetScriptLocation(nsACString &aStr) override;
nsresult GetOriginInternal(nsACString& aOrigin) override; nsresult GetOriginInternal(nsACString& aOrigin) override;
PrincipalKind Kind() override { return eExpandedPrincipal; }
protected: protected:
virtual ~nsExpandedPrincipal(); virtual ~nsExpandedPrincipal();
+70 -25
View File
@@ -9,6 +9,7 @@
#include "xpcpublic.h" #include "xpcpublic.h"
#include "XPCWrapper.h" #include "XPCWrapper.h"
#include "nsIAppsService.h"
#include "nsIInputStreamChannel.h" #include "nsIInputStreamChannel.h"
#include "nsILoadContext.h" #include "nsILoadContext.h"
#include "nsIServiceManager.h" #include "nsIServiceManager.h"
@@ -54,6 +55,7 @@
#include "nsIChromeRegistry.h" #include "nsIChromeRegistry.h"
#include "nsIContentSecurityPolicy.h" #include "nsIContentSecurityPolicy.h"
#include "nsIAsyncVerifyRedirectCallback.h" #include "nsIAsyncVerifyRedirectCallback.h"
#include "mozIApplication.h"
#include "mozilla/Preferences.h" #include "mozilla/Preferences.h"
#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ContentParent.h" #include "mozilla/dom/ContentParent.h"
@@ -74,7 +76,6 @@ nsIIOService *nsScriptSecurityManager::sIOService = nullptr;
nsIStringBundle *nsScriptSecurityManager::sStrBundle = nullptr; nsIStringBundle *nsScriptSecurityManager::sStrBundle = nullptr;
JSContext *nsScriptSecurityManager::sContext = nullptr; JSContext *nsScriptSecurityManager::sContext = nullptr;
bool nsScriptSecurityManager::sStrictFileOriginPolicy = true; bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
bool nsScriptSecurityManager::sSameOriginPolicy = true;
/////////////////////////// ///////////////////////////
// Convenience Functions // // Convenience Functions //
@@ -238,6 +239,68 @@ nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI)
return NS_SecurityHashURI(aURI); return NS_SecurityHashURI(aURI);
} }
uint16_t
nsScriptSecurityManager::AppStatusForPrincipal(nsIPrincipal *aPrin)
{
uint32_t appId = aPrin->GetAppId();
// After bug 1238160, the principal no longer knows how to answer "is this a
// browser element", which is really what this code path wants. Currently,
// desktop is the only platform where we intend to disable isolation on a
// browser frame, so non-desktop should be able to assume that
// inIsolatedMozBrowser is true for all mozbrowser frames. Additionally,
// apps are no longer used on desktop, so appId is always NO_APP_ID. We use
// a release assertion in nsFrameLoader::OwnerIsIsolatedMozBrowserFrame so
// that platforms with apps can assume inIsolatedMozBrowser is true for all
// mozbrowser frames.
bool inIsolatedMozBrowser = aPrin->GetIsInIsolatedMozBrowserElement();
NS_WARNING_ASSERTION(
appId != nsIScriptSecurityManager::UNKNOWN_APP_ID,
"Asking for app status on a principal with an unknown app id");
// Installed apps have a valid app id (not NO_APP_ID or UNKNOWN_APP_ID)
// and they are not inside a mozbrowser.
if (appId == nsIScriptSecurityManager::NO_APP_ID ||
appId == nsIScriptSecurityManager::UNKNOWN_APP_ID ||
inIsolatedMozBrowser)
{
return nsIPrincipal::APP_STATUS_NOT_INSTALLED;
}
nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID);
NS_ENSURE_TRUE(appsService, nsIPrincipal::APP_STATUS_NOT_INSTALLED);
nsCOMPtr<mozIApplication> app;
appsService->GetAppByLocalId(appId, getter_AddRefs(app));
NS_ENSURE_TRUE(app, nsIPrincipal::APP_STATUS_NOT_INSTALLED);
uint16_t status = nsIPrincipal::APP_STATUS_INSTALLED;
NS_ENSURE_SUCCESS(app->GetAppStatus(&status),
nsIPrincipal::APP_STATUS_NOT_INSTALLED);
nsString appOrigin;
NS_ENSURE_SUCCESS(app->GetOrigin(appOrigin),
nsIPrincipal::APP_STATUS_NOT_INSTALLED);
nsCOMPtr<nsIURI> appURI;
NS_ENSURE_SUCCESS(NS_NewURI(getter_AddRefs(appURI), appOrigin),
nsIPrincipal::APP_STATUS_NOT_INSTALLED);
// The app could contain a cross-origin iframe - make sure that the content
// is actually same-origin with the app.
MOZ_ASSERT(inIsolatedMozBrowser == false, "Checked this above");
nsAutoCString suffix;
PrincipalOriginAttributes attrs;
NS_ENSURE_TRUE(attrs.PopulateFromOrigin(NS_ConvertUTF16toUTF8(appOrigin), suffix),
nsIPrincipal::APP_STATUS_NOT_INSTALLED);
attrs.mAppId = appId;
attrs.mInIsolatedMozBrowser = false;
nsCOMPtr<nsIPrincipal> appPrin = BasePrincipal::CreateCodebasePrincipal(appURI, attrs);
NS_ENSURE_TRUE(appPrin, nsIPrincipal::APP_STATUS_NOT_INSTALLED);
return aPrin->Equals(appPrin) ? status
: nsIPrincipal::APP_STATUS_NOT_INSTALLED;
}
/* /*
* GetChannelResultPrincipal will return the principal that the resource * GetChannelResultPrincipal will return the principal that the resource
* returned by this channel will use. For example, if the resource is in * returned by this channel will use. For example, if the resource is in
@@ -472,8 +535,7 @@ NS_IMPL_ISUPPORTS(nsScriptSecurityManager,
///////////////// Security Checks ///////////////// ///////////////// Security Checks /////////////////
bool bool
nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx, nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx)
JS::HandleValue aValue)
{ {
MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext()); MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal(); nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
@@ -496,23 +558,12 @@ nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx,
} }
if (reportViolation) { if (reportViolation) {
JS::Rooted<JSString*> jsString(cx, JS::ToString(cx, aValue));
if (NS_WARN_IF(!jsString)) {
JS_ClearPendingException(cx);
return false;
}
nsAutoJSString scriptSample;
if (NS_WARN_IF(!scriptSample.init(cx, jsString))) {
JS_ClearPendingException(cx);
return false;
}
JS::AutoFilename scriptFilename;
nsAutoString fileName; nsAutoString fileName;
unsigned lineNum = 0; unsigned lineNum = 0;
unsigned columnNum = 0; NS_NAMED_LITERAL_STRING(scriptSample, "call to eval() or related function blocked by CSP");
if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum, &columnNum)) {
JS::AutoFilename scriptFilename;
if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum)) {
if (const char *file = scriptFilename.get()) { if (const char *file = scriptFilename.get()) {
CopyUTF8toUTF16(nsDependentCString(file), fileName); CopyUTF8toUTF16(nsDependentCString(file), fileName);
} }
@@ -523,7 +574,6 @@ nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx,
fileName, fileName,
scriptSample, scriptSample,
lineNum, lineNum,
columnNum,
EmptyString(), EmptyString(),
EmptyString()); EmptyString());
} }
@@ -544,7 +594,7 @@ nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
nsIURI* aTargetURI, nsIURI* aTargetURI,
bool reportError) bool reportError)
{ {
if (sSameOriginPolicy && !SecurityCompareURIs(aSourceURI, aTargetURI)) if (!SecurityCompareURIs(aSourceURI, aTargetURI))
{ {
if (reportError) { if (reportError) {
ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"), ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"),
@@ -1371,13 +1421,10 @@ nsScriptSecurityManager::CanGetService(JSContext *cx,
const char sJSEnabledPrefName[] = "javascript.enabled"; const char sJSEnabledPrefName[] = "javascript.enabled";
const char sFileOriginPolicyPrefName[] = const char sFileOriginPolicyPrefName[] =
"security.fileuri.strict_origin_policy"; "security.fileuri.strict_origin_policy";
const char sSameOriginPolicyPrefName[] =
"security.same_origin_policy.enabled";
static const char* kObservedPrefs[] = { static const char* kObservedPrefs[] = {
sJSEnabledPrefName, sJSEnabledPrefName,
sFileOriginPolicyPrefName, sFileOriginPolicyPrefName,
sSameOriginPolicyPrefName,
"capability.policy.", "capability.policy.",
nullptr nullptr
}; };
@@ -1533,8 +1580,6 @@ nsScriptSecurityManager::ScriptSecurityPrefChanged()
Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled); Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled);
sStrictFileOriginPolicy = sStrictFileOriginPolicy =
Preferences::GetBool(sFileOriginPolicyPrefName, false); Preferences::GetBool(sFileOriginPolicyPrefName, false);
sSameOriginPolicy =
Preferences::GetBool(sSameOriginPolicyPrefName, true);
mFileURIWhitelist.reset(); mFileURIWhitelist.reset();
} }
+1 -2
View File
@@ -91,7 +91,7 @@ private:
// Decides, based on CSP, whether or not eval() and stuff can be executed. // Decides, based on CSP, whether or not eval() and stuff can be executed.
static bool static bool
ContentSecurityPolicyPermitsJSAction(JSContext *cx, JS::HandleValue aValue); ContentSecurityPolicyPermitsJSAction(JSContext *cx);
static bool static bool
JSPrincipalsSubsume(JSPrincipals *first, JSPrincipals *second); JSPrincipalsSubsume(JSPrincipals *first, JSPrincipals *second);
@@ -152,7 +152,6 @@ private:
} }
static bool sStrictFileOriginPolicy; static bool sStrictFileOriginPolicy;
static bool sSameOriginPolicy;
static nsIIOService *sIOService; static nsIIOService *sIOService;
static nsIStringBundle *sStrBundle; static nsIStringBundle *sStrBundle;
+3 -3
View File
@@ -36,9 +36,7 @@ public:
NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override; NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
nsresult GetOriginInternal(nsACString& aOrigin) override; nsresult GetOriginInternal(nsACString& aOrigin) override;
nsSystemPrincipal() nsSystemPrincipal() {}
: BasePrincipal(eSystemPrincipal)
{}
virtual nsresult GetScriptLocation(nsACString &aStr) override; virtual nsresult GetScriptLocation(nsACString &aStr) override;
@@ -54,6 +52,8 @@ protected:
{ {
return true; return true;
} }
PrincipalKind Kind() override { return eSystemPrincipal; }
}; };
#endif // nsSystemPrincipal_h__ #endif // nsSystemPrincipal_h__
+1
View File
@@ -4,6 +4,7 @@ support-files =
file_disableScript.html file_disableScript.html
!/js/xpconnect/tests/mochitest/file_empty.html !/js/xpconnect/tests/mochitest/file_empty.html
[test_app_principal_equality.html]
[test_bug246699.html] [test_bug246699.html]
[test_bug292789.html] [test_bug292789.html]
[test_bug423375.html] [test_bug423375.html]
@@ -0,0 +1,88 @@
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=777467
-->
<head>
<meta charset="utf-8">
<title>Test app principal's equality</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=777467">Mozilla Bug 777467</a>
<p id="display"></p>
<script>
/** Test for app principal's equality **/
SimpleTest.waitForExplicitFinish();
var permissions = new Promise(resolve => {
SpecialPowers.pushPermissions(
[{ type: "browser", allow: true, context: document },
{ type: "embed-apps", allow: true, context: document }],
resolve);
});
permissions.then(() => {
$('content').innerHTML =
'<iframe src="error404"></iframe>\n' +
'<iframe mozbrowser src="error404"></iframe>\n' +
'<iframe mozapp="http://example.org/manifest.webapp" mozbrowser src="error404"></iframe>';
var iframes = document.getElementsByTagName("iframe");
var promises = []
for (var i = 0; i < promises.length; ++i) {
promises.push(new Promise(resolve => {
iframes[i].addEventListener("load", resolve);
}));
}
return Promise.all(promises);
});
var prefs = new Promise(resolve => {
SpecialPowers.pushPrefEnv(
{ set: [[ "dom.mozBrowserFramesEnabled", true ],
[ "dom.ipc.browser_frames.oop_by_default", false ]] },
resolve);
});
</script>
<div id="content" style="display: none;">
</div>
<pre id="test">
<script type="application/javascript">
function canAccessDocument(win) {
var result = true;
try {
win.document;
} catch(e) {
result = false;
}
return result;
}
var loaded = new Promise(resolve => addLoadEvent(resolve));
Promise.all([ permissions, prefs, loaded ]).then(runTest);
function runTest() {
// Test the witness frame (we can access same-origin frame).
is(canAccessDocument(frames[0]), true,
"should be able to access the first frame");
// Test different app/browserElement frames.
for (var i=1; i<frames.length; ++i) {
is(canAccessDocument(frames[i]), false,
"should not be able to access the other frames");
}
SimpleTest.finish();
}
</script>
</pre>
</body>
</html>
+1 -1
View File
@@ -66,7 +66,7 @@ endif
SH := /bin/sh SH := /bin/sh
PERL ?= perl PERL ?= perl
PYTHON ?= $(shell which python3 > /dev/null 2>&1 && echo python3 || echo python) PYTHON ?= $(shell which python2.7 > /dev/null 2>&1 && echo python2.7 || echo python)
CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess) CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
ifdef CONFIG_GUESS_SCRIPT ifdef CONFIG_GUESS_SCRIPT
+12 -12
View File
@@ -22,7 +22,7 @@ if topsrcdir == '':
topsrcdir = '.' topsrcdir = '.'
def check_call_noisy(cmd, *args, **kwargs): def check_call_noisy(cmd, *args, **kwargs):
print("Executing command:", cmd) print "Executing command:", cmd
check_call(cmd, *args, **kwargs) check_call(cmd, *args, **kwargs)
def do_hg_pull(dir, repository, hg): def do_hg_pull(dir, repository, hg):
@@ -67,22 +67,22 @@ def do_cvs_export(modules, tag, cvsroot, cvs):
cvs_module = module_tuple[1] cvs_module = module_tuple[1]
fullpath = os.path.join(topsrcdir, module) fullpath = os.path.join(topsrcdir, module)
if os.path.exists(fullpath): if os.path.exists(fullpath):
print("Removing '%s'" % fullpath) print "Removing '%s'" % fullpath
shutil.rmtree(fullpath) shutil.rmtree(fullpath)
(parent, leaf) = os.path.split(module) (parent, leaf) = os.path.split(module)
print("CVS export begin: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")) print "CVS export begin: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
check_call_noisy([cvs, '-d', cvsroot, check_call_noisy([cvs, '-d', cvsroot,
'export', '-r', tag, '-d', leaf, cvs_module], 'export', '-r', tag, '-d', leaf, cvs_module],
cwd=os.path.join(topsrcdir, parent)) cwd=os.path.join(topsrcdir, parent))
print("CVS export end: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")) print "CVS export end: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
def toggle_trailing_blank_line(depname): def toggle_trailing_blank_line(depname):
"""If the trailing line is empty, then we'll delete it. """If the trailing line is empty, then we'll delete it.
Otherwise we'll add a blank line.""" Otherwise we'll add a blank line."""
lines = open(depname, "r").readlines() lines = open(depname, "r").readlines()
if not lines: if not lines:
print("unexpected short file", file=sys.stderr) print >>sys.stderr, "unexpected short file"
return return
if not lines[-1].strip(): if not lines[-1].strip():
@@ -95,7 +95,7 @@ def toggle_trailing_blank_line(depname):
def get_trailing_blank_line_state(depname): def get_trailing_blank_line_state(depname):
lines = open(depname, "r").readlines() lines = open(depname, "r").readlines()
if not lines: if not lines:
print("unexpected short file", file=sys.stderr) print >>sys.stderr, "unexpected short file"
return "no blank line" return "no blank line"
if not lines[-1].strip(): if not lines[-1].strip():
@@ -104,18 +104,18 @@ def get_trailing_blank_line_state(depname):
return "no blank line" return "no blank line"
def update_nspr_or_nss(tag, depfile, destination, hgpath): def update_nspr_or_nss(tag, depfile, destination, hgpath):
print("reverting to HG version of %s to get its blank line state" % depfile) print "reverting to HG version of %s to get its blank line state" % depfile
check_call_noisy([options.hg, 'revert', depfile]) check_call_noisy([options.hg, 'revert', depfile])
old_state = get_trailing_blank_line_state(depfile) old_state = get_trailing_blank_line_state(depfile)
print("old state of %s is: %s" % (depfile, old_state)) print "old state of %s is: %s" % (depfile, old_state)
do_hg_replace(destination, hgpath, tag, HG_EXCLUSIONS, options.hg) do_hg_replace(destination, hgpath, tag, HG_EXCLUSIONS, options.hg)
new_state = get_trailing_blank_line_state(depfile) new_state = get_trailing_blank_line_state(depfile)
print("new state of %s is: %s" % (depfile, new_state)) print "new state of %s is: %s" % (depfile, new_state)
if old_state == new_state: if old_state == new_state:
print("toggling blank line in: ", depfile) print "toggling blank line in: ", depfile
toggle_trailing_blank_line(depfile) toggle_trailing_blank_line(depfile)
tag_file = destination + "/TAG-INFO" tag_file = destination + "/TAG-INFO"
print(tag, file=file(tag_file, "w")) print >>file(tag_file, "w"), tag
o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname") o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname")
o.add_option("--skip-mozilla", dest="skip_mozilla", o.add_option("--skip-mozilla", dest="skip_mozilla",
@@ -139,7 +139,7 @@ except IndexError:
sys.exit(2) sys.exit(2)
if action in ('checkout', 'co'): if action in ('checkout', 'co'):
print("Warning: client.py checkout is obsolete.", file=sys.stderr) print >>sys.stderr, "Warning: client.py checkout is obsolete."
pass pass
elif action in ('update_nspr'): elif action in ('update_nspr'):
tag, = args[1:] tag, = args[1:]
+5 -5
View File
@@ -46,7 +46,7 @@ class ZipFile(zipfile.ZipFile):
date_time=time.localtime(time.time())) date_time=time.localtime(time.time()))
zinfo.compress_type = self.compression zinfo.compress_type = self.compression
# Add some standard UNIX file access permissions (-rw-r--r--). # Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16 zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
else: else:
zinfo = zinfo_or_arcname zinfo = zinfo_or_arcname
@@ -58,7 +58,7 @@ class ZipFile(zipfile.ZipFile):
# as the old, reuse the existing entry. # as the old, reuse the existing entry.
doSeek = False # store if we need to seek to the eof after overwriting doSeek = False # store if we need to seek to the eof after overwriting
if zinfo.filename in self.NameToInfo: if self.NameToInfo.has_key(zinfo.filename):
# Find the last ZipInfo with our name. # Find the last ZipInfo with our name.
# Last, because that's catching multiple overwrites # Last, because that's catching multiple overwrites
i = len(self.filelist) i = len(self.filelist)
@@ -109,14 +109,14 @@ class ZipFile(zipfile.ZipFile):
# adjust file mode if we originally just wrote, now we rewrite # adjust file mode if we originally just wrote, now we rewrite
self.fp.close() self.fp.close()
self.fp = open(self.filename, 'r+b') self.fp = open(self.filename, 'r+b')
all = [(zi, True) for zi in self.filelist] + \ all = map(lambda zi: (zi, True), self.filelist) + \
[(zi, False) for zi in self._remove] map(lambda zi: (zi, False), self._remove)
all.sort(lambda l, r: cmp(l[0].header_offset, r[0].header_offset)) all.sort(lambda l, r: cmp(l[0].header_offset, r[0].header_offset))
# empty _remove for multiple closes # empty _remove for multiple closes
self._remove = [] self._remove = []
lengths = [all[i+1][0].header_offset - all[i][0].header_offset lengths = [all[i+1][0].header_offset - all[i][0].header_offset
for i in range(len(all)-1)] for i in xrange(len(all)-1)]
lengths.append(self.end - all[-1][0].header_offset) lengths.append(self.end - all[-1][0].header_offset)
to_pos = 0 to_pos = 0
for (zi, keep), length in zip(all, lengths): for (zi, keep), length in zip(all, lengths):
Loaded 100 of 16646 files, more files were not shown because too many files have changed in this diff. Show more