diff options
author | binji@chromium.org <binji@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2012-05-10 18:38:50 +0000 |
---|---|---|
committer | binji@chromium.org <binji@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2012-05-10 18:38:50 +0000 |
commit | b6adedd93b1a72252cd84fd824f354130c4b694e (patch) | |
tree | f2ed5af2b1f2a739522cacba96da225def520b33 /native_client_sdk | |
parent | 6822759c3eaa0ef121d5ddcb53b56ec48d69d9ab (diff) | |
download | chromium_src-b6adedd93b1a72252cd84fd824f354130c4b694e.zip chromium_src-b6adedd93b1a72252cd84fd824f354130c4b694e.tar.gz chromium_src-b6adedd93b1a72252cd84fd824f354130c4b694e.tar.bz2 |
[NaCL SDK] Remove unused scripts from native_client_sdk/src/build_tools
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/10339006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@136350 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'native_client_sdk')
119 files changed, 0 insertions, 15606 deletions
diff --git a/native_client_sdk/src/build_tools/MkLink/MkLink.c b/native_client_sdk/src/build_tools/MkLink/MkLink.c deleted file mode 100644 index a821af0..0000000 --- a/native_client_sdk/src/build_tools/MkLink/MkLink.c +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright 2008, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include <windows.h> -#include <commctrl.h> -#include <nsis/pluginapi.h> -#include <winternl.h> - -enum { kLargeBuf = 1024, kSmallBuf = 256 } ; - -#if defined(_MSC_VER) -/* Ensure these are treated as functions and not inlined as intrinsics, or disable /Oi */ -#pragma warning(disable:4164) /* intrinsic function not declared */ -#pragma function(memcpy, memset, memcmp) -#endif - -HMODULE hNrDll = NULL; -NTSTATUS (NTAPI *fNtCreateFile) (PHANDLE FileHandle, - ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, - PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, - ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, - ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength); -NTSTATUS (NTAPI *fNtClose) (HANDLE Handle); - -HMODULE hKernel32 = NULL; -BOOL (WINAPI *fCreateHardLink) (TCHAR * linkFileName, - TCHAR * existingFileName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); -BOOL (WINAPI *fCreateSymbolicLink) (TCHAR * linkFileName, - TCHAR * existingFileName, DWORD flags); - -#undef CreateHardLink -#undef CreateSymbolicLink -#ifdef UNICODE -#define CreateHardLink "CreateHardLinkW" -#define CreateSymbolicLink "CreateSymbolicLinkW" -#else -#define CreateHardLink "CreateHardLinkA" -#define CreateSymbolicLink "CreateSymbolicLinkA" -#endif - -BOOL MakeHardLink(TCHAR *linkFileName, TCHAR *existingFileName) { - if (!hKernel32) - hKernel32 = LoadLibrary(_T("KERNEL32.DLL")); - if (hKernel32) { - if (!fCreateHardLink) - fCreateHardLink = GetProcAddress(hKernel32, CreateHardLink); - if (fCreateHardLink) - return fCreateHardLink(linkFileName, existingFileName, NULL); - } - return FALSE; -} - -BOOL MakeSymLink(TCHAR *linkFileName, TCHAR *existingFileName, BOOL dirLink) { - TCHAR *f1 = HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*kLargeBuf); - TCHAR *f2 = HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*kLargeBuf); - SECURITY_ATTRIBUTES sec_attr = { sizeof (SECURITY_ATTRIBUTES), NULL, FALSE}; - OBJECT_ATTRIBUTES obj_attr; - IO_STATUS_BLOCK io_block; - TCHAR *p, *q; - HANDLE f; - BOOL status; - if (!f1 || !f2) - return FALSE; - lstrcpy(f1, linkFileName); - for (p = f1; p[0]; p++) - if (p[0] == _T('/')) - p[0] = _T('\\'); - q = f1; - while (q[0]) { - p = q; - do { - q++; - } while (q[0] && q[0] != '\\'); - } - if (p[0] = '\\') { - TCHAR c = p[1]; - p[1] = 0; - status = GetVolumeInformation(f1, NULL, 0, NULL, NULL, NULL, - f2, sizeof(f2)); - p[1] = c; - } else { - status = GetVolumeInformation(NULL, NULL, 0, NULL, NULL, NULL, - f2, sizeof(f2)); - } - /* If it's NFS then we can create real symbolic link. */ - if (!lstrcmpi(f2, _T("NFS"))) { - lstrcpy(f2, existingFileName); - for (p = f2; p[0]; p++) - if (p[0] == _T('\\')) - p[0] = _T('/'); - if (!hNrDll) - hNrDll = LoadLibrary(_T("NTDLL.DLL")); - if (hNrDll) { - if (!fNtCreateFile) - fNtCreateFile = GetProcAddress(hNrDll, "NtCreateFile"); - if (!fNtClose) - fNtClose = GetProcAddress(hNrDll, "NtClose"); - if (fNtCreateFile && fNtClose) { - struct { - ULONG offset; - UCHAR flags; - UCHAR nameLength; - USHORT valueLength; - CHAR name[21]; - /* To prevent troubles with alignment */ - CHAR value[kLargeBuf*sizeof(WCHAR)]; - } *ea_info = HeapAlloc(GetProcessHeap(), - HEAP_ZERO_MEMORY, - sizeof(*ea_info)); - WCHAR *fn = HeapAlloc(GetProcessHeap(), - 0, - sizeof(TCHAR)*kLargeBuf); - UNICODE_STRING n = { lstrlen(f1), kLargeBuf, fn }; - ea_info->nameLength = 20; - lstrcpy(ea_info->name, "NfsSymlinkTargetName"); -#ifdef UNICODE - lstrcpy(fn, f1); - lstrcpy((LPWSTR)ea_info->value, existingFileName); -#else - MultiByteToWideChar(CP_ACP, 0, f1, -1, fn, kLargeBuf); - MultiByteToWideChar(CP_ACP, 0, existingFileName, -1, - (LPWSTR)ea_info->value, - sizeof(ea_info->value)/sizeof(WCHAR)); -#endif - ea_info->valueLength = - lstrlenW((LPWSTR)ea_info->value)*sizeof(WCHAR); - InitializeObjectAttributes(&obj_attr, &n, OBJ_CASE_INSENSITIVE, - NULL, NULL); - status = fNtCreateFile( - &f, FILE_WRITE_DATA | FILE_WRITE_EA | SYNCHRONIZE, &obj_attr, - &io_block, NULL, FILE_ATTRIBUTE_SYSTEM, FILE_SHARE_READ | - FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_CREATE, - FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT, - &ea_info, 1024 * sizeof (WCHAR)); - if (NT_SUCCESS(status)) { - fNtClose(f); - HeapFree(GetProcessHeap(), 0, fn); - HeapFree(GetProcessHeap(), 0, ea_info); - HeapFree(GetProcessHeap(), 0, f2); - HeapFree(GetProcessHeap(), 0, f1); - return TRUE; - } - HeapFree(GetProcessHeap(), 0, fn); - HeapFree(GetProcessHeap(), 0, ea_info); - } - } - } - lstrcpy(f2, existingFileName); - for (p = f2; p[0]; p++) - if (p[0] == _T('/')) - p[0] = _T('\\'); - if (!hKernel32) - hKernel32 = LoadLibrary(_T("KERNEL32.DLL")); - if (hKernel32) { - if (!fCreateSymbolicLink) - fCreateSymbolicLink = GetProcAddress(hKernel32, CreateSymbolicLink); - if (fCreateSymbolicLink) { - if (fCreateSymbolicLink(f1, f2, - dirLink ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) { - HeapFree(GetProcessHeap(), 0, f2); - HeapFree(GetProcessHeap(), 0, f1); - return TRUE; - } - } - } - if (dirLink) { - /* Ignore errors - file may already exist */ - CreateDirectory(f1, NULL); - f = CreateFile(f1, GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, - NULL ); - if (f != INVALID_HANDLE_VALUE) { - struct rp_info { - DWORD tag; - DWORD dataLength; - WORD reserved1; - WORD targetLength; - WORD targetMaxLength; - WORD reserved2; - WCHAR target[kLargeBuf+4]; - } *rp_info = HeapAlloc(GetProcessHeap(), - HEAP_ZERO_MEMORY, - sizeof(*rp_info)); - DWORD len; - WCHAR *startlink, *endlink; - rp_info->tag = IO_REPARSE_TAG_MOUNT_POINT; - rp_info->target[0] = L'\\'; - rp_info->target[1] = L'?'; - rp_info->target[2] = L'?'; - rp_info->target[3] = L'\\'; - if (((f2[0] == _T('\\')) && (f2[1] == _T('\\'))) || - ((f2[1] == _T(':')) && (f2[2] == _T('\\')))) { -#ifdef UNICODE - lstrcpy(rp_info->target+4, f2); -#else - MultiByteToWideChar(CP_ACP, 0, f2, -1, - rp_info->target+4, kLargeBuf); -#endif - } else { -#ifdef UNICODE - GetFullPathNameW(f1, 1024, rp_info->target+4, &startlink); - lstrcpy(startlink, f2); -#else - MultiByteToWideChar(CP_ACP, 0, f1, -1, - (LPWSTR)f1, kLargeBuf/sizeof(WCHAR)); - GetFullPathNameW(f1, 1024, rp_info->target+4, &startlink); - MultiByteToWideChar(CP_ACP, 0, f2, -1, - startlink, kLargeBuf+4-(startlink-rp_info->target)); -#endif - } - /* Remove "XXX/../" and replace "/" with "\" */ - for (startlink = endlink = rp_info->target+4; - endlink[0]; startlink++, endlink++) { - startlink[0] = endlink[0]; - if ((startlink[0] == L'\\') && - (startlink[-1] == L'.') && - (startlink[-2] == L'.')) { - for (startlink--; startlink > rp_info->target+4 && - startlink[0] != L'\\'; startlink--) - { } - for (startlink--; startlink > rp_info->target+4 && - startlink[0] != L'\\'; startlink--) - { } - if (startlink < rp_info->target+4) - startlink = rp_info->target+4; - } - } - startlink[0] = endlink[0]; - rp_info->targetLength = lstrlenW(rp_info->target)*sizeof(WCHAR); - rp_info->targetMaxLength = rp_info->targetLength+sizeof(WCHAR); - rp_info->dataLength = rp_info->targetMaxLength - +FIELD_OFFSET(struct rp_info, target) - -FIELD_OFFSET(struct rp_info, reserved1) - +sizeof(WCHAR); - if (DeviceIoControl(f, 0x900A4, rp_info, - rp_info->dataLength - +FIELD_OFFSET(struct rp_info, reserved1), - NULL, 0, &len, NULL)) { - CloseHandle(f); - HeapFree(GetProcessHeap(), 0, rp_info); - HeapFree(GetProcessHeap(), 0, f2); - HeapFree(GetProcessHeap(), 0, f1); - return TRUE; - } - CloseHandle(f); - RemoveDirectory(f1); - HeapFree(GetProcessHeap(), 0, rp_info); - } - } - for (p = f2; p[0]; p++) - if (p[0] == _T('\\')) - p[0] = _T('/'); - f = CreateFile(f1, GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_SYSTEM, NULL); - if (f != INVALID_HANDLE_VALUE) { - struct { - WCHAR sig[4]; - WCHAR value[kLargeBuf]; - } *link_info = HeapAlloc(GetProcessHeap(), - HEAP_ZERO_MEMORY, - sizeof(*link_info)); - DWORD towrite, written; - link_info->sig[0] = 0x6e49; - link_info->sig[1] = 0x7874; - link_info->sig[2] = 0x4e4c; - link_info->sig[3] = 0x014b; -#ifdef UNICODE - lstrcpy(link_info->value, f2); -#else - MultiByteToWideChar(CP_ACP, 0, f2, -1, link_info->value, kLargeBuf); -#endif - towrite = lstrlenW(link_info->value)*sizeof(WCHAR)+sizeof(link_info->sig); - WriteFile(f, link_info, towrite, &written, NULL); - CloseHandle(f); - if (written == towrite) { - HeapFree(GetProcessHeap(), 0, link_info); - HeapFree(GetProcessHeap(), 0, f2); - HeapFree(GetProcessHeap(), 0, f1); - return TRUE; - } - HeapFree(GetProcessHeap(), 0, link_info); - } - HeapFree(GetProcessHeap(), 0, f2); - HeapFree(GetProcessHeap(), 0, f1); - return FALSE; -} - -HINSTANCE instance; - -HWND parent, list; - -/* - * Show message in NSIS details window. - */ -void NSISprint(const TCHAR *str) { - if (list && *str) { - LVITEM item = { - /* mask */ LVIF_TEXT, - /* iItem */ SendMessage(list, LVM_GETITEMCOUNT, 0, 0), - /* iSubItem */ 0, /* state */ 0, /* stateMask */ 0, - /* pszText */ (TCHAR *) str, /* cchTextMax */ 0, - /* iImage */ 0, /* lParam */ 0, /* iIndent */ 0, - /* iGroupId */ 0, /* cColumns */ 0, /* puColumns */ NULL, - /* piColFmt */ NULL, /* iGroup */ 0}; - ListView_InsertItem(list, &item); - ListView_EnsureVisible(list, item.iItem, 0); - } -} - -enum linktype { HARDLINK, SOFTLINKD, SOFTLINKF }; - -void makelink(HWND hwndParent, int string_size, TCHAR *variables, - stack_t **stacktop, extra_parameters *extra, enum linktype type) { - TCHAR *msg = HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*kLargeBuf); - TCHAR *from = HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*kSmallBuf); - TCHAR *to = HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*kSmallBuf); - TCHAR *msgFormat = - type == HARDLINK ? _T("Link: \"%s\" to \"%s\"%s") : - type == SOFTLINKD ? _T("Symbolic Directory Link: \"%s\" to \"%s\"%s") : - _T("Symbolic Link: \"%s\" to \"%s\"%s"); - BOOL res; - parent = hwndParent; - list = FindWindowEx(FindWindowEx(parent, NULL, _T("#32770"), NULL), - NULL, _T("SysListView32"), NULL); - - EXDLL_INIT(); - - if (!msg || !from || !to) { - MessageBox(parent, _T("Fatal error: no memory for MkLink"), 0, MB_OK); - } - - if (popstringn(from, kSmallBuf)) { - MessageBox(parent, - _T("Usage: MkLink::Hard \"to_file\" \"from_file\" "), 0, MB_OK); - } - - if (popstringn(to, kSmallBuf)) { - MessageBox(parent, - _T("Usage: MkLink::Hard \"fo_file\" \"from_file\" "),0,MB_OK); - } - - switch (type) { - case HARDLINK: - res = MakeHardLink(from, to); - break; - case SOFTLINKD: - res = MakeSymLink(from, to, TRUE); - break; - case SOFTLINKF: - res = MakeSymLink(from, to, FALSE); - break; - } - wsprintf(msg, msgFormat, to, from, res ? _T("") : _T(" - fail...")); - NSISprint(msg); - - HeapFree(GetProcessHeap(), 0, to); - HeapFree(GetProcessHeap(), 0, from); - HeapFree(GetProcessHeap(), 0, msg); -} - -void __declspec(dllexport) Hard(HWND hwndParent, int string_size, - TCHAR *variables, stack_t **stacktop, - extra_parameters *extra) { - makelink(hwndParent, string_size, variables, stacktop, extra, HARDLINK); -} - -void __declspec(dllexport) SoftD(HWND hwndParent, int string_size, - TCHAR *variables, stack_t **stacktop, - extra_parameters *extra) { - makelink(hwndParent, string_size, variables, stacktop, extra, SOFTLINKD); -} - -void __declspec(dllexport) SoftF(HWND hwndParent, int string_size, - TCHAR *variables, stack_t **stacktop, - extra_parameters *extra) { - makelink(hwndParent, string_size, variables, stacktop, extra, SOFTLINKF); -} - -BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { - instance = hInst; - return TRUE; -} diff --git a/native_client_sdk/src/build_tools/MkLink/MkLink.sln b/native_client_sdk/src/build_tools/MkLink/MkLink.sln deleted file mode 100644 index 05a60ff..0000000 --- a/native_client_sdk/src/build_tools/MkLink/MkLink.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MkLink", "MkLink.vcproj", "{5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug Unicode|Win32 = Debug Unicode|Win32 - Debug|Win32 = Debug|Win32 - Release Unicode|Win32 = Release Unicode|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Debug Unicode|Win32.ActiveCfg = Debug Unicode|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Debug Unicode|Win32.Build.0 = Debug Unicode|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Debug|Win32.ActiveCfg = Debug|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Debug|Win32.Build.0 = Debug|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Release Unicode|Win32.ActiveCfg = Release Unicode|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Release Unicode|Win32.Build.0 = Release Unicode|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Release|Win32.ActiveCfg = Release|Win32 - {5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/native_client_sdk/src/build_tools/MkLink/MkLink.vcproj b/native_client_sdk/src/build_tools/MkLink/MkLink.vcproj deleted file mode 100644 index 0067ad6..0000000 --- a/native_client_sdk/src/build_tools/MkLink/MkLink.vcproj +++ /dev/null @@ -1,484 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="9.00" - Name="MkLink" - ProjectGUID="{5E3E2AFD-1D6B-4997-A9B5-8ECBC8F6C31A}" - RootNamespace="MkLink" - TargetFrameworkVersion="0" - > - <Platforms> - <Platform - Name="Win32" - /> - </Platforms> - <ToolFiles> - </ToolFiles> - <Configurations> - <Configuration - Name="Release|Win32" - OutputDirectory=".\Release" - IntermediateDirectory=".\Release" - ConfigurationType="2" - InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" - UseOfMFC="0" - ATLMinimizesCRunTimeLibraryUsage="false" - CharacterSet="2" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - PreprocessorDefinitions="NDEBUG" - MkTypLibCompatible="true" - SuppressStartupBanner="true" - TargetEnvironment="1" - TypeLibraryName=".\Release/MkLink.tlb" - HeaderFileName="" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="1" - InlineFunctionExpansion="0" - AdditionalIncludeDirectories="." - PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;_USRDLL;EXDLL_EXPORTS;NSISCALL=__stdcall" - StringPooling="true" - RuntimeLibrary="2" - BufferSecurityCheck="false" - EnableFunctionLevelLinking="true" - PrecompiledHeaderFile=".\Release/MkLink.pch" - AssemblerListingLocation=".\Release/" - ObjectFile=".\Release/" - ProgramDataBaseFileName=".\Release/" - WarningLevel="3" - SuppressStartupBanner="true" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - PreprocessorDefinitions="NDEBUG" - Culture="1033" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="odbc32.lib odbccp32.lib nsis\pluginapi.lib" - OutputFile=".\Release/MkLink.dll" - LinkIncremental="1" - SuppressStartupBanner="true" - GenerateManifest="false" - IgnoreAllDefaultLibraries="true" - IgnoreDefaultLibraryNames="libc.lib" - ProgramDatabaseFile=".\Release/MkLink.pdb" - OptimizeForWindows98="1" - EntryPointSymbol="DllMain" - RandomizedBaseAddress="1" - DataExecutionPrevention="0" - ImportLibrary=".\Release/MkLink.lib" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - SuppressStartupBanner="true" - OutputFile=".\Release/MkLink.bsc" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - <Configuration - Name="Debug|Win32" - OutputDirectory=".\Debug" - IntermediateDirectory=".\Debug" - ConfigurationType="2" - InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" - UseOfMFC="0" - ATLMinimizesCRunTimeLibraryUsage="false" - CharacterSet="2" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - PreprocessorDefinitions="_DEBUG" - MkTypLibCompatible="true" - SuppressStartupBanner="true" - TargetEnvironment="1" - TypeLibraryName=".\Debug/MkLink.tlb" - HeaderFileName="" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories="." - PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;_USRDLL;EXDLL_EXPORTS;NSISCALL=__stdcall" - MinimalRebuild="true" - BasicRuntimeChecks="0" - RuntimeLibrary="3" - BufferSecurityCheck="false" - PrecompiledHeaderFile=".\Debug/MkLink.pch" - AssemblerListingLocation=".\Debug/" - ObjectFile=".\Debug/" - ProgramDataBaseFileName=".\Debug/" - WarningLevel="3" - SuppressStartupBanner="true" - DebugInformationFormat="4" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - PreprocessorDefinitions="_DEBUG" - Culture="1033" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="odbc32.lib odbccp32.lib nsis\pluginapi.lib" - OutputFile=".\Debug/MkLink.dll" - LinkIncremental="2" - SuppressStartupBanner="true" - GenerateManifest="false" - IgnoreAllDefaultLibraries="true" - IgnoreDefaultLibraryNames="" - GenerateDebugInformation="true" - ProgramDatabaseFile=".\Debug/MkLink.pdb" - EntryPointSymbol="DllMain" - RandomizedBaseAddress="1" - DataExecutionPrevention="0" - ImportLibrary=".\Debug/MkLink.lib" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - SuppressStartupBanner="true" - OutputFile=".\Debug/MkLink.bsc" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - <Configuration - Name="Release Unicode|Win32" - OutputDirectory="$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" - UseOfMFC="0" - ATLMinimizesCRunTimeLibraryUsage="false" - CharacterSet="1" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - PreprocessorDefinitions="NDEBUG" - MkTypLibCompatible="true" - SuppressStartupBanner="true" - TargetEnvironment="1" - TypeLibraryName=".\Release Unicode/MkLink.tlb" - HeaderFileName="" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="1" - InlineFunctionExpansion="0" - AdditionalIncludeDirectories="." - PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;_USRDLL;EXDLL_EXPORTS;NSISCALL=__stdcall" - StringPooling="true" - RuntimeLibrary="2" - BufferSecurityCheck="false" - EnableFunctionLevelLinking="true" - PrecompiledHeaderFile=".\Release Unicode/MkLink.pch" - AssemblerListingLocation=".\Release Unicode/" - ObjectFile=".\Release Unicode/" - ProgramDataBaseFileName=".\Release Unicode/" - WarningLevel="3" - SuppressStartupBanner="true" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - PreprocessorDefinitions="NDEBUG" - Culture="1033" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="odbc32.lib odbccp32.lib nsis\pluginapi.lib" - OutputFile=".\Release Unicode/MkLink.dll" - LinkIncremental="1" - SuppressStartupBanner="true" - GenerateManifest="false" - IgnoreAllDefaultLibraries="true" - IgnoreDefaultLibraryNames="libc.lib" - ProgramDatabaseFile=".\Release Unicode/MkLink.pdb" - OptimizeForWindows98="1" - EntryPointSymbol="DllMain" - RandomizedBaseAddress="1" - DataExecutionPrevention="0" - ImportLibrary=".\Release Unicode/MkLink.lib" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - SuppressStartupBanner="true" - OutputFile=".\Release Unicode/MkLink.bsc" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - <Configuration - Name="Debug Unicode|Win32" - OutputDirectory="$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops" - UseOfMFC="0" - ATLMinimizesCRunTimeLibraryUsage="false" - CharacterSet="1" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - PreprocessorDefinitions="_DEBUG" - MkTypLibCompatible="true" - SuppressStartupBanner="true" - TargetEnvironment="1" - TypeLibraryName=".\Debug Unicode/MkLink.tlb" - HeaderFileName="" - /> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories="." - PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;_USRDLL;EXDLL_EXPORTS;NSISCALL=__stdcall" - MinimalRebuild="true" - BasicRuntimeChecks="0" - RuntimeLibrary="3" - BufferSecurityCheck="false" - PrecompiledHeaderFile=".\Debug Unicode/MkLink.pch" - AssemblerListingLocation=".\Debug Unicode/" - ObjectFile=".\Debug Unicode/" - ProgramDataBaseFileName=".\Debug Unicode/" - WarningLevel="3" - SuppressStartupBanner="true" - DebugInformationFormat="4" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - PreprocessorDefinitions="_DEBUG" - Culture="1033" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="odbc32.lib odbccp32.lib nsis\pluginapi.lib" - OutputFile=".\Debug Unicode/MkLink.dll" - LinkIncremental="2" - SuppressStartupBanner="true" - GenerateManifest="false" - IgnoreAllDefaultLibraries="true" - IgnoreDefaultLibraryNames="" - GenerateDebugInformation="true" - ProgramDatabaseFile=".\Debug Unicode/MkLink.pdb" - EntryPointSymbol="DllMain" - RandomizedBaseAddress="1" - DataExecutionPrevention="0" - ImportLibrary=".\Debug Unicode/MkLink.lib" - TargetMachine="1" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - SuppressStartupBanner="true" - OutputFile=".\Debug Unicode/MkLink.bsc" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <Filter - Name="Source Files" - Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" - > - <File - RelativePath=".\MkLink.c" - > - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories="" - PreprocessorDefinitions="" - /> - </FileConfiguration> - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories="" - PreprocessorDefinitions="" - /> - </FileConfiguration> - <FileConfiguration - Name="Debug Unicode|Win32" - > - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories="" - PreprocessorDefinitions="" - /> - </FileConfiguration> - <FileConfiguration - Name="Release Unicode|Win32" - > - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories="" - PreprocessorDefinitions="" - /> - </FileConfiguration> - </File> - </Filter> - <Filter - Name="Header Files" - Filter="h;hpp;hxx;hm;inl" - > - <File - RelativePath="nsis\pluginapi.h" - > - </File> - </Filter> - <Filter - Name="Resource Files" - Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" - > - </Filter> - </Files> - <Globals> - </Globals> -</VisualStudioProject> diff --git a/native_client_sdk/src/build_tools/MkLink/Release Unicode/MkLink.dll b/native_client_sdk/src/build_tools/MkLink/Release Unicode/MkLink.dll Binary files differdeleted file mode 100755 index c4c604d..0000000 --- a/native_client_sdk/src/build_tools/MkLink/Release Unicode/MkLink.dll +++ /dev/null diff --git a/native_client_sdk/src/build_tools/README_NSIS.txt b/native_client_sdk/src/build_tools/README_NSIS.txt deleted file mode 100644 index e51141a..0000000 --- a/native_client_sdk/src/build_tools/README_NSIS.txt +++ /dev/null @@ -1,59 +0,0 @@ -Note: This whole process takes about 1:30 to 2 hours for someone who is pretty -familiar with it. If this is your first attempt, it's best to plan for this to -take the whole day. - -Step 0: Make sure your toolchain dir is clean. - The easiest way to do this is to remove these dirs and then do a gclient sync: - rmdir src\toolchain - rmdir src\third_party - scons -c examples - gclient sync - Or: start with a fresh checkout from nothing. - -Step 1: Generate a base copy of make_native_client_sdk.nsi - Edit generate_windows_installer.py so that it runs everything up to - make_native_client_sdk2.sh. - Easiest: add a 'break' after waiting for make_native_client_sdk.sh subprocess. - This is around line 194. - In src, python build_tools\generate_installers.py --development - This will produce build_tools\make_native_client_sdk.nsi - -Step 3: Create a back-up and an editable copy of make_native_client_sdk.nsi - Make 2 copies of make_native_client_sdk.nsi: - copy make_native_client_sdk.nsi make_native_client_sdk-orig.nsi - copy make_native_client_sdk.nsi make_native_client_sdk-new.nsi - -Step 4: Edit the .nsi file to contain the appropriate changes. - Edit the "-new" version of make_native_client_sdk. - Manually apply the patch in nsi_patch.txt (and any other necessary edits) to - make_native_client_sdk-new.nsi - -Step 5: Create the new patch file. - cd build_tools - copy nsi_patch.txt nsi_patch-old.txt - ..\third_party\cygwin\bin\diff -Naur make_native_client_sdk-orig.nsi make_native_client_sdk-new.nsi > nsi_patch.txt - Note: the order of -orig and -new is important. - -Step 6: Edit the patch file. - Edit nsi_patch.txt - Change every occurrence of native_client_sdk_0_x_y to %NACL_SDK_FULL_NAME% - Change every occurrence of third_party\cygwin\ to %$CYGWIN_DIR% - Note: the trailing '\' on third_party\cygwin_dir\ is important. - At the top of the file, change the diff file names to both be - make_native_client_sdk.nsi - -Step 7: Test the patch. - (In the build_tools dir): - copy make_native_client_sdk-orig.nsi make_native_client_sdk.nsi - ..\third_party\cygwin\bin\bash make_native_client_sdk2.sh -V 0.x.y -v -n - Note: |x| and |y| have to match the original values in - native_client_sdk_0_x_y from Step 6. - Note: This step can take a long time (5 min or more). - -Step 8: Test the installer. - Step 7 should have produced nacl_sdk.exe in the root of the nacl-sdk project. - Run this from the Finder, and install the SDK to see if it works. - -Step 9: Upload the changes. - If everything works, make a CL. - REMEMBER: remove the 'break' statement you added in Step 1. diff --git a/native_client_sdk/src/build_tools/apply_patch.py b/native_client_sdk/src/build_tools/apply_patch.py deleted file mode 100755 index 13ffc9c..0000000 --- a/native_client_sdk/src/build_tools/apply_patch.py +++ /dev/null @@ -1,533 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -""" Utility for applying svn-diff-style patches to files. - -This file contains a collection of classes for parsing svn-diff patch files -and applying these patches to files in a directory. The main API class is -ApplyPatch. It has two entry point: method Parse to parse a patch file and -method Apply to apply that patch to a base directory. - -Most other classes are internal only. Each class corresponds to a structure in -the patch file, such as _Range, which corresponds to the range line identified -by the heading and traling '@@'. -""" - -__author__ = 'gwink@google.com (Georges Winkenbach)' - -import os -import re -import shutil -import sys -import tempfile - -# Constants: regular expressions for parsing patch lines. -RE_HEADER_ORIGINAL_FILE = re.compile('---\s+([^\s]+)') -RE_HEADER_OUT_FILE = re.compile('\+\+\+\s+([^\s]+)') -RE_RANGE = re.compile('@@\s*-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s*@@') - -# Constants: type of diff lines. -CONTEXTUAL_DIFF_LINE = 0 -ADDED_DIFF_LINE = 1 -DELETED_DIFF_LINE = 2 -NOT_A_DIFF_LINE = 3 - - -class Error(Exception): - ''' Exceptions raised in this file. - - Attributes: - error: a string that describes the error. - context: a string that shows the context where the error occured. - ''' - - def __init__(self, context='', error='error'): - ''' Init Error with context and error info. ''' - super(Error, self).__init__(context, error) - self.error = error - self.context = context - - def __str__(self): - out = 'Error %s.' % self._error - return out - - -class _Range(object): - ''' Corresponds to a range info in the patch file. - - _Range encapsulates the source- and destination-file range information - found in the patch file. - - Attributes: - src_start_line: index to the first line in the source file. - src_line_count: the number of lines in the source file. - dest_start_line: index to the first line in the destination file. - dest_line_count: the number of lines in the destination file. - ''' - def __init__(self): - ''' Init _Range with empty source and destination range info. ''' - self.src_start_line = 0 - self.src_line_count = 0 - self.dest_start_line = 0 - self.dest_line_count = 0 - - def Parse(self, diff_lines): - ''' Parse a range diff line. - - Parse the line at index 0 in diff_lines as a range-info line and set the - range info accordingly. Raise an Error exception if the line is not a valid - range line. If successful, the line at index 0 is removed from diff_lines. - - Arguments: - diff_lines: a list of diff lines read from the patch file. - ''' - match = re.match(RE_RANGE, diff_lines[0]) - if not match: - raise Error(context=diff_lines[0], error='Bad range info') - - # Range in source file. The line count is optional and defaults to 1. - self.src_start_line = int(match.group(1)) - self.src_line_count = 1 - if (match.group(2)): - self.src_line_count = int(match.group(2)) - # Range in destination file. The line count is optional and defaults to 1. - self.dest_start_line = int(match.group(3)) - self.dest_line_count = 1 - if (match.group(4)): - self.dest_line_count = int(match.group(4)) - - diff_lines.pop(0) - - -class _ChangeHunk(object): - ''' A ChangeHunk is a range followed by a series of diff lines in the patch. - - Encapsulate the info represented by a range line and the subsequent diff - lines in the patch file. - - Attributes: - range: the range info, an instance of _Range - lines: a list containing the diff lines that follow the range info in - the patch file. - ''' - - def __init__(self): - ''' Init an empty _ChangeHunk. ''' - self.range = None - self.lines = [] - - @staticmethod - def _DiffLineType(line): - ''' Helper function that determines the type of a diff line. - - Arguments: - line: the diff line whose type must be determined. - Return: - One of CONTEXTUAL_DIFF_LINE, DELETED_DIFF_LINE, ADDED_DIFF_LINE or - NOT_A_DIFF_LINE. - ''' - # A contextual line starts with a space or can be an empty line. - if line[0] in [' ', '\n', '\r']: - return CONTEXTUAL_DIFF_LINE - # A delete line starts with '-'; but '---' denotes a header line. - elif line[0] == '-' and not line.startswith('---'): - return DELETED_DIFF_LINE - # A add line starts with '+'; but '+++' denotes a header line. - elif line[0] == '+' and not line.startswith('+++'): - return ADDED_DIFF_LINE - # Anything else is not a diff line. - else: - return NOT_A_DIFF_LINE - - def _ParseLines(self, diff_lines): - ''' Parse diff lines for a change-hunk. - - Parse the diff lines, update the change-hunk info accordingly and validate - the hunk info. The first line in diff_lines should be the line that follows - the range info in the patch file.. The subsequent lines should be diff - lines. Raise an Error exception if the hunk info doesn't validate. Matched - lines are removed from diff_lines. - - Arguments: - diff_lines: a list of diff lines read from the patch file. - ''' - src_line_count = 0 - dest_line_count = 0 - index = 0 - for index, line in enumerate(diff_lines): - line_type = self._DiffLineType(line) - if line_type == CONTEXTUAL_DIFF_LINE: - # Contextual line (maybe an empty line). - src_line_count += 1 - dest_line_count += 1 - elif line_type == DELETED_DIFF_LINE: - # Deleted line. - src_line_count += 1 - elif line_type == ADDED_DIFF_LINE: - # Added line. - dest_line_count += 1 - else: - # Done. - break; - - # Store each valid diff line into the local list. - self.lines.append(line) - - # Remove lines that have been consumed from list. - del diff_lines[0:index] - - # Validate the change hunk. - if (src_line_count != self.range.src_line_count) or (dest_line_count != - self.range.dest_line_count): - raise Error(context=self.lines[0], - error='Range info doesn\'t match lines that follow') - - def Parse(self, diff_lines): - ''' Parse a change-hunk. - - Parse the range and subsequent diff lines for a change hunk. The first line - in diff_lines should be a range line starting with @@. Raise an Error - exception if the hunk info doesn't validate. Matched lines are removed from - diff_lines. - - Arguments: - diff_lines: a list of diff lines read from the patch file. - ''' - self.range = _Range() - self.range.Parse(diff_lines) - self._ParseLines(diff_lines) - - def Apply(self, line_num, in_file, out_file): - ''' Apply the change hunk to in_file. - - Apply the change hunk to in_file, outputing the result to out_file. Raise a - Error exception if any inconsistency is detected. - - Arguments: - line_num: the last line number read from in_file, or 0 if the file has not - yet been read from. - in_file: the input (source) file. Maybe None if the hunk only adds - lines to a new file. - out_file: the output (destination) file. - Return: - the line number of the last line read (consumed) from in_file. - ''' - # If range starts at N, consume all lines from line_num to N-1. Don't read - # line N yet; what we'll do with it depend on the first diff line. Each - # line is written to the output file. - while line_num < self.range.src_start_line - 1: - out_file.write(in_file.readline()) - line_num = line_num + 1 - - for diff_line in self.lines: - diff_line_type = self._DiffLineType(diff_line) - if diff_line_type == CONTEXTUAL_DIFF_LINE: - # Remove the contextual-line marker, if present. - if diff_line[0] == ' ': - diff_line = diff_line[1:] - # Contextual line should match the input line. - line = in_file.readline() - line_num = line_num + 1 - if not line == diff_line: - raise Error(context=line, error='Contextual line mismatched') - out_file.write(line) - elif diff_line_type == DELETED_DIFF_LINE: - # Deleted line: consume it from in_file, verify that it matches the - # diff line (with marker removed), do not write it to out_file. - line = in_file.readline() - line_num = line_num + 1 - if not line == diff_line[1:]: - raise Error(context=line, error='Deleted line mismatched') - elif diff_line_type == ADDED_DIFF_LINE: - # Added line: simply write it to out_file, without the add-line marker. - diff_line = diff_line[1:] - out_file.write(diff_line) - else: - # Not a valid diff line; this is an internal error. - raise Error(context=diff_line, error='Unexpected diff line') - - return line_num - - -class _PatchHeader(object): - ''' The header portion of a patch. - - Encapsulates a header, the two lines prefixed with '---' and '+++' before - a series of change hunks. - - Attributes: - in_file_name: the file name for the input (source) file. - out_file_name: the file name for the output (new) file. - ''' - def __init__(self): - ''' Init _PatchHeader with no filenames. ''' - self.in_file_name = None - self.out_file_name = None - - def Parse(self, diff_lines): - ''' Parse header info. - - Parse the header information, the two lines starting with '---' and '+++' - respectively. Gather the in (source) file name and out (new) file name - locally. The first line in diff_lines should be a header line starting - with '---'. Raise an Error exception if no header info is found. Matched - lines are consumed (remove from diff_lines). - - Arguments: - diff_lines: a list of diff lines read from the patch. - ''' - match = self._MatchHeader(RE_HEADER_ORIGINAL_FILE, diff_lines) - self.in_file_name = match.group(1) - match = self._MatchHeader(RE_HEADER_OUT_FILE, diff_lines) - self.out_file_name = match.group(1) - - def _MatchHeader(self, header_re, diff_lines): - ''' Helper function to match a single header line using regular expression - header_re. - ''' - match = re.match(header_re, diff_lines[0]) - if not match: - raise Error(context=diff_lines[0], error='Bad header') - diff_lines.pop(0) - return match - - -class _Patch(object): - ''' A _Patch is the header and all the change hunks pertaining to a single - file. - - Encapsulates all the information for a single-file patch, including the - header and all the subsequent change hunks found in the patch file. - - Attributes: - header: the header info, an instance of _PatchHeader. - hunks: a list of _ChangeHunks. - ''' - def __init__(self): - ''' Init an empty _Patch. ''' - self.header = None - self.hunks = [] - - def _SrcFileIsOptional(self): - ''' Helper function that returns true if it's ok for this patch to not have - source file. (It's ok to not have a source file if the patch has a - single hunk and that hunk only adds lines to the destination file. - ''' - return len(self.hunks) == 1 and self.hunks[0].range.src_line_count == 0 - - def Parse(self, diff_lines): - ''' Parse a complete single-file patch. - - Parse a complete patch for a single file, updating the local patch info - accordingly. Raise an Error exception if any inconsistency is detected. - Patch lines from diff_lines are consumed as they are matched. The first line - in diff_lines should be a header line starting with '---'. - - Arguments: - diff_lines: a list diff lines read from the patch file. - ''' - # Parse the patch header - self.header = _PatchHeader() - self.header.Parse(diff_lines) - # The next line must be a range. - if not diff_lines[0].startswith('@@'): - raise Error(context=diff_lines[0], error='Bad range info') - - # Parse the range. - while diff_lines: - if diff_lines[0].startswith('@@'): - hunk = _ChangeHunk() - hunk.Parse(diff_lines) - self.hunks.append(hunk) - else: - break - - def Apply(self, base_path): - ''' Apply the patch to the directory base_path. - - Apply the single-file patch using base_path as the root directory. - The source file name, extracted from the header, is appended to base_path - to derive the full path to the file to be patched. The file is patched - in-place. That is, if the patching is successful, the source file path - will conatin the patched file when this method exits. - - Argument: - base_path: path to the root directory. - ''' - # Form an absolute path to the source file and verify that it exists if - # it is required. - in_path = os.path.abspath( - os.path.join(base_path, self.header.in_file_name)) - if not os.path.exists(in_path) and not self._SrcFileIsOptional(): - raise Error(context=in_path, error='Original file doesn\'t exists') - - in_file = None - out_file = None - temp_out_path = None - try: - # Patch the input file into a temporary output file. - if os.path.exists(in_path): - in_file = open(in_path) - with tempfile.NamedTemporaryFile(delete=False) as out_file: - line_num = 0 - # Apply all the change hunks. - for hunk in self.hunks: - line_num = hunk.Apply(line_num, in_file, out_file) - - # We ran out of change hunks, but there may be lines left in the input - # file. Copy them to the output file. - if in_file: - for line in in_file: - out_file.write(line) - - # Close the input and output files; retain the temporary output file - # path so we can rename it later. - temp_out_path = out_file.name - out_file.close() - out_file = None - if in_file: - in_file.close() - in_file = None - - # Rename the output file to the original input file name. Windows - # forces us to delete the original file first. Linux is fussy about - # renaming a temp file. So we copy and delete instead. - if os.path.exists(in_path): - os.remove(in_path) - shutil.copy(temp_out_path, in_path) - os.remove(temp_out_path) - except: - raise - finally: - if in_file: in_file.close() - if out_file: out_file.close() - if temp_out_path and os.path.exists(temp_out_path): - os.remove(temp_out_path) - - -class _PatchSet(object): - ''' All the patches from a patch file. - - Encapsulates all the patches found in a patch file. - ''' - def __init__(self): - self._patches = [] - - def Parse(self, patch_file): - ''' Parse all the patches in a patch file. - - Parse all the patches from a given patch file and store each patch info - into list _patches. Raise an Error exception if an inconsistency is found. - - Argument: - patch_file: a file descriptor for the patch file, ready for reading. - ''' - diff_lines = patch_file.readlines() - while diff_lines: - # Look for the start of a header. - if diff_lines[0].startswith('---'): - patch = _Patch() - patch.Parse(diff_lines) - self._patches.append(patch) - else: - # Skip unrecognized lines. - diff_lines.pop(0) - - def Apply(self, base_path): - ''' Apply all the patches. - - Apply all the patches to files using base_path as the root directory. - Raise an Error exception if an inconsistency is found. Files are patched - in-place. - - Argument: - base_path: path to the root directory in which to apply the patches. - ''' - for patch in self._patches: - patch.Apply(base_path) - - -class ApplyPatch(object): - ''' Read a patch fileand apply it to a given base directory. - - ApplyPatch provides support for reading and parsing a patch file and - applying the patches to files relative to a given base directory. - ''' - - def __init__(self): - ''' Init ApplyPatch to empty. ''' - self._patch_set = None - - def Parse(self, patch_path): - ''' Parse a patch file. - - Parse the patch file at path patch_path and store the patch info into - _patch_set. Parsing-error messages are sent to stderr. - - Argument: - patch_path: path to the patch file. - - Return: - True if the patch file is successfully read and ready to apply and False - otherwise. - ''' - try: - if not os.path.exists(patch_path): - raise Error(context=patch_path, error="Patch file not found"); - with open(patch_path) as patch_file: - self._patch_set = _PatchSet() - self._patch_set.Parse(patch_file) - - except Error as (error): - sys.stderr.write('Patch error: %s.\n' % error.error) - sys.stderr.write('At line: %s\n' % error.context) - return False - - return True - - def Apply(self, base_path): - ''' Apply a patch to files. - - Apply an entire set of patches to files using base_path as the base - directory. The files are patched in place. Patching-error message are output - to stderr. - - Argument: - base_path: path to the base directory in which to apply the patches. - - Return: - True if all the patches are applied successfully and False otherwise. - ''' - try: - if not os.path.exists(base_path): - raise Error(context=base_path, error="Invalid base path"); - if not os.path.isdir(base_path): - raise Error(context=base_path, error="Base path is not a directory"); - self._patch_set.Apply(base_path) - - except Error as (error): - sys.stderr.write('Processing error: %s.\n' % error.error) - sys.stderr.write('>>> %s\n' % error.context) - return False - - return True - - -def main(argv): - apply_patch = ApplyPatch() - if apply_patch.Parse(os.path.abspath(argv[0])): - if apply_patch.Apply(os.path.abspath(argv[1])): - sys.exit(0) - - sys.exit(1) - - -if __name__ == '__main__': - if len(sys.argv) != 3: - sys.stderr.write('Usage: %s patch-file base-dir\n' % - os.path.basename(sys.argv[0])) - sys.exit(1) - else: - main(sys.argv[1:]) diff --git a/native_client_sdk/src/build_tools/build.scons b/native_client_sdk/src/build_tools/build.scons deleted file mode 100644 index 156d05c..0000000 --- a/native_client_sdk/src/build_tools/build.scons +++ /dev/null @@ -1,304 +0,0 @@ -#! -*- python -*- -# -# Copyright (c) 2011 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Build file for running scripts in the build_tools directory - -Adapted from scons documentation: http://www.scons.org/wiki/UnitTests -and from ../project_templates/test.scons -""" - -__author__ = 'mball@google.com (Matt Ball)' - -from build_tools import build_utils -from build_tools import make_nacl_tools -from build_tools import make_sdk_tools -import os -import sys - -Import('env') - -# Add the system path to this environment so that we can run gclient and such -env.AppendENVPath('PATH', os.environ['PATH']) -# Duplicate all the shell environment variables, so that various Visual Studio -# tools will have the variables they expect (e.g. VS 2008 needs VS90COMNTOOLS). -# Do this using "if not in" instead of update(), so that os.environ variables -# don't override variables in env['ENV']. -for shell_var in os.environ: - if shell_var not in env['ENV']: - env['ENV'][shell_var] = os.environ[shell_var] - - -def run_generate_installer(env, target, source): - '''Runs the generate_installer script to create the SDK installer''' - args = [] - if env['IS_WINDOWS']: - from build_tools import generate_windows_installer - return generate_windows_installer.main(args) - else: - from build_tools import generate_installers - return generate_installers.main(args) - -installer_node = env.Command( - target='generate_installers_dummy_target.txt', - source='generate_installers.py', - action=run_generate_installer) - -env.Depends(installer_node, env.GetToolchainNode()) -env.Depends(installer_node, env.GetInstallerPrereqsNode()) -env.AddNodeAliases(installer_node, ['bot'], 'installer') - -install_file = 'nacl-sdk.exe' if sys.platform == 'win32' else 'nacl-sdk.tgz' -installer = os.path.join(os.path.dirname(env['ROOT_DIR']), install_file) - -def BuildSdkTools(env, target, source): - make_sdk_tools.MakeSdkTools(str(target[0].abspath), str(target[1].abspath)) - -sdk_tools_node = env.Command( - target=['nacl_sdk.zip', 'sdk_tools.tgz'], - source=[os.path.join('sdk_tools', 'sdk_update.py'), - 'make_sdk_tools.py', - os.path.join(env['ROOT_DIR'], 'LICENSE')], - action=BuildSdkTools) - -env.AddNodeAliases(sdk_tools_node, ['bot'], 'sdk_tools') - -installer_test_node = env.CreatePythonUnitTest( - 'tests/installer_test.py', - [installer_node if not env['USE_EXISTING_INSTALLER'] else installer], - buffered=False, - params=['--jobs=%s' % env['JOB_COUNT'], - '--outdir=%s' % os.path.join('scons-out', 'sdk_installer'), - '--nacl-sdk', env.File('nacl_sdk.zip'), - '--sdk-tools', env.File('sdk_tools.tgz'), - installer], - banner='test installer',) - -env.AddNodeToTestSuite(installer_test_node, ['bot'], - 'run_installer_test', 'large') - -env.Depends(env.GetInstallerTestNode(), installer_test_node) - -#------------------------------------------------------------------------------ -# Add build_tools unit tests - -def AddPythonUnitTest(command, file, size='small', **kwargs): - ''' Adds a new python unit test - - Args: - command: The scons command to run this unit test - file: The python file containing the unit test - size: How big is this test? small, medium, or large - kwargs: See named parameters to CreatePythonUnitTest - - returns: - test node for this newly created test''' - test_node = env.CreatePythonUnitTest(file, **kwargs) - env.AddNodeToTestSuite(test_node, ['bot'], command, size) - return test_node - -AddPythonUnitTest('run_build_utils_test', 'tests/build_utils_test.py') -AddPythonUnitTest('run_tar_archive_test', 'tests/tar_archive_test.py') -AddPythonUnitTest('run_update_manifest_test', - 'tests/update_manifest_test.py', size='medium') -AddPythonUnitTest('run_sdk_update_test', 'tests/sdk_update_test.py') -AddPythonUnitTest('run_set_nacl_env_test', 'tests/set_nacl_env_test.py', - dependencies=[env.GetToolchainNode()]) -AddPythonUnitTest('run_installer_contents_test', - 'tests/installer_contents_test.py') -AddPythonUnitTest('run_nacl_utils_test', 'nacl_sdk_scons/nacl_utils_test.py') -AddPythonUnitTest('run_path_set_test', 'tests/path_set_test.py') -AddPythonUnitTest('run_apply_patch_test', 'tests/apply_patch_test.py') -AddPythonUnitTest('run_nmf_test', - 'nacl_sdk_scons/nmf_test.py', - size='medium', - dependencies=[env.GetToolchainNode()], - params=['--toolchain-dir=%s' % - env['NACL_TOOLCHAIN_ROOTS'][('x86', 'glibc')]]) -AddPythonUnitTest('run_html_check_test', - 'html_checker.py', - params=[os.path.join(env['ROOT_DIR'], 'examples', name) - for name in ['index.html', 'index_staging.html']]) - -if env['IS_WINDOWS']: - AddPythonUnitTest('run_install_nsis_test', 'tests/install_nsis_test.py') - AddPythonUnitTest('run_nsis_script_test', 'tests/nsis_script_test.py') - - -#------------------------------------------------------------------------------ -# Put together the toolchain - -import gyp_extract -import re - -def GypSources(gyp_data, pattern): - """Extract a sources from a target matching a given pattern. - - Args: - gyp_data: list containing sources from gyp file. - pattern: re pattern that sources must match. - Returns: - A list of strings containing source filenames. - """ - # Extract source files that match. - re_compiled = re.compile(pattern) - return [source_file for source_file in gyp_data - if re_compiled.match(source_file)] - -ppapi_base = os.path.join(env['SRC_DIR'], 'ppapi') - -# Unfortunately gyp_extract does not handle variables or includes so we must -# pull the list of sources from ppapi_sources.gypi directly. -ppapi_sources_gypi = open(os.path.join(ppapi_base, - 'ppapi_sources.gypi'), 'r').read() -ppapi_sources_map = eval(ppapi_sources_gypi)['variables'] - -# Load ppapi_cpp.gypi -ppapi_cpp_gypi = gyp_extract.LoadGypFile(os.path.join(ppapi_base, - 'ppapi_cpp.gypi')) - -# Load ppapi_gl.gypi -ppapi_gl_gypi = gyp_extract.LoadGypFile(os.path.join(ppapi_base, - 'ppapi_gl.gypi')) - -# From ppapi_cpp.gypi:ppapi_c:c/[^/]*\.h -c_headers = GypSources(ppapi_sources_map['c_source_files'], 'c/[^/]*\.h') - -# From ppapi_cpp.gypi:ppapi_c:c/dev/[^/]*\.h -c_dev_headers = GypSources(ppapi_sources_map['c_source_files'], - 'c/dev/[^/]*\.h') - -# From ppapi_cpp.gypi:ppapi_cpp_objects:cpp/[^/]*\.h -# From ppapi_cpp.gypi:ppapi_cpp:cpp/[^/]*\.h -cpp_headers = ( - GypSources(ppapi_sources_map['cpp_source_files'], 'cpp/[^/]*\.h') + - gyp_extract.GypTargetSources( - ppapi_cpp_gypi, 'ppapi_cpp', 'cpp/[^/]*\.h') -) - -# From ppapi_cpp.gypi:ppapi_cpp_objects:cpp/dev/[^/]*\.h -cpp_dev_headers = GypSources(ppapi_sources_map['cpp_source_files'], - 'cpp/dev/[^/]*\.h') - -# From ppapi_gl.gypi:ppapi_gles2:.*\.h -gles2_headers = gyp_extract.GypTargetSources( - ppapi_gl_gypi, 'ppapi_gles2', '.*\.h') - - -c_header_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, h) for h in c_headers], os.path.join('ppapi', 'c')) -c_dev_header_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, h) for h in c_dev_headers], - os.path.join('ppapi', 'c', 'dev')) -cpp_header_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, h) for h in cpp_headers], - os.path.join('ppapi', 'cpp')) -cpp_dev_header_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, h) for h in cpp_dev_headers], - os.path.join('ppapi', 'cpp', 'dev')) - -# TODO(dspringer): Remove these lines when trusted ppapi builds are no longer -# needed for debugging. -# -------- 8< Cut here -------- -# From ppapi_cpp.gypi:ppapi_cpp_objects:cpp/[^/]*\.cc -# From ppapi_cpp.gypi:ppapi_cpp:cpp/[^/]*\.cc -cpp_trusted_sources = ( - GypSources(ppapi_sources_map['cpp_source_files'], 'cpp/[^/]*\.cc') + - gyp_extract.GypTargetSources( - ppapi_cpp_gypi, 'ppapi_cpp', 'cpp/[^/]*\.cc') -) - -cpp_trusted_source_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, cpp) for cpp in cpp_trusted_sources], - subdir=os.path.join('ppapi', 'cpp'), - base_dirs=[os.path.join(env['ROOT_DIR'], 'third_party')]) -# -------- 8< Cut here -------- - -#env.AddLibraryToSdk(['ppapi_cpp']) -env.Requires('ppapi_cpp', [c_header_install, - c_dev_header_install, - cpp_header_install, - cpp_dev_header_install, - # TODO(dspringer): Remove this when trusted ppapi - # builds are no longer needed. - cpp_trusted_source_install]) - -# GLES2 headers go into the GLES2 subdir, Khronos headers into the KHR subdir, -# EGL header go in the EGL subdir. -gl_base = os.path.join(ppapi_base, 'lib', 'gl', 'include') -egl_base = os.path.join(gl_base, 'EGL') -egl_header_install = env.AddHeaderToSdk([ - os.path.join(egl_base, 'egl.h'), - os.path.join(egl_base, 'eglext.h'), - os.path.join(egl_base, 'eglplatform.h'), - ], 'EGL') - -gles2_base = os.path.join(gl_base, 'GLES2') -gles2_header_install = env.AddHeaderToSdk([ - os.path.join(gles2_base, 'gl2.h'), - os.path.join(gles2_base, 'gl2ext.h'), - os.path.join(gles2_base, 'gl2platform.h'), - ], 'GLES2') -khr_header_install = env.AddHeaderToSdk([ - os.path.join(gl_base, 'KHR', 'khrplatform.h'), - ], 'KHR') -ppapi_gles2_header_install = env.AddHeaderToSdk( - [os.path.join(ppapi_base, h) for h in gles2_headers], - os.path.join('ppapi', 'gles2')) -#env.AddLibraryToSdk(['ppapi_gles2']) -env.Requires('ppapi_gles2', [ - egl_header_install, - gles2_header_install, - khr_header_install, - ppapi_gles2_header_install, -]) - - -#------------------------------------------------------------------------------ -# Build Native Client components that are not included in the toolchain zip - -def build_nacl_tools(env, target, source): - ''' Tool for running make_nacl_tools - This builds sel_ldr, ncval, and the nacl libraries''' - build_utils.BotAnnotator().BuildStep('build NaCl tools') - for key, toolchain in env['NACL_TOOLCHAIN_ROOTS'].items(): - (_, variant) = key - make_nacl_tools_args = [ - '--toolchain', - toolchain, - '--jobs', - env['JOB_COUNT'], - '--nacl_dir', - env['SRC_DIR'], - ] - if env.GetOption('clean'): - make_nacl_tools_args.extend(['--clean']) - args = make_nacl_tools_args + ['--lib=%s' % variant] - print 'Running make_nacl_tools with ', args - sys.stdout.flush() - make_nacl_tools.main(args) - -exe = '.exe' if sys.platform in ['cygwin', 'win32'] else '' - -tools = [ - os.path.join('bin', 'sel_ldr_x86_32%s' % exe), - os.path.join('bin', 'sel_ldr_x86_64%s' % exe), - os.path.join('bin', 'ncval_x86_32%s' % exe), - os.path.join('bin', 'ncval_x86_64%s' % exe), - os.path.join('runtime', 'irt_core_x86_32.nexe'), - os.path.join('runtime', 'irt_core_x86_64.nexe'), - ] - -all_tools = [] -for dir in env['NACL_TOOLCHAIN_ROOTS'].values(): - all_tools += [os.path.join(dir, tool) for tool in tools] - -nacl_tools_cmd = env.Command(all_tools, - ['make_nacl_tools.py', - os.path.join(env['SRC_DIR'], 'DEPS')], - build_nacl_tools) -env.Depends(nacl_tools_cmd, env.GetHeadersNode()) -env.Depends(env.GetToolchainNode(), nacl_tools_cmd) -env.AddCleanAction([], build_nacl_tools, ['toolchain', 'bot'], nacl_tools_cmd) diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/build.scons b/native_client_sdk/src/build_tools/debug_server/debug_stub/build.scons deleted file mode 100644 index a294cb5..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/build.scons +++ /dev/null @@ -1,37 +0,0 @@ -# -*- python -*- -# Copyright 2010 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can -# be found in the LICENSE file. - -# This file needs to be in sync with $SOURCE_ROOT/ppapi/ppapi.gyp -# at the revision specified in $SOURCE_ROOT/native_client/DEPS. - -Import('env') - -debug_sources = [ - 'debug_stub.cc', - 'event_common.cc', - 'platform_common.cc', - 'transport_common.cc', - ] - -# TODO(noelallen) -# Still need to add Linux and Mac implementation. Move "common" to -# above section once their dependancies are satisfied. -if env.Bit('windows'): - debug_sources += [ - 'win/debug_stub_win.cc', - 'win/mutex_impl.cc', - 'win/platform_impl.cc', - 'win/thread_impl.cc', - ] -else: - debug_sources += [ - 'posix/debug_stub_posix.cc', - 'posix/mutex_impl.cc', - 'posix/platform_impl.cc', - 'posix/thread_impl.cc', - ] - - -env.DualLibrary('debug_stub', debug_sources) diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.cc deleted file mode 100644 index 827224a..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.cc +++ /dev/null @@ -1,15 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "native_client/src/debug_server/debug_stub/debug_stub.h" - -void NaClDebugStubInit() { - NaClDebugStubPlatformInit(); -} - -void NaClDebugStubFini() { - NaClDebugStubPlatformFini(); -} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.gyp b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.gyp deleted file mode 100644 index 89183cc..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.gyp +++ /dev/null @@ -1,170 +0,0 @@ -# -# Copyright 2011 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can -# be found in the LICENSE file. -# -{ - 'includes': [ - '../../../build/common.gypi', - ], - 'variables': { - 'common_sources': [ - 'debug_stub.h', - 'debug_stub.cc', - 'event_common.cc', - 'platform_common.cc', - 'transport_common.cc', - ], - 'conditions': [ - ['OS=="linux" or OS=="mac"', { - 'platform_sources': [ - 'posix/debug_stub_posix.cc', - 'posix/mutex_impl.cc', - 'posix/platform_impl.cc', - 'posix/thread_impl.cc', - ], - }], - ['OS=="win"', { - 'platform_sources': [ - 'win/debug_stub_win.cc', - 'win/mutex_impl.cc', - 'win/platform_impl.cc', - 'win/thread_impl.cc', - ], - }], - ], - }, - - 'target_defaults': { - 'variables': { - 'target_base': 'none', - }, - 'target_conditions': [ - ['OS=="linux" or OS=="mac"', { - 'cflags': [ - '-Wno-long-long', - ], - }], - ['target_base=="debug_stub"', { - 'sources': [ - '<@(common_sources)', - '<@(platform_sources)', - ], - }], - ['target_base=="debug_stub_test"', { - 'sources': [ - 'debug_stub_test.cc', - ], - }], - ], - }, - 'targets': [ - # ---------------------------------------------------------------------- - { - 'target_name': 'debug_stub', - 'type': 'static_library', - 'variables': { - 'target_base': 'debug_stub', - }, - 'dependencies': [ - '<(DEPTH)/native_client/src/trusted/gdb_rsp/gdb_rsp.gyp:gdb_rsp', - ], - }, - # --------------------------------------------------------------------- - { - 'target_name': 'debug_stub_test', - 'type': 'executable', - 'variables': { - 'target_base': 'debug_stub_test', - }, - 'dependencies': [ - 'debug_stub', - ], - }, - ], - 'conditions': [ - ['OS=="win"', { - 'targets': [ - # --------------------------------------------------------------------- - { - 'target_name': 'debug_stub64', - 'type': 'static_library', - 'variables': { - 'target_base': 'debug_stub', - 'win_target': 'x64', - }, - 'dependencies': [ - '<(DEPTH)/native_client/src/trusted/gdb_rsp/gdb_rsp.gyp:gdb_rsp64', - ], - }, - # --------------------------------------------------------------------- - { - 'target_name': 'debug_stub_test64', - 'type': 'executable', - 'variables': { - 'target_base': 'debug_stub_test', - 'win_target': 'x64', - }, - 'dependencies': [ - 'debug_stub64', - ], - }, - # --------------------------------------------------------------------- - { - 'target_name': 'run_debug_stub_test', - 'message': 'running test run_imc_tests', - 'type': 'none', - 'dependencies': [ - 'debug_stub_test', - 'debug_stub_test64', - ], - 'actions': [ - { - 'action_name': 'run_debug_stub_test', - 'msvs_cygwin_shell': 0, - 'inputs': [ - '<(DEPTH)/native_client/tests/debug_stub/test_debug_stub.py', - '<(PRODUCT_DIR)/debug_stub_test', - ], - 'outputs': [ - '<(PRODUCT_DIR)/test-output/debug_stub_test.out', - ], - 'action': [ - '<@(python_exe)', - '<(DEPTH)/native_client/tests/debug_stub/test_debug_stub.py', - '<(PRODUCT_DIR)/debug_stub_test', - '>', - '<@(_outputs)', - ], - }, - ], - 'conditions': [ - ['MSVS_OS_BITS==64', { - 'actions': [ - { - 'action_name': 'run_debug_stub_test64', - 'msvs_cygwin_shell': 0, - 'inputs': [ - '<(DEPTH)/native_client/tests/debug_stub/test_debug_stub.py', - '<(PRODUCT_DIR)/debug_stub_test', - ], - 'outputs': [ - '<(PRODUCT_DIR)/test-output/debug_stub_test.out', - ], - 'action': [ - '<@(python_exe)', - '<(DEPTH)/native_client/tests/debug_stub/test_debug_stub.py', - '<(PRODUCT_DIR)/debug_stub_test64', - '>', - '<@(_outputs)', - ], - }, - ], - }], - ], - }, - ], - }], - ], -} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.h b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.h deleted file mode 100644 index d459523..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef NATIVE_CLIENT_DEBUG_STUB_DEBUG_STUB_H_ -#define NATIVE_CLIENT_DEBUG_STUB_DEBUG_STUB_H_ - -#include "native_client/src/include/nacl_base.h" - -EXTERN_C_BEGIN - -void NaClDebugStubInit(); -void NaClDebugStubFini(); - -/* - * Platform-specific init/fini functions - */ -void NaClDebugStubPlatformInit(); -void NaClDebugStubPlatformFini(); - -EXTERN_C_END - -#endif /* NATIVE_CLIENT_DEBUG_STUB_DEBUG_STUB_H_ */ diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.rules b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.rules deleted file mode 100644 index 3ca1cae..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="debug_stub" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.sln b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.sln deleted file mode 100644 index b399c1b..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub.sln +++ /dev/null @@ -1,110 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "(debug_stub)", "debug_stub", "{C44F267D-CA3D-2707-9AF9-6331B7BDD7F3}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "(gdb_rsp)", "gdb_rsp", "{36DDA403-5397-3B36-4C08-47C4ED351C15}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "debug_stub", "debug_stub.vcproj", "{D9221BEA-DBFE-4677-4909-B88BA2E5A104}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "debug_stub64", "debug_stub64.vcproj", "{C3E9609B-A809-EF38-CA53-2962E844062E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "debug_stub_test", "debug_stub_test.vcproj", "{216DF189-70D2-3010-9D62-6AD9D13C62FD}" - ProjectSection(ProjectDependencies) = postProject - {D9221BEA-DBFE-4677-4909-B88BA2E5A104} = {D9221BEA-DBFE-4677-4909-B88BA2E5A104} - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6} = {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "debug_stub_test64", "debug_stub_test64.vcproj", "{59F612B2-1E67-81E5-6F41-F56978638136}" - ProjectSection(ProjectDependencies) = postProject - {C3E9609B-A809-EF38-CA53-2962E844062E} = {C3E9609B-A809-EF38-CA53-2962E844062E} - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC} = {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gdb_rsp", "..\gdb_rsp\gdb_rsp.vcproj", "{0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gdb_rsp64", "..\gdb_rsp\gdb_rsp64.vcproj", "{78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "run_debug_stub_test", "run_debug_stub_test.vcproj", "{B7A7E685-394E-D4CF-B572-8A968A5E46AC}" - ProjectSection(ProjectDependencies) = postProject - {216DF189-70D2-3010-9D62-6AD9D13C62FD} = {216DF189-70D2-3010-9D62-6AD9D13C62FD} - {59F612B2-1E67-81E5-6F41-F56978638136} = {59F612B2-1E67-81E5-6F41-F56978638136} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Release|x64 = Release|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Release|x64.ActiveCfg = Release|x64 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Release|x64.Build.0 = Release|x64 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Debug|Win32.ActiveCfg = Debug|Win32 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Debug|Win32.Build.0 = Debug|Win32 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Debug|x64.ActiveCfg = Debug|x64 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Debug|x64.Build.0 = Debug|x64 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Release|Win32.ActiveCfg = Release|Win32 - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6}.Release|Win32.Build.0 = Release|Win32 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Release|x64.ActiveCfg = Release|x64 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Release|x64.Build.0 = Release|x64 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Debug|Win32.ActiveCfg = Debug|Win32 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Debug|Win32.Build.0 = Debug|Win32 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Debug|x64.ActiveCfg = Debug|x64 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Debug|x64.Build.0 = Debug|x64 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Release|Win32.ActiveCfg = Release|Win32 - {216DF189-70D2-3010-9D62-6AD9D13C62FD}.Release|Win32.Build.0 = Release|Win32 - {59F612B2-1E67-81E5-6F41-F56978638136}.Release|x64.ActiveCfg = Release|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Release|x64.Build.0 = Release|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Debug|Win32.ActiveCfg = Debug|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Debug|Win32.Build.0 = Debug|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Debug|x64.ActiveCfg = Debug|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Debug|x64.Build.0 = Debug|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Release|Win32.ActiveCfg = Release|x64 - {59F612B2-1E67-81E5-6F41-F56978638136}.Release|Win32.Build.0 = Release|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Release|x64.ActiveCfg = Release|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Release|x64.Build.0 = Release|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Debug|Win32.ActiveCfg = Debug|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Debug|Win32.Build.0 = Debug|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Debug|x64.ActiveCfg = Debug|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Debug|x64.Build.0 = Debug|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Release|Win32.ActiveCfg = Release|x64 - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC}.Release|Win32.Build.0 = Release|x64 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Release|x64.ActiveCfg = Release|x64 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Release|x64.Build.0 = Release|x64 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Debug|Win32.ActiveCfg = Debug|Win32 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Debug|Win32.Build.0 = Debug|Win32 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Debug|x64.ActiveCfg = Debug|x64 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Debug|x64.Build.0 = Debug|x64 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Release|Win32.ActiveCfg = Release|Win32 - {B7A7E685-394E-D4CF-B572-8A968A5E46AC}.Release|Win32.Build.0 = Release|Win32 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Release|x64.ActiveCfg = Release|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Release|x64.Build.0 = Release|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Debug|Win32.ActiveCfg = Debug|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Debug|Win32.Build.0 = Debug|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Debug|x64.ActiveCfg = Debug|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Debug|x64.Build.0 = Debug|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Release|Win32.ActiveCfg = Release|x64 - {C3E9609B-A809-EF38-CA53-2962E844062E}.Release|Win32.Build.0 = Release|x64 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Release|x64.ActiveCfg = Release|x64 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Release|x64.Build.0 = Release|x64 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Debug|Win32.ActiveCfg = Debug|Win32 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Debug|Win32.Build.0 = Debug|Win32 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Debug|x64.ActiveCfg = Debug|x64 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Debug|x64.Build.0 = Debug|x64 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Release|Win32.ActiveCfg = Release|Win32 - {D9221BEA-DBFE-4677-4909-B88BA2E5A104}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {C3E9609B-A809-EF38-CA53-2962E844062E} = {C44F267D-CA3D-2707-9AF9-6331B7BDD7F3} - {59F612B2-1E67-81E5-6F41-F56978638136} = {C44F267D-CA3D-2707-9AF9-6331B7BDD7F3} - {D9221BEA-DBFE-4677-4909-B88BA2E5A104} = {C44F267D-CA3D-2707-9AF9-6331B7BDD7F3} - {216DF189-70D2-3010-9D62-6AD9D13C62FD} = {C44F267D-CA3D-2707-9AF9-6331B7BDD7F3} - {B7A7E685-394E-D4CF-B572-8A968A5E46AC} = {C44F267D-CA3D-2707-9AF9-6331B7BDD7F3} - {0F659521-D577-1DFD-46FC-6DBEE3E1DFD6} = {36DDA403-5397-3B36-4C08-47C4ED351C15} - {78AAD972-57EA-27B4-5F13-3CD2B7E8ABFC} = {36DDA403-5397-3B36-4C08-47C4ED351C15} - EndGlobalSection -EndGlobal diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub64.rules b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub64.rules deleted file mode 100644 index 09cae6f..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub64.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="debug_stub64" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.cc deleted file mode 100644 index e46ffd9..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.cc +++ /dev/null @@ -1,12 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ -#include "native_client/src/include/portability.h" - -int main(int argc, char* argv[]) { - UNREFERENCED_PARAMETER(argc); - UNREFERENCED_PARAMETER(argv); - // TODO(noelallen): implement me - return 0; -} diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.rules b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.rules deleted file mode 100644 index ba96b7c..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="debug_stub_test" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test64.rules b/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test64.rules deleted file mode 100644 index 279f11a..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/debug_stub_test64.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="debug_stub_test64" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/event_common.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/event_common.cc deleted file mode 100644 index f2d29c3..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/event_common.cc +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "native_client/src/shared/platform/nacl_sync.h" - -/* - * Define the common gdb_utils IEvent interface to use the NaCl version. - * IEvent only suports single trigger Signal API. - */ - -#if NACL_WINDOWS -# include "native_client/src/shared/platform/win/lock.h" -# include "native_client/src/shared/platform/win/condition_variable.h" -#elif NACL_LINUX || NACL_OSX -# include "native_client/src/shared/platform/linux/lock.h" -# include "native_client/src/shared/platform/linux/condition_variable.h" -#endif - -#include "native_client/src/debug_server/port/event.h" - -namespace port { - -class Event : public IEvent { - public: - Event() : signaled_(false) { } - ~Event() {} - - void Wait() { - /* Start the wait owning the lock */ - lock_.Acquire(); - - /* We can skip this if already signaled */ - while (!signaled_) { - /* Otherwise, try and wait, which release the lock */ - cond_.Wait(lock_); - - /* We exit the wait owning the lock again. */ - }; - - /* Clear the signal then unlock. */ - signaled_ = false; - lock_.Release(); - } - - void Signal() { - signaled_ = true; - cond_.Signal(); - } - - public: - volatile bool signaled_; - NaCl::Lock lock_; - NaCl::ConditionVariable cond_; -}; - -IEvent* IEvent::Allocate() { - return new Event; -} - -void IEvent::Free(IEvent *ievent) { - delete static_cast<Event*>(ievent); -} - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/linux/debug_stub_linux.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/linux/debug_stub_linux.cc deleted file mode 100644 index 2ffcb5d..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/linux/debug_stub_linux.cc +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ -#include "native_client/src/trusted/debug_stub/debug_stub.h" - -void NaClDebugStubPlatformInit() { - // TODO(noelallen): implement me -} - -void NaClDebugStubPlatformFini() { - // TODO(noelallen): implement me -} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/osx/debug_stub_osx.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/osx/debug_stub_osx.cc deleted file mode 100644 index 2ffcb5d..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/osx/debug_stub_osx.cc +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ -#include "native_client/src/trusted/debug_stub/debug_stub.h" - -void NaClDebugStubPlatformInit() { - // TODO(noelallen): implement me -} - -void NaClDebugStubPlatformFini() { - // TODO(noelallen): implement me -} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/platform_common.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/platform_common.cc deleted file mode 100644 index e7cca2d..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/platform_common.cc +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> - -#include <map> - -#include "native_client/src/shared/platform/nacl_log.h" -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/port/platform.h" - -namespace port { - -// Log a message -void IPlatform::LogInfo(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - NaClLogV(LOG_INFO, fmt, argptr); -} - -void IPlatform::LogWarning(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - NaClLogV(LOG_WARNING, fmt, argptr); -} - -void IPlatform::LogError(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - NaClLogV(LOG_ERROR, fmt, argptr); -} - -} // End of port namespace diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/debug_stub_posix.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/debug_stub_posix.cc deleted file mode 100644 index 64ad819..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/debug_stub_posix.cc +++ /dev/null @@ -1,11 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "native_client/src/trusted/debug_stub/debug_stub.h" - -// No platform specific initialization need for POSIX -void NaClDebugStubPlatformInit() {} -void NaClDebugStubPlatformFini() {} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/mutex_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/mutex_impl.cc deleted file mode 100644 index 00377e0..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/mutex_impl.cc +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <pthread.h> - -#include "native_client/src/debug_server/port/mutex.h" - -/* - * Unfortunately NaClSync does not have the correct recursive - * property so we need to use our own version. - */ - -namespace port { - -class Mutex : public IMutex { - public: - Mutex() { - pthread_mutexattr_t attr; - - // Create a recursive mutex, so we can reenter on the same thread - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&mutex_, &attr); - pthread_mutexattr_destroy(&attr); - } - - ~Mutex() { - pthread_mutex_destroy(&mutex_); - } - - virtual void Lock() { - pthread_mutex_lock(&mutex_); - } - - virtual bool Try() { - return pthread_mutex_trylock(&mutex_) == 0; - } - - virtual void Unlock() { - pthread_mutex_unlock(&mutex_); - } - - public: - pthread_mutex_t mutex_; -}; - -IMutex* IMutex::Allocate() { - return new Mutex; -} - -void IMutex::Free(IMutex *mutex) { - delete static_cast<Mutex*>(mutex); -} - -} // namespace port diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/platform_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/platform_impl.cc deleted file mode 100644 index 27c77cf..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/platform_impl.cc +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> -#include <sys/mman.h> -#include <sys/types.h> -#include <sys/syscall.h> -#include <pthread.h> - -#include <map> -#include <vector> - -#include "native_client/src/shared/platform/nacl_log.h" -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" -#include "native_client/src/debug_server/port/event.h" -#include "native_client/src/debug_server/port/platform.h" - -#include "native_client/src/trusted/service_runtime/nacl_config.h" -#include "native_client/src/trusted/service_runtime/sel_ldr.h" -#include "native_client/src/trusted/service_runtime/sel_rt.h" - - -/* - * Define the OS specific portions of gdb_utils IPlatform interface. - */ - - -// TODO(noelallen) : Add POSIX implementation. These functions -// represent a minimal implementation to allow the debugging -// code to link and run. -static port::IEvent* GetLaunchEvent() { - static port::IEvent* event_ = port::IEvent::Allocate(); - return event_; -} - -namespace port { - -struct StartInfo_t { - port::IPlatform::ThreadFunc_t func_; - void *cookie_; - volatile uint32_t id_; -}; - -// Get the OS id of this thread -uint32_t IPlatform::GetCurrentThread() { - return static_cast<uint32_t>(syscall(SYS_gettid)); -} - -// Use start stub, to record thread id, and signal launcher -static void *StartFunc(void* cookie) { - StartInfo_t* info = reinterpret_cast<StartInfo_t*>(cookie); - info->id_ = (uint32_t) syscall(SYS_gettid); - - printf("Started thread...\n"); - GetLaunchEvent()->Signal(); - info->func_(info->cookie_); - - return NULL; -} - -uint32_t IPlatform::CreateThread(ThreadFunc_t func, void* cookie) { - pthread_t thread; - StartInfo_t info; - - // Setup the thread information - info.func_ = func; - info.cookie_ = cookie; - - printf("Creating thread...\n"); - - // Redirect to stub and wait for signal before continuing - if (pthread_create(&thread, NULL, StartFunc, &info) == 0) { - GetLaunchEvent()->Wait(); - printf("Found thread...\n"); - return info.id_; - } - - return 0; -} - -void IPlatform::Relinquish(uint32_t msec) { - usleep(msec * 1000); -} - -bool IPlatform::GetMemory(uint64_t virt, uint32_t len, void *dst) { - UNREFERENCED_PARAMETER(virt); - UNREFERENCED_PARAMETER(len); - UNREFERENCED_PARAMETER(dst); - return false; -} - -bool IPlatform::SetMemory(uint64_t virt, uint32_t len, void *src) { - UNREFERENCED_PARAMETER(virt); - UNREFERENCED_PARAMETER(len); - UNREFERENCED_PARAMETER(src); - return false; -} - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/thread_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/thread_impl.cc deleted file mode 100644 index 8fb620b..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/posix/thread_impl.cc +++ /dev/null @@ -1,122 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdexcept> - -#include "native_client/src/shared/platform/nacl_log.h" -#include "native_client/src/debug_server/port/mutex.h" -#include "native_client/src/debug_server/port/thread.h" - -/* - * Define the OS specific portions of gdb_utils IThread interface. - */ - -namespace port { - -static IMutex* ThreadGetLock() { - static IMutex* mutex_ = IMutex::Allocate(); - return mutex_; -} - -static IThread::ThreadMap_t *ThreadGetMap() { - static IThread::ThreadMap_t* map_ = new IThread::ThreadMap_t; - return map_; -} - -// TODO(noelallen) : Add POSIX implementation. These functions -// represent a minimal implementation to allow the debugging -// code to link and run. -class Thread : public IThread { - public: - explicit Thread(uint32_t id) : ref_(1), id_(id), state_(DEAD) {} - ~Thread() {} - - uint32_t GetId() { - return id_; - } - - State GetState() { - return state_; - } - - virtual bool Suspend() { - return false; - } - - virtual bool Resume() { - return false; - } - - virtual bool SetStep(bool on) { - UNREFERENCED_PARAMETER(on); - return false; - } - - virtual bool GetRegister(uint32_t index, void *dst, uint32_t len) { - UNREFERENCED_PARAMETER(index); - UNREFERENCED_PARAMETER(dst); - UNREFERENCED_PARAMETER(len); - return false; - } - - virtual bool SetRegister(uint32_t index, void* src, uint32_t len) { - UNREFERENCED_PARAMETER(index); - UNREFERENCED_PARAMETER(src); - UNREFERENCED_PARAMETER(len); - return false; - } - - virtual void* GetContext() { return NULL; } - - private: - uint32_t ref_; - uint32_t id_; - State state_; - - friend class IThread; -}; - -IThread* IThread::Acquire(uint32_t id, bool create) { - MutexLock lock(ThreadGetLock()); - Thread* thread; - ThreadMap_t &map = *ThreadGetMap(); - - // Check if we have that thread - if (map.count(id)) { - thread = static_cast<Thread*>(map[id]); - thread->ref_++; - return thread; - } - - // If not, can we create it? - if (create) { - // If not add it to the map - thread = new Thread(id); - map[id] = thread; - return thread; - } - - return NULL; -} - -void IThread::Release(IThread *ithread) { - MutexLock lock(ThreadGetLock()); - Thread* thread = static_cast<Thread*>(ithread); - thread->ref_--; - - if (thread->ref_ == 0) { - ThreadGetMap()->erase(thread->id_); - delete static_cast<IThread*>(thread); - } -} - -void IThread::SetExceptionCatch(IThread::CatchFunc_t func, void *cookie) { - UNREFERENCED_PARAMETER(func); - UNREFERENCED_PARAMETER(cookie); -} - - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/run_debug_stub_test.rules b/native_client_sdk/src/build_tools/debug_server/debug_stub/run_debug_stub_test.rules deleted file mode 100644 index 2e368f4..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/run_debug_stub_test.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="run_debug_stub_test" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/transport_common.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/transport_common.cc deleted file mode 100644 index 7043d5c..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/transport_common.cc +++ /dev/null @@ -1,293 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifdef _WIN32 -#include <windows.h> -#ifndef AF_IPX -#include <winsock2.h> -#endif -#define SOCKET_HANDLE SOCKET -#else - -#include <arpa/inet.h> -#include <netdb.h> -#include <sys/select.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <unistd.h> - -#define SOCKET_HANDLE int -#define closesocket close -#endif - -#include <stdlib.h> -#include <string> - -#include "native_client/src/debug_server/gdb_rsp/util.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/transport.h" - -using gdb_rsp::stringvec; -using gdb_rsp::StringSplit; - -namespace port { - -typedef int socklen_t; - -class Transport : public ITransport { - public: - Transport() { - handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - } - - explicit Transport(SOCKET_HANDLE s) { - handle_ = s; - } - - ~Transport() { - if (handle_ != -1) closesocket(handle_); - } - - // Read from this transport, return a negative value if there is an error - // otherwise return the number of bytes actually read. - virtual int32_t Read(void *ptr, int32_t len) { - return ::recv(handle_, reinterpret_cast<char *>(ptr), len, 0); - } - - // Write to this transport, return a negative value if there is an error - // otherwise return the number of bytes actually written. - virtual int32_t Write(const void *ptr, int32_t len) { - return ::send(handle_, reinterpret_cast<const char *>(ptr), len, 0); - } - - // Return true if data becomes availible or false after ms milliseconds. - virtual bool ReadWaitWithTimeout(uint32_t ms = 0) { - fd_set fds; - - FD_ZERO(&fds); - FD_SET(handle_, &fds); - - // We want a "non-blocking" check - struct timeval timeout; - timeout.tv_sec = 0; - timeout.tv_usec= ms * 1000; - - // Check if this file handle can select on read - int cnt = select(0, &fds, 0, 0, &timeout); - - // If we are ready, or if there is an error. We return true - // on error, to "timeout" and let the next IO request fail. - if (cnt != 0) return true; - - return false; - } - -// On windows, the header that defines this has other definition -// colitions, so we define it outselves just in case -#ifndef SD_BOTH -#define SD_BOTH 2 -#endif - - virtual void Disconnect() { - // Shutdown the conneciton in both diections. This should - // always succeed, and nothing we can do if this fails. - (void) ::shutdown(handle_, SD_BOTH); - } - - protected: - SOCKET_HANDLE handle_; -}; - -// Convert string in the form of [addr][:port] where addr is a -// IPv4 address or host name, and port is a 16b tcp/udp port. -// Both portions are optional, and only the portion of the address -// provided is updated. Values are provided in network order. -static bool StringToIPv4(const std::string &instr, uint32_t *addr, - uint16_t *port) { - // Make a copy so the are unchanged unless we succeed - uint32_t outaddr = *addr; - uint16_t outport = *port; - - // Substrings of the full ADDR:PORT - std::string addrstr; - std::string portstr; - - // We should either have one or two tokens in the form of: - // IP - IP, NUL - // IP: - IP, NUL - // :PORT - NUL, PORT - // IP:PORT - IP, PORT - - // Search for the port marker - size_t portoff = instr.find(':'); - - // If we found a ":" before the end, get both substrings - if ((portoff != std::string::npos) && (portoff + 1 < instr.size())) { - addrstr = instr.substr(0, portoff); - portstr = instr.substr(portoff + 1, std::string::npos); - } else { - // otherwise the entire string is the addr portion. - addrstr = instr; - portstr = ""; - } - - // If the address portion was provided, update it - if (addrstr.size()) { - // Special case 0.0.0.0 which means any IPv4 interface - if (addrstr == "0.0.0.0") { - outaddr = 0; - } else { - struct hostent *host = gethostbyname(addrstr.data()); - - // Check that we found an IPv4 host - if ((NULL == host) || (AF_INET != host->h_addrtype)) return false; - - // Make sure the IP list isn't empty. - if (0 == host->h_addr_list[0]) return false; - - // Use the first one. - uint32_t *addrarray = reinterpret_cast<uint32_t*>(host->h_addr_list); - outaddr = addrarray[0]; - } - } - - // if the port portion was provided, then update it - if (portstr.size()) { - int val = atoi(portstr.data()); - if ((val < 0) || (val > 65535)) return false; - outport = ntohs(static_cast<uint16_t>(val)); - } - - // We haven't failed, so set the values - *addr = outaddr; - *port = outport; - return true; -} - - -static SOCKET_HANDLE s_ServerSock; - -void Init() -{ - WSADATA wsaData; - WORD wVersionRequested = MAKEWORD( 1, 1 ); - int res = ::WSAStartup( wVersionRequested, &wsaData ); - printf("::WSAStartup -> %d\n", res); -} - - -static bool SocketInit() { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - Init(); - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - long sc = (long)::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - s_ServerSock = sc; - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - if (s_ServerSock == -1) { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - IPlatform::LogError("Failed to create socket.\n"); - return false; - } - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - - return true; -} - -static bool SocketsAvailable() { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - static bool _init = SocketInit(); - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - return _init; -} - -static bool BuildSockAddr(const char *addr, struct sockaddr_in *sockaddr) { - std::string addrstr = addr; - uint32_t *pip = reinterpret_cast<uint32_t*>(&sockaddr->sin_addr.s_addr); - uint16_t *pport = reinterpret_cast<uint16_t*>(&sockaddr->sin_port); - - sockaddr->sin_family = AF_INET; - return StringToIPv4(addrstr, pip, pport); -} - -ITransport* ITransport::Connect(const char *addr) { - if (!SocketsAvailable()) return NULL; - - SOCKET_HANDLE s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (s == -1) { - IPlatform::LogError("Failed to create connection socket.\n"); - return NULL; - } - - struct sockaddr_in saddr; - saddr.sin_family = AF_INET; - saddr.sin_addr.s_addr = htonl(0x7F000001); - saddr.sin_port = htons(4014); - - // Override portions address that are provided - if (addr) BuildSockAddr(addr, &saddr); - - if (::connect(s, reinterpret_cast<sockaddr*>(&saddr), sizeof(saddr)) != 0) { - IPlatform::LogError("Failed to connect.\n"); - return NULL; - } - - return new Transport(s); -} - -ITransport* ITransport::Accept(const char *addr) { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - static bool listening = false; - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - if (!SocketsAvailable()) return NULL; - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - - if (!listening) { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - struct sockaddr_in saddr; - socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr)); - saddr.sin_family = AF_INET; - saddr.sin_addr.s_addr = htonl(0x7F000001); - saddr.sin_port = htons(4014); - - // Override portions address that are provided - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - if (addr) BuildSockAddr(addr, &saddr); - - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - struct sockaddr *psaddr = reinterpret_cast<struct sockaddr *>(&saddr); - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - if (bind(s_ServerSock, psaddr, addrlen)) { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - IPlatform::LogError("Failed to bind server.\n"); - return NULL; - } - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - - if (listen(s_ServerSock, 1)) { - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - IPlatform::LogError("Failed to listen.\n"); - return NULL; - } - printf("---> %d %s\n", __LINE__, __FILE__); fflush(stdout); - - listening = true; - } - - if (listening) { - SOCKET_HANDLE s = ::accept(s_ServerSock, NULL, 0); - if (-1 != s) return new Transport(s); - return NULL; - } - - return NULL; -} - -void ITransport::Free(ITransport* itrans) { - Transport* trans = static_cast<Transport*>(itrans); - delete trans; -} - -} // namespace port diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/debug_stub_win.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/win/debug_stub_win.cc deleted file mode 100644 index a74b0f4..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/debug_stub_win.cc +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <windows.h> - -#ifndef AF_IPX -#include <winsock2.h> -#endif - -#include "native_client/src/debug_server/debug_stub/debug_stub.h" -#include "native_client/src/debug_server/port/platform.h" - - -using port::IPlatform; - -void NaClDebugStubPlatformInit() { - WORD wVersionRequested; - WSADATA wsaData; - int err; - - // Make sure to request the use of sockets. - // NOTE: It is safe to call Startup multiple times - wVersionRequested = MAKEWORD(2, 2); - err = WSAStartup(wVersionRequested, &wsaData); - if (err != 0) { - // We could not find a matching DLL - IPlatform::LogError("WSAStartup failed with error: %d\n", err); - exit(-1); - } - - if (HIBYTE(wsaData.wVersion) != 2) { - // We couldn't get a matching version - IPlatform::LogError("Could not find a usable version of Winsock.dll\n"); - WSACleanup(); - exit(-1); - } -} - -void NaClDebugStubPlatformFini() { - WSACleanup(); -} - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/mutex_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/win/mutex_impl.cc deleted file mode 100644 index b2d163a..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/mutex_impl.cc +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <windows.h> -#include <exception> - -#include "native_client/src/debug_server/port/mutex.h" - -/* - * Define the gdb_utils IMutex interface to use the NaCl version. - * Unfortunately NaClSync does not have the correct recursive - * property so we need to use our own version. - */ - -namespace port { - -class Mutex : public IMutex { - public: - Mutex() : handle_(NULL) { - handle_ = CreateMutex(NULL, FALSE, NULL); - - // If we fail to create the mutex, then abort the app. - if (NULL == handle_) throw std::exception("Failed to create mutex."); - } - - ~Mutex() { - // If constructor where to throw, then the mutex could be unset - if (NULL == handle_) return; - - // This should always succeed. - (void) CloseHandle(handle_); - } - - void Lock() { - DWORD ret; - do { - ret = WaitForSingleObject(handle_, INFINITE); - if (WAIT_OBJECT_0 == ret) return; - - // If this lock wasn't abandoned or locked - // the there must be an error. - if (WAIT_ABANDONED != ret) { - throw std::exception("Lock failed on mutex."); - } - } while (WAIT_ABANDONED == ret); - } - - bool Try() { - DWORD ret = WaitForSingleObject(handle_, 0); - switch (ret) { - case WAIT_OBJECT_0: - return true; - - // The lock was already taken, we will need to retry. - case WAIT_TIMEOUT: - return false; - - // The lock was abandoned and ownership transfered, it is still unlocked - // so we can just retry. - case WAIT_ABANDONED: - return false; - - // Unrecoverable error. - default: - throw std::exception("Try failed on mutex."); - } - } - - void Mutex::Unlock() { - (void) ReleaseMutex(handle_); - } - - private: - HANDLE handle_; -}; - -IMutex* IMutex::Allocate() { - return new Mutex; -} - -void IMutex::Free(IMutex *mutex) { - delete static_cast<Mutex*>(mutex); -} - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/platform_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/win/platform_impl.cc deleted file mode 100644 index b8a9fcf..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/platform_impl.cc +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <process.h> -#include <stdio.h> -#include <stdlib.h> -#include <windows.h> - -#include <exception> - -#include "native_client/src/shared/platform/nacl_log.h" -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/port/platform.h" - -/* - * Define the OS specific portions of gdb_utils IPlatform interface. - */ -int GetLastErrorString(char* buffer, size_t length) { - DWORD error = GetLastError(); - return FormatMessageA( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - buffer, - static_cast<DWORD>((64 * 1024 < length) ? 64 * 1024 : length), - NULL) ? 0 : -1; -} - - -static DWORD Reprotect(void *ptr, uint32_t len, DWORD newflags) { - DWORD oldflags; - if (!VirtualProtect(ptr, len, newflags, &oldflags)) { - char msg[256] = {0}; - GetLastErrorString(msg, sizeof(msg) - 1); - msg[sizeof(msg) - 1] = 0; - printf("Failed with %d [%s]\n", GetLastError(), msg); - return -1; - } - - FlushInstructionCache(GetCurrentProcess(), ptr, len); - return oldflags; -} - -namespace port { - -// Called to request the platform start/stop the thread -uint32_t IPlatform::GetCurrentThread() { - return static_cast<uint32_t>(GetCurrentThreadId()); -} - -/* - * Since the windows compiler does not use __stdcall by default, we need to - * modify this function pointer. - */ -typedef unsigned (__stdcall *WinThreadFunc_t)(void *cookie); - -uint32_t IPlatform::CreateThread(IPlatform::ThreadFunc_t func, void* cookie) { - uint32_t id; - /* - * We use our own code here instead of NaClThreadCtor because - * it does not report the thread ID only the handle. - * TODO(noelallen) - Merge port and platform - */ - uintptr_t res = _beginthreadex(NULL, 0, - reinterpret_cast<WinThreadFunc_t>(func), - cookie, 0, &id); - - return id; -} - -void IPlatform::Relinquish(uint32_t msec) { - Sleep(msec); -} - -bool IPlatform::GetMemory(uint64_t virt, uint32_t len, void *dst) { - uint32_t oldFlags = Reprotect(reinterpret_cast<void*>(virt), - len, PAGE_READONLY); - - if (oldFlags == -1) return false; - - memcpy(dst, reinterpret_cast<void*>(virt), len); - (void) Reprotect(reinterpret_cast<void*>(virt), len, oldFlags); - return true; -} - -bool IPlatform::SetMemory(uint64_t virt, uint32_t len, void *src) { - uint32_t oldFlags = Reprotect(reinterpret_cast<void*>(virt), - len, PAGE_EXECUTE_READWRITE); - - if (oldFlags == -1) return false; - - memcpy(reinterpret_cast<void*>(virt), src, len); - FlushInstructionCache(GetCurrentProcess(), - reinterpret_cast<void*>(virt), len); - (void) Reprotect(reinterpret_cast<void*>(virt), len, oldFlags); - return true; -} - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/thread_impl.cc b/native_client_sdk/src/build_tools/debug_server/debug_stub/win/thread_impl.cc deleted file mode 100644 index 661ed56..0000000 --- a/native_client_sdk/src/build_tools/debug_server/debug_stub/win/thread_impl.cc +++ /dev/null @@ -1,437 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <windows.h> -#include <exception> -#include <stdexcept> - -#include "native_client/src/debug_server/port/mutex.h" -#include "native_client/src/debug_server/port/thread.h" - -/* - * Define the OS specific portions of gdb_utils IThread interface. - */ - -#define AAA(x) case x: return #x - -//0x40010006 - - const char* ExceptionCodeStr(int code) { - switch(code) { - AAA(EXCEPTION_ACCESS_VIOLATION); - AAA(EXCEPTION_ARRAY_BOUNDS_EXCEEDED); - AAA(EXCEPTION_BREAKPOINT); - AAA(EXCEPTION_DATATYPE_MISALIGNMENT); - AAA(EXCEPTION_FLT_DENORMAL_OPERAND); - AAA(EXCEPTION_FLT_DIVIDE_BY_ZERO); - AAA(EXCEPTION_FLT_INEXACT_RESULT); - AAA(EXCEPTION_FLT_INVALID_OPERATION); - AAA(EXCEPTION_FLT_OVERFLOW); - AAA(EXCEPTION_FLT_STACK_CHECK); - AAA(EXCEPTION_FLT_UNDERFLOW); - AAA(EXCEPTION_ILLEGAL_INSTRUCTION); - AAA(EXCEPTION_IN_PAGE_ERROR); - AAA(EXCEPTION_INT_DIVIDE_BY_ZERO); - AAA(EXCEPTION_INT_OVERFLOW); - AAA(EXCEPTION_INVALID_DISPOSITION); - AAA(EXCEPTION_NONCONTINUABLE_EXCEPTION); - AAA(EXCEPTION_PRIV_INSTRUCTION); - AAA(EXCEPTION_SINGLE_STEP); - AAA(EXCEPTION_STACK_OVERFLOW); - } - return "N/A"; -} - -namespace port { - -static IThread::CatchFunc_t s_CatchFunc = NULL; -static void* s_CatchCookie = NULL; -static PVOID s_OldCatch = NULL; - -enum PosixSignals { - SIGINT = 2, - SIGQUIT = 3, - SIGILL = 4, - SIGTRACE= 5, - SIGBUS = 7, - SIGFPE = 8, - SIGKILL = 9, - SIGSEGV = 11, - SIGSTKFLT = 16, -}; - - -static IMutex* ThreadGetLock() { - static IMutex* mutex_ = IMutex::Allocate(); - return mutex_; -} - -static IThread::ThreadMap_t *ThreadGetMap() { - static IThread::ThreadMap_t* map_ = new IThread::ThreadMap_t; - return map_; -} - -static int8_t ExceptionToSignal(int ex) { - switch (ex) { - case EXCEPTION_GUARD_PAGE: - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - case EXCEPTION_DATATYPE_MISALIGNMENT: - case EXCEPTION_ACCESS_VIOLATION: - case EXCEPTION_IN_PAGE_ERROR: - return SIGSEGV; - - case EXCEPTION_BREAKPOINT: - case EXCEPTION_SINGLE_STEP: - return SIGTRACE; - - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_STACK_CHECK: - case EXCEPTION_FLT_UNDERFLOW: - return SIGFPE; - - case EXCEPTION_INT_DIVIDE_BY_ZERO: - case EXCEPTION_INT_OVERFLOW: - case EXCEPTION_ILLEGAL_INSTRUCTION: - case EXCEPTION_PRIV_INSTRUCTION: - return SIGILL; - - case EXCEPTION_STACK_OVERFLOW: - return SIGSTKFLT; - - case CONTROL_C_EXIT: - return SIGQUIT; - - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - case EXCEPTION_INVALID_DISPOSITION: - case EXCEPTION_INVALID_HANDLE: - return SIGILL; - } - return SIGILL; -} - - -#ifdef _WIN64 -static void *GetPointerToRegInCtx(CONTEXT *ctx, int32_t num) { - switch (num) { - case 0: return &ctx->Rax; - case 1: return &ctx->Rbx; - case 2: return &ctx->Rcx; - case 3: return &ctx->Rdx; - case 4: return &ctx->Rsi; - case 5: return &ctx->Rdi; - case 6: return &ctx->Rbp; - case 7: return &ctx->Rsp; - case 8: return &ctx->R8; - case 9: return &ctx->R9; - case 10:return &ctx->R10; - case 11:return &ctx->R11; - case 12:return &ctx->R12; - case 13:return &ctx->R13; - case 14:return &ctx->R14; - case 15:return &ctx->R15; - case 16:return &ctx->Rip; - case 17:return &ctx->EFlags; - case 18:return &ctx->SegCs; - case 19:return &ctx->SegSs; - case 20:return &ctx->SegDs; - case 21:return &ctx->SegEs; - case 22:return &ctx->SegFs; - case 23:return &ctx->SegGs; - } - - throw std::out_of_range("Register index out of range."); -} - -static int GetSizeofRegInCtx(int32_t num) { - CONTEXT *ctx = NULL; - switch (num) { - case 0: return sizeof ctx->Rax; - case 1: return sizeof ctx->Rbx; - case 2: return sizeof ctx->Rcx; - case 3: return sizeof ctx->Rdx; - case 4: return sizeof ctx->Rsi; - case 5: return sizeof ctx->Rdi; - case 6: return sizeof ctx->Rbp; - case 7: return sizeof ctx->Rsp; - case 8: return sizeof ctx->R8; - case 9: return sizeof ctx->R9; - case 10:return sizeof ctx->R10; - case 11:return sizeof ctx->R11; - case 12:return sizeof ctx->R12; - case 13:return sizeof ctx->R13; - case 14:return sizeof ctx->R14; - case 15:return sizeof ctx->R15; - case 16:return sizeof ctx->Rip; - case 17:return sizeof ctx->EFlags; - case 18:return sizeof ctx->SegCs; - case 19:return sizeof ctx->SegSs; - case 20:return sizeof ctx->SegDs; - case 21:return sizeof ctx->SegEs; - case 22:return sizeof ctx->SegFs; - case 23:return sizeof ctx->SegGs; - } - - throw std::out_of_range("Register index out of range."); -} - -#else - -static void *GetPointerToRegInCtx(CONTEXT *ctx, int32_t num) { - switch (num) { - case 0: return &ctx->Eax; - case 1: return &ctx->Ecx; - case 2: return &ctx->Edx; - case 3: return &ctx->Ebx; - case 4: return &ctx->Ebp; - case 5: return &ctx->Esp; - case 6: return &ctx->Esi; - case 7: return &ctx->Edi; - case 8: return &ctx->Eip; - case 9: return &ctx->EFlags; - case 10:return &ctx->SegCs; - case 11:return &ctx->SegSs; - case 12:return &ctx->SegDs; - case 13:return &ctx->SegEs; - case 14:return &ctx->SegFs; - case 15:return &ctx->SegGs; - } - - throw std::out_of_range("Register index out of range."); -} - -static int GetSizeofRegInCtx(int32_t num) { - CONTEXT *ctx = NULL; - switch (num) { - case 0: return sizeof ctx->Eax; - case 1: return sizeof ctx->Ecx; - case 2: return sizeof ctx->Edx; - case 3: return sizeof ctx->Ebx; - case 4: return sizeof ctx->Ebp; - case 5: return sizeof ctx->Esp; - case 6: return sizeof ctx->Esi; - case 7: return sizeof ctx->Edi; - case 8: return sizeof ctx->Eip; - case 9: return sizeof ctx->EFlags; - case 10:return sizeof ctx->SegCs; - case 11:return sizeof ctx->SegSs; - case 12:return sizeof ctx->SegDs; - case 13:return sizeof ctx->SegEs; - case 14:return sizeof ctx->SegFs; - case 15:return sizeof ctx->SegGs; - } - - throw std::out_of_range("Register index out of range."); -} -#endif - - -class Thread : public IThread { - public: - explicit Thread(uint32_t id) : ref_(1), id_(id), - handle_(NULL), state_(RUNNING) { - handle_ = OpenThread(THREAD_ALL_ACCESS, false, id); - memset(&context_, 0, sizeof(context_)); - context_.ContextFlags = CONTEXT_ALL; - if (NULL == handle_) state_ = DEAD; - } - - ~Thread() { - if (NULL == handle_) return; - - // This should always succeed, so ignore the return. - (void) CloseHandle(handle_); - } - - uint32_t GetId() { - return id_; - } - - State GetState() { - return state_; - } - - virtual bool Suspend() { - MutexLock lock(ThreadGetLock()); - if (state_ != RUNNING) return false; - - // Attempt to suspend the thread - DWORD count = SuspendThread(handle_); - - // Ignore result, since there is nothing we can do about - // it at this point. - (void) GetThreadContext(handle_, &context_); - - if (count != -1) { - state_ = SUSPENDED; - return true; - } - - return false; - } - - virtual bool Resume() { - MutexLock lock(ThreadGetLock()); - if (state_ != SUSPENDED) return false; - - // Ignore result, since there is nothing we can do about - // it at this point if the set fails. - (void) SetThreadContext(handle_, &context_); - - // Attempt to resume the thread - if (ResumeThread(handle_) != -1) { - state_ = RUNNING; - return true; - } - - return false; - } - - #define TRAP_FLAG (1 << 8) - virtual bool SetStep(bool on) { - if ((state_ == RUNNING) || (state_ == DEAD)) return false; - - if (on) { - context_.EFlags |= TRAP_FLAG; - } else { - context_.EFlags &= ~TRAP_FLAG; - } - return true; - } - - virtual bool GetRegister(uint32_t index, void *dst, uint32_t len) { - uint32_t clen = GetSizeofRegInCtx(index); - void* src = GetPointerToRegInCtx(&context_, index); - - if ((state_ == RUNNING) || (state_ == DEAD)) return false; - - // TODO(noelallen) we assume big endian - if (clen < len) len = clen; - memcpy(dst, src, len); - - return true; - } - - virtual bool SetRegister(uint32_t index, void* src, uint32_t len) { - uint32_t clen = GetSizeofRegInCtx(index); - void* dst = GetPointerToRegInCtx(&context_, index); - - if ((state_ == RUNNING) || (state_ == DEAD) || - (state_ != SYSCALL)) return false; - - // TODO(noelallen) we assume big endian - if (clen < len) len = clen; - memcpy(dst, src, len); - - return true; - } - - virtual void* GetContext() { return &context_; } - - //swi_lsp: non-browser app; disable - - static LONG NTAPI ExceptionCatch(PEXCEPTION_POINTERS ep) { -/* - printf("---> ExceptionCatch(PEXCEPTION_POINTERS: addr=%p code=%d=0x%X=%s [%d-%s]\n", - ep->ExceptionRecord->ExceptionAddress, - ep->ExceptionRecord->ExceptionCode, - ep->ExceptionRecord->ExceptionCode, - ExceptionCodeStr(ep->ExceptionRecord->ExceptionCode), ep->ExceptionRecord->NumberParameters, - ep->ExceptionRecord->ExceptionInformation[1]); -*/ - if(DBG_PRINTEXCEPTION_C == ep->ExceptionRecord->ExceptionCode) - return EXCEPTION_CONTINUE_EXECUTION; - - uint32_t id = static_cast<uint32_t>(GetCurrentThreadId()); - Thread* thread = static_cast<Thread*>(Acquire(id)); - - // If we are not tracking this thread, then ignore it - if (NULL == thread) return EXCEPTION_CONTINUE_SEARCH; - - State old_state = thread->state_; - thread->state_ = SIGNALED; - int8_t sig = ExceptionToSignal(ep->ExceptionRecord->ExceptionCode); - - void *ctx = thread->GetContext(); - - memcpy(ctx, ep->ContextRecord, sizeof(CONTEXT)); - if (NULL != s_CatchFunc) s_CatchFunc(id, sig, s_CatchCookie); - memcpy(ep->ContextRecord, ctx, sizeof(CONTEXT)); - - thread->state_ = old_state; - Release(thread); - return EXCEPTION_CONTINUE_EXECUTION; - } - - - - private: - uint32_t ref_; - uint32_t id_; - State state_; - HANDLE handle_; - CONTEXT context_; - - friend class IThread; -}; - -IThread* IThread::Acquire(uint32_t id, bool create) { - MutexLock lock(ThreadGetLock()); - Thread* thread; - ThreadMap_t &map = *ThreadGetMap(); - - // Check if we have that thread - if (map.count(id)) { - thread = static_cast<Thread*>(map[id]); - thread->ref_++; - return thread; - } - - // If not, can we create it? - if (create) { - // If not add it to the map - thread = new Thread(id); - if (NULL == thread->handle_) { - delete thread; - return NULL; - } - - map[id] = thread; - return thread; - } - - return NULL; -} - -void IThread::Release(IThread *ithread) { - MutexLock lock(ThreadGetLock()); - Thread* thread = static_cast<Thread*>(ithread); - thread->ref_--; - - if (thread->ref_ == 0) { - ThreadGetMap()->erase(thread->id_); - delete static_cast<IThread*>(thread); - } -} - -void IThread::SetExceptionCatch(IThread::CatchFunc_t func, void *cookie) { - MutexLock lock(ThreadGetLock()); - - // Remove our old catch if there is one, this allows us to add again - if (NULL != s_OldCatch) RemoveVectoredExceptionHandler(s_OldCatch); - - // Add the new one, at the front of the list - s_OldCatch = AddVectoredExceptionHandler(1, Thread::ExceptionCatch); - s_CatchFunc = func; - s_CatchCookie = cookie; -} - - -} // End of port namespace - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.cc deleted file mode 100644 index 10e9449..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.cc +++ /dev/null @@ -1,208 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> - -#include <map> -#include <string> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/port/platform.h" - -using port::IPlatform; - -namespace gdb_rsp { - -#define MINIDEF(x, name, purpose) { #name, sizeof(x), Abi::purpose, 0, 0 } -#define BPDEF(x) { sizeof(x), x } - -static Abi::RegDef RegsX86_64[] = { - MINIDEF(uint64_t, rax, GENERAL), - MINIDEF(uint64_t, rbx, GENERAL), - MINIDEF(uint64_t, rcx, GENERAL), - MINIDEF(uint64_t, rdx, GENERAL), - MINIDEF(uint64_t, rsi, GENERAL), - MINIDEF(uint64_t, rdi, GENERAL), - MINIDEF(uint64_t, rbp, GENERAL), - MINIDEF(uint64_t, rsp, GENERAL), - MINIDEF(uint64_t, r8, GENERAL), - MINIDEF(uint64_t, r9, GENERAL), - MINIDEF(uint64_t, r10, GENERAL), - MINIDEF(uint64_t, r11, GENERAL), - MINIDEF(uint64_t, r12, GENERAL), - MINIDEF(uint64_t, r13, GENERAL), - MINIDEF(uint64_t, r14, GENERAL), - MINIDEF(uint64_t, r15, GENERAL), - MINIDEF(uint64_t, rip, INST_PTR), - MINIDEF(uint32_t, eflags, FLAGS), - MINIDEF(uint32_t, cs, SEGMENT), - MINIDEF(uint32_t, ss, SEGMENT), - MINIDEF(uint32_t, ds, SEGMENT), - MINIDEF(uint32_t, es, SEGMENT), - MINIDEF(uint32_t, fs, SEGMENT), - MINIDEF(uint32_t, gs, SEGMENT), -}; - -static Abi::RegDef RegsX86_32[] = { - MINIDEF(uint32_t, eax, GENERAL), - MINIDEF(uint32_t, ecx, GENERAL), - MINIDEF(uint32_t, edx, GENERAL), - MINIDEF(uint32_t, ebx, GENERAL), - MINIDEF(uint32_t, esp, GENERAL), - MINIDEF(uint32_t, ebp, GENERAL), - MINIDEF(uint32_t, esi, GENERAL), - MINIDEF(uint32_t, edi, GENERAL), - MINIDEF(uint32_t, eip, INST_PTR), - MINIDEF(uint32_t, eflags, FLAGS), - MINIDEF(uint32_t, cs, SEGMENT), - MINIDEF(uint32_t, ss, SEGMENT), - MINIDEF(uint32_t, ds, SEGMENT), - MINIDEF(uint32_t, es, SEGMENT), - MINIDEF(uint32_t, fs, SEGMENT), - MINIDEF(uint32_t, gs, SEGMENT), -}; - -static Abi::RegDef RegsArm[] = { - MINIDEF(uint32_t, r0, GENERAL), - MINIDEF(uint32_t, r1, GENERAL), - MINIDEF(uint32_t, r2, GENERAL), - MINIDEF(uint32_t, r3, GENERAL), - MINIDEF(uint32_t, r4, GENERAL), - MINIDEF(uint32_t, r5, GENERAL), - MINIDEF(uint32_t, r6, GENERAL), - MINIDEF(uint32_t, r7, GENERAL), - MINIDEF(uint32_t, r8, GENERAL), - MINIDEF(uint32_t, r9, GENERAL), - MINIDEF(uint32_t, r10, GENERAL), - MINIDEF(uint32_t, r11, GENERAL), - MINIDEF(uint32_t, r12, GENERAL), - MINIDEF(uint32_t, sp, STACK_PTR), - MINIDEF(uint32_t, lr, LINK_PTR), - MINIDEF(uint32_t, pc, INST_PTR), -}; - -static uint8_t BPCodeX86[] = { 0xCC }; - -static Abi::BPDef BPX86 = BPDEF(BPCodeX86); - -static AbiMap_t s_Abis; - -// AbiInit & AbiIsAvailable -// This pair of functions work together as singleton to -// ensure the module has been correctly initialized. All -// dependant functions should call AbiIsAvailable to ensure -// the module is ready. -static bool AbiInit() { - Abi::Register("i386", RegsX86_32, sizeof(RegsX86_32), &BPX86); - Abi::Register("i386:x86-64", RegsX86_64, sizeof(RegsX86_64), &BPX86); - - // TODO(cbiffle) Figure out how to REALLY detect ARM, and define Breakpoint - Abi::Register("iwmmxt", RegsArm, sizeof(RegsArm), NULL); - - return true; -} - -static bool AbiIsAvailable() { - static bool initialized_ = AbiInit(); - return initialized_; -} - - - -Abi::Abi() {} -Abi::~Abi() {} - -void Abi::Register(const char *name, RegDef *regs, - uint32_t bytes, const BPDef *bp) { - uint32_t offs = 0; - const uint32_t cnt = bytes / sizeof(RegDef); - - // Build indexes and offsets - for (uint32_t loop = 0; loop < cnt; loop++) { - regs[loop].index_ = loop; - regs[loop].offset_ = offs; - offs += regs[loop].bytes_; - } - - Abi *abi = new Abi; - - abi->name_ = name; - abi->regCnt_ = cnt; - abi->regDefs_= regs; - abi->ctxSize_ = offs; - abi->bpDef_ = bp; - - s_Abis[name] = abi; -} - -const Abi* Abi::Find(const char *name) { - if (!AbiIsAvailable()) { - IPlatform::LogError("Failed to initalize ABIs."); - return NULL; - } - - AbiMap_t::const_iterator itr = s_Abis.find(name); - if (itr == s_Abis.end()) return NULL; - - return itr->second; -} - -const Abi* Abi::Get() { - static const Abi* abi = NULL; - - if ((NULL == abi) && AbiIsAvailable()) { -#ifdef GDB_RSP_ABI_ARM - abi = Abi::Find("iwmmxt"); -#elif GDB_RSP_ABI_X86_64 - abi = Abi::Find("i386:x86-64"); -#elif GDB_RSP_ABI_X86 - abi = Abi::Find("i386"); -#else -#error "Unknown CPU architecture." -#endif - } - - return abi; -} - -const char* Abi::GetName() const { - return name_; -} - -const Abi::BPDef *Abi::GetBreakpointDef() const { - return bpDef_; -} - -uint32_t Abi::GetContextSize() const { - return ctxSize_; -} - -uint32_t Abi::GetRegisterCount() const { - return regCnt_; -} - -const Abi::RegDef *Abi::GetRegisterDef(uint32_t index) const { - if (index >= regCnt_) return NULL; - - return ®Defs_[index]; -} - -const Abi::RegDef *Abi::GetRegisterType(RegType rtype, uint32_t nth) const { - uint32_t typeNum = 0; - - // Scan for the "nth" register of rtype; - for (uint32_t regNum = 0; regNum < regCnt_; regNum++) { - if (rtype == regDefs_[regNum].type_) { - if (typeNum == nth) return ®Defs_[regNum]; - typeNum++; - } - } - - // Otherwise we failed to find it - return NULL; -} - -} // namespace gdb_rsp - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.h deleted file mode 100644 index 69d0a6d..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi.h +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -// This module provides an interface for performing ABI specific -// functions needed by the Target and Host. ABI objects are provided -// to the rest of the system as "const" to prevent accidental modification. -// None of the resources in the Abi object are actually owned by the Abi -// object, they are assumed to be static and never destroyed. -// -// This module will only throw standard errors -// std::bad_alloc - when out of memory -// std::out_of_range - when using an out of range regsiter index -// -// It is required that Init be called prior to calling Find to ensure -// the various built-in ABIs have been registered. - -#ifndef NATIVE_CLIENT_GDB_RSP_ABI_H_ -#define NATIVE_CLIENT_GDB_RSP_ABI_H_ 1 - -#include <map> -#include <string> - -#include "native_client/src/debug_server/port/std_types.h" - -namespace gdb_rsp { - -class Abi { - public: - enum RegType { - GENERAL, - LINK_PTR, - INST_PTR, - STACK_PTR, - FRAME_PTR, - BASE_PTR, - SEGMENT, - TLS, - FLAGS, - CONTROL, - REG_TYPE_CNT - }; - - // Defines an individual register - struct RegDef { - const char *name_; - uint32_t bytes_; - RegType type_; - uint32_t index_; - uint32_t offset_; - }; - - // Defines how breakpoints work. - // code_ points to a series of bytes which will be placed in the code to - // create the breakpoint. size_ is the size of that array. We use a 32b - // size since the memory modification API only supports a 32b size. - struct BPDef { - uint32_t size_; - uint8_t *code_; - }; - - // Returns the registered name of this ABI. - const char *GetName() const; - - // Returns a pointer to the breakpoint definition. - const BPDef *GetBreakpointDef() const; - - // Returns the size of the thread context. - uint32_t GetContextSize() const; - - // Returns the number of registers visbible. - uint32_t GetRegisterCount() const; - - // Returns a definition of the register at the provided index, or - // NULL if it does not exist. - const RegDef *GetRegisterDef(uint32_t index) const; - - // Returns the 'nth' register of the type specified or NULL if it - // does not exist. - const RegDef *GetRegisterType(RegType rt, uint32_t index = 0) const; - - // Called to assign a set of register definitions to an ABI. - // This function is non-reentrant. - static void Register(const char *name, RegDef *defs, - uint32_t cnt, const BPDef *bp); - - // Called to search the map for a matching Abi by name. - // This function is reentrant. - static const Abi *Find(const char *name); - - // Get the ABI of for the running application. - static const Abi *Get(); - - protected: - const char *name_; - const RegDef *regDefs_; - uint32_t regCnt_; - uint32_t ctxSize_; - const BPDef *bpDef_; - - private: - Abi(); - ~Abi(); - void operator =(const Abi&); -}; - -typedef std::map<std::string, Abi*> AbiMap_t; - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_ABI_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi_test.cc deleted file mode 100644 index 1244912..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/abi_test.cc +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" - -using gdb_rsp::Abi; - -int VerifyAbi(const char *name, uint32_t regs) { - int errs = 0; - - const Abi *abi = Abi::Find(name); - if (NULL != abi) { - uint32_t regCnt = abi->GetRegisterCount(); - uint32_t byteCnt= abi->GetContextSize(); - uint32_t bytes = 0; - uint32_t loop = 0; - - if (strcmp(abi->GetName(), name)) { - printf("Incorrect name for ABI %s.\n", name); - errs++; - } - - if (regCnt != regs) { - printf("Incorrect number of registers for ABI %s.\n", name); - errs++; - } - - if (abi->GetRegisterDef(regs) != NULL) { - printf("Unexpected register for ABI %s.\n", name); - errs++; - } - - for (loop = 0; loop < regs; loop++) { - const Abi::RegDef *def = abi->GetRegisterDef(loop); - if (NULL == def) { - printf("Missing register for ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - if (NULL == def->name_) { - printf("Missing register name for ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - if (loop != def->index_) { - printf("Index mismatch for ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - if ((1 > def->bytes_) || (def->bytes_ > byteCnt)) { - printf("Index mismatch for ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - if ((def->type_ < Abi::GENERAL) || (def->type_ >= Abi::REG_TYPE_CNT)) { - printf("Illegal register type ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - if (def->offset_ != bytes) { - printf("Offset mismatch in ABI %s, reg %d.\n", name, loop); - errs++; - break; - } - - bytes += def->bytes_; - } - - if (bytes != byteCnt) { - printf("Context size mismatch for ABI %s.\n", name); - errs++; - } - - if (abi->GetRegisterType(Abi::GENERAL) == NULL) { - printf("Missing general registers for ABI %s.\n", name); - errs++; - } - - if (abi->GetRegisterType(Abi::INST_PTR) == NULL) { - printf("Missing instruction pointer for ABI %s.\n", name); - errs++; - } - } else { - printf("Could not find ABI %s.\n", name); - errs++; - } - return errs; -} - -int TestAbi() { - int errs = 0; - - // TODO(cbiffle) Figure out how to REALLY detect ARM - errs += VerifyAbi("iwmmxt", 16); - errs += VerifyAbi("i386", 16); - errs += VerifyAbi("i386:x86-64", 24); - - // Get the default ABI - const Abi* abi = Abi::Get(); - if (NULL == abi) { - printf("Failed to get default ABI.\n"); - errs++; - } - - // Get a generic register - const Abi::RegDef *def = abi->GetRegisterType(Abi::GENERAL); - if (NULL == def) { - printf("Failed to get a generic register on the default ABI %s.\n", - abi->GetName()); - errs++; - } else { - if (def->bytes_ != sizeof(intptr_t)) { - printf("Generic register %d != %d pointer size for %s\n", - static_cast<int>(def->bytes_), - static_cast<int>(sizeof(intptr_t)), - abi->GetName()); - errs++; - } - } - - if (NULL != Abi::Find("non-existant")) { - printf("Found 'non-existant' ABI.\n"); - errs++; - } - - return errs; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/build.scons b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/build.scons deleted file mode 100644 index c43e781..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/build.scons +++ /dev/null @@ -1,57 +0,0 @@ -# -*- python -*- -# Copyright 2010 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can -# be found in the LICENSE file. - -# This file needs to be in sync with $SOURCE_ROOT/ppapi/ppapi.gyp -# at the revision specified in $SOURCE_ROOT/native_client/DEPS. - -Import('env') - -# this is needed for including gdb_utils files -env.Append(CPPPATH=['${SOURCE_ROOT}/gdb_utils/src']) - -if env.Bit('windows'): - env.Append(CPPDEFINES=['WIN32']) - if env.Bit('target_x86_64'): - env.Append(CPPDEFINES=['WIN64']) - -if env.Bit('target_arm'): - env.Append(CPPDEFINES=['GDB_RSP_ABI_ARM']) -elif env.Bit('target_x86'): - env.Append(CPPDEFINES=['GDB_RSP_ABI_X86']) - if env.Bit('target_x86_64'): - env.Append(CPPDEFINES=['GDB_RSP_ABI_X86_64']) -else: - raise Exception("Unknown target") - -rsp_sources = [ - 'abi.cc', - 'host.cc', - 'packet.cc', - 'session.cc', - 'target.cc', - 'util.cc', - ] - -rsp_test_sources = [ - 'abi_test.cc', - 'host_test.cc', - 'packet_test.cc', - 'session_test.cc', - 'session_mock.cc', - 'target_test.cc', - 'util_test.cc', - 'test.cc' - ] - -# Build only for Win64 -env.DualLibrary('gdb_rsp', rsp_sources) -gdb_rsp_test_exe = env.ComponentProgram('gdb_rsp_unittest', - rsp_test_sources, - EXTRA_LIBS=['gdb_rsp']) - -node = env.CommandTest( - 'gdb_rsp_unittest.out', - command=[gdb_rsp_test_exe]) -env.AddNodeToTestSuite(node, ['small_tests'], 'run_gdb_rsp_tests') diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.gyp b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.gyp deleted file mode 100644 index e634300..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.gyp +++ /dev/null @@ -1,162 +0,0 @@ -# -*- python -*- -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -{ - 'includes': [ - '../../../build/common.gypi', - ], - 'target_defaults': { - 'conditions': [ - ['target_arch=="ia32"', { - 'defines': [ - 'GDB_RSP_ABI_X86', - ], - }], - ['target_arch=="x64"', { - 'defines': [ - 'GDB_RSP_ABI_X86', - 'GDB_RSP_ABI_X86_64', - ], - }], - ['target_arch=="arm"', { - 'defines': [ - 'GDB_RSP_ABI_ARM', - ], - }], - ], - 'target_conditions': [ - ['OS=="linux" or OS=="mac"', { - 'cflags': [ - '-fexceptions', - ], - 'cflags_cc' : [ - '-frtti', - ] - }], - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', # -fexceptions - 'GCC_ENABLE_CPP_RTTI': 'YES', # -frtti - } - }], - ['OS=="win"', { - 'msvs_settings': { - 'VCCLCompilerTool': { - 'ExceptionHandling': '1', - 'RuntimeTypeInfo': 'true', - }, - } - }], - ], - }, - 'variables': { - 'gdb_rsp_sources': [ - 'abi.cc', - 'abi.h', - 'host.cc', - 'host.h', - 'packet.cc', - 'packet.h', - 'session.cc', - 'session.h', - 'target.cc', - 'target.h', - 'util.cc', - 'util.h', - ], - 'gdb_test_sources': [ - 'abi_test.cc', - 'packet_test.cc', - 'host_test.cc', - 'session_mock.h', - 'session_mock.cc', - 'session_test.cc', - 'target_test.cc', - 'util_test.cc', - 'test.cc', - 'test.h', - ], - }, - 'targets': [ - { - 'target_name': 'gdb_rsp', - 'type': 'static_library', - 'sources': [ - '<@(gdb_rsp_sources)', - ], - }, - { - 'target_name': 'gdb_rsp_test', - 'type': 'executable', - 'sources': [ - '<@(gdb_test_sources)', - ], - 'dependencies': [ - 'gdb_rsp', - ] - }, - ], - 'conditions': [ - ['OS=="win"', { - 'targets': [ - { - 'target_name': 'gdb_rsp64', - 'type': 'static_library', - 'sources': [ - '<@(gdb_rsp_sources)', - ], - 'defines': [ - 'GDB_RSP_ABI_X86_64', - ], - 'configurations': { - 'Common_Base': { - 'msvs_target_platform': 'x64', - }, - }, - }, - { - 'target_name': 'gdb_rsp_test64', - 'type': 'executable', - 'sources': [ - '<@(gdb_test_sources)', - ], - 'configurations': { - 'Common_Base': { - 'msvs_target_platform': 'x64', - }, - }, - 'dependencies': [ - 'gdb_rsp64', - ] - }, - ], - }], - ], -} diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.rules b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.rules deleted file mode 100644 index bc56170..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="gdb_rsp" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp64.rules b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp64.rules deleted file mode 100644 index 79d04ca..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp64.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="gdb_rsp64" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test.rules b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test.rules deleted file mode 100644 index 6a3ddbdd3..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="gdb_rsp_test" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test64.rules b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test64.rules deleted file mode 100644 index f63bc2e..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/gdb_rsp_test64.rules +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioToolFile Name="gdb_rsp_test64" Version="8.00"> - <Rules> - <CustomBuildRule AdditionalDependencies="..\..\..\..\native_client\tools\win_as.py;$(InputPath)" CommandLine="..\..\..\..\native_client\tools\win_py.cmd ..\..\..\..\native_client\tools\win_as.py -a $(PlatformName) -o $(IntDir)\$(InputName).obj -p ..\..\..\.. $(InputPath)" ExecutionDescription="Building assembly language file $(InputPath)" FileExtensions="S" Name="assembler (gnu-compatible)" Outputs="$(IntDir)\$(InputName).obj"/> - </Rules> -</VisualStudioToolFile> diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.cc deleted file mode 100644 index 4514df7..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.cc +++ /dev/null @@ -1,523 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <string.h> -#include <stdlib.h> -#include <stdio.h> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/host.h" -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" - -#include "native_client/src/debug_server/port/std_types.h" -#include "native_client/src/debug_server/port/platform.h" - -#ifdef WIN32 -#define snprintf sprintf_s -#endif - - -using std::string; -using port::IPlatform; - -namespace gdb_rsp { - -Host::Thread::Thread(const Abi *abi, uint32_t id) - : id_(id), ctx_(NULL), abi_(abi) { - ctx_ = new uint8_t[abi_->GetContextSize()]; - assert(NULL != ctx_); -} - -Host::Thread::~Thread() { - delete[] ctx_; -} - -uint32_t Host::Thread::GetId() const { - return id_; -} - -const Abi *Host::Thread::GetAbi() const { - return abi_; -} - -void Host::Thread::GetRegister(uint32_t index, void *dst) const { - assert(NULL != dst); - assert(index < abi_->GetRegisterCount()); - - const Abi::RegDef *def = abi_->GetRegisterDef(index); - uint8_t *ptr = ctx_ + def->offset_; - memcpy(dst, ptr, def->bytes_); -} - -void Host::Thread::SetRegister(uint32_t index, const void *src) { - assert(src); - assert(index < abi_->GetRegisterCount()); - - const Abi::RegDef *def = abi_->GetRegisterDef(index); - uint8_t *ptr = ctx_ + def->offset_; - memcpy(ptr, src, def->bytes_); -} - - -// Construct unitialzied -Host::Host(Session *session) : session_(session), abi_(NULL), - status_(HS_UNINIT) { } - -Host::~Host() { } - -bool Host::Init() { - string reply; - - properties_.clear(); - - // Set the default max packet size. We use the default value - // that GDB appears to like which is 1K - xsum/etc overhead. - properties_["PacketSize"] = "3fa"; - - // Get properties - if (!Request("qSupported", &reply)) return false; - - // Parse the semicolon delimited properties - stringvec tokens = StringSplit(reply.data(), ";"); - for (uint32_t loop = 0; loop < tokens.size(); loop++) { - // Properties are in the form of "Key=Val", "Key+", or "Key-" - string &prop = tokens[loop]; - - // If the form is Key=Val, there should be two components Key and Val - stringvec keyval = StringSplit(prop, "="); - if (keyval.size() == 2) { - properties_[keyval[0]] = keyval[1]; - continue; - } - - // Strip off the + or - by splitting to get the name. - keyval = StringSplit(prop, "+-"); - // Size==1 means we got either XXX, XXX+, or XXX- - if (keyval.size() == 1) { - size_t len = prop.length(); - // In which case the last character must be + or -, or we ignore. - switch (prop[len - 1]) { - case '+' : - properties_[keyval[0]] = "true"; - continue; - case '-' : - properties_[keyval[0]] = "false"; - continue; - } - } - - // Otherwise it was a malformed property - IPlatform::LogError("Returned feature with strange assignment: %s", - prop.data()); - } - - // Must support and use property read method to get CPU type - if (!ReadObject("features", "target.xml", &reply)) return false; - - // Search for start of "architecture" tag - const char *name = strstr(reply.data(), "<architecture>"); - if (NULL != name) { - // Size of "<architecture>" - const int nameStart = 14; - char *str = strdup(&name[nameStart]); - char *term = strchr(str, '<'); - *term = 0; - - abi_ = Abi::Find(str); - free(str); - } - - // Check if we failed to find the correct ABI - if (NULL == abi_) { - IPlatform::LogError("Failed to find ABI for %s\n", reply.data()); - return false; - } - - return Update(); -} - -bool Host::Update() { - ThreadVector_t old_ids; - ThreadVector_t new_ids; - - ThreadMap_t::const_iterator itr = threads_.begin(); - while (itr != threads_.end()) { - old_ids.push_back(itr->first); - itr++; - } - - if (!RequestThreadList(&new_ids)) return false; - - for (uint32_t loop = 0; loop < new_ids.size(); loop++) { - // Large enough for log10(2^32) + NUL + "Hg"; - char tmp[16]; - - uint32_t id = new_ids[loop]; - string request; - string ignore_reply; - - snprintf(tmp, sizeof(tmp), "Hg%x", id); - if (!Request(tmp, &ignore_reply)) { - IPlatform::LogError("Failed to set thread context for %d.\n", id); - continue; - } - - Packet req, resp; - req.AddString("g"); - if (!Send(&req, &resp)) { - IPlatform::LogError("Failed to get thread registers for %d.\n", id); - continue; - } - - Thread *thread = threads_[id]; - if (NULL == thread) { - thread = new Thread(abi_, id); - threads_[id] = thread; - } - - resp.GetBlock(thread->ctx_, abi_->GetContextSize()); - } - - // Update the current state - string reply; - if (Request("?", &reply)) return ParseStopPacket(reply.data()); - - // If we are not "broken" then we must have failed to update - return false; -} - -bool Host::GetThreads(ThreadVector_t* threads) const { - // We can get threads if stopped - if (HS_STOPPED != status_) return false; - - threads->clear(); - ThreadMap_t::const_iterator itr = threads_.begin(); - while (itr != threads_.end()) { - threads->push_back(itr->first); - itr++; - } - - return true; -} - -bool Host::Step() { - Packet out; - - // We can only step if we are stopped - if (HS_STOPPED != status_) return false; - - out.AddRawChar('s'); - if (SendOnly(&out)) { - // We are running again (even if we expect to immediately break) - status_ = HS_RUNNING; - return true; - } - - return false; -} - -bool Host::Continue() { - Packet out; - - // We can only step if we are stopped - if (HS_STOPPED != status_) return false; - - out.AddRawChar('c'); - if (SendOnly(&out)) { - // We are running again - status_ = HS_RUNNING; - return true; - } - - return false; -} - -// Wait to see if we receive a break -bool Host::WaitForBreak() { - // We can not wait if we are not running - if (HS_RUNNING != status_) return false; - - Packet rx; - std::string str; - if (session_->GetPacket(&rx) == false) return false; - - rx.GetString(&str); - if (ParseStopPacket(str.data())) return Update(); - return false; -} - - - -Host::Thread* Host::GetThread(uint32_t id) { - ThreadMap_t::const_iterator itr; - itr = threads_.find(id); - - if (itr == threads_.end()) return NULL; - - return itr->second; -} - -bool Host::ParseStopPacket(const char *data) { - if (strlen(data) < 3) return false; - - // Stop in the form of (S|T|W|X)[XX]{n=xxx,r=yyy;{...}} - // where XX is the result code (Unix signal number for stops) - // or the form of OXX{XX..} where XX is a hex pair encoded string. - switch (data[0]) { - // Both S & T signals are a normal stop - case 'S': - case 'T': - status_ = HS_STOPPED; - break; - - case 'W': - status_ = HS_EXIT; - break; - - case 'X': - status_ = HS_TERMINATED; - break; - - case 'O': - return true; - - default: - return false; - } - - if (!NibblesToByte(&data[1], &lastSignal_)) return false; - - return true; -} - - -bool Host::RequestThreadList(ThreadVector_t* ids) { - string reply; - - ids->clear(); - - if (!Request("qfThreadInfo", &reply)) return false; - - do { - // Check if we are done - if (reply == "l") return true; - - if (reply[0] != 'm') { - IPlatform::LogError("Expecting diffent thread format: %s\n", - reply.data()); - return false; - } - - stringvec replys = StringSplit(&reply[1], ","); - for (uint32_t loop = 0; loop < replys.size(); loop++) { - ids->push_back(strtol(replys[loop].data(), NULL, 16)); - } - } while (Request("qsThreadInfo", &reply)); - - IPlatform::LogError("Failed request of qsThreadInfo.\n", reply.data()); - return false; -} - -bool Host::HasProperty(const char *name) const { - std::map<string, string>::const_iterator itr; - itr = properties_.find(name); - - return properties_.end() != itr; -} - -bool Host::ReadProperty(const char *name, string* val) const { - std::map<string, string>::const_iterator itr; - itr = properties_.find(name); - - if (properties_.end() == itr) return false; - - *val = itr->second; - return true; -} - - -bool Host::ReadObject(const char *type, const char *name, string *reply) { - uint32_t offset = 0; - uint32_t maxTX = 1024; - reply->clear(); - - if (ReadProperty("PacketSize", reply)) { - maxTX = static_cast<uint32_t>(strtol(reply->data(), NULL, 16)); - } - - while (1) { - // We make this 64B to hold 2xlog16(2^64) + NUL + 14 characters although - // in practice these tend to be 16b values. - char tmp[64]; - - string replyPiece; - string query = "qXfer:"; - query += type; - query += ":read:"; - query += name; - snprintf(tmp, sizeof(tmp), ":%x,%x", offset, maxTX); - query += tmp; - - if (!Request(query, &replyPiece)) return false; - - if (replyPiece[0] == 'l') { - *reply += &replyPiece[1]; - return true; - } - - if ((replyPiece[0] == 'E') && (replyPiece.length() == 3)) { - return false; - } - - if (replyPiece[0] != 'm') { - IPlatform::LogError("Expecting more or end signal got:\n\t%s.", - replyPiece.data()); - return false; - } - - *reply += replyPiece; - offset += static_cast<uint32_t>(replyPiece.length()); - } - - return true; -} - -bool Host::Break() { - char brk[2] = { 0x03, 0x00 }; - - // We can only break if running - if (HS_RUNNING != status_) return false; - - status_ = HS_STOPPING; - return RequestOnly(brk); -} - -bool Host::Detach() { - // We can only detach if stopped - if (HS_STOPPED != status_) return false; - - return RequestOnly("d"); -} - -int32_t Host::GetSignal() { - // We always return the lasted cached value - return lastSignal_; -} - -Host::Status Host::GetStatus() { - return status_; -} - -bool Host::GetMemory(void *dst, uint64_t addr, uint32_t size) { - char *ptr = reinterpret_cast<char *>(dst); - uint32_t maxTX = 1024; - string reply; - Packet pktReq, pktReply; - - // We can only access memory if stopped - if (HS_STOPPED != status_) return false; - - if (ReadProperty("PacketSize", &reply)) { - maxTX = strtoul(reply.data(), NULL, 16); - } - - // Reply is encoded as two nibbles plus a single char - // Mxxxxxxxx... - maxTX = (maxTX - 1) / 2; - - while (size) { - uint32_t len = size; - if (len > maxTX) len = maxTX; - - pktReq.Clear(); - pktReq.AddRawChar('m'); - pktReq.AddNumberSep(addr, ','); - pktReq.AddNumberSep(size, 0); - - if (!Send(&pktReq, &pktReply)) return false; - - if (!pktReply.GetBlock(ptr, len)) return false; - - ptr += len; - addr += len; - size -= len; - } - - return true; -} - -bool Host::SetMemory(const void *src, uint64_t addr, uint32_t size) { - const char *ptr = reinterpret_cast<const char *>(src); - uint32_t maxTX = 1024; - string reply; - Packet pktReq, pktReply; - - // We can only access memory if stopped - if (HS_STOPPED != status_) return false; - - if (ReadProperty("PacketSize", &reply)) { - maxTX = strtoul(reply.data(), NULL, 16); - } - - // Reply is encoded as two nibbles plus a single char(3), plus address (16) - // a and size (8) or Maaaaaaaaaaaaaaaa,ssssssss:(27) - maxTX = (maxTX - 27) / 2; - - while (size) { - uint32_t len = size; - if (len > maxTX) len = maxTX; - - pktReq.Clear(); - pktReq.AddRawChar('M'); - pktReq.AddNumberSep(addr, ','); - pktReq.AddNumberSep(len, ':'); - pktReq.AddBlock(src, len); - - if (!Send(&pktReq, &pktReply)) return false; - - ptr += len; - addr += len; - size -= len; - } - - return true; -} - -bool Host::RequestOnly(const string& req) { - Packet pktReq; - - pktReq.AddString(req.data()); - return SendOnly(&pktReq); -} - -bool Host::Request(const string& req, string *resp) { - Packet pktReq, pktResp; - - pktReq.AddString(req.data()); - bool result = Send(&pktReq, &pktResp); - - pktResp.GetString(resp); - - // Check for error code on return - if ((resp->length() == 3) && (resp->data()[0] == 'E')) return false; - - return result; -} - -bool Host::SendOnly(Packet *tx) { - return session_->SendPacketOnly(tx); -} - -bool Host::Send(Packet *tx, Packet *rx) { - if (!session_->SendPacket(tx)) return false; - return session_->GetPacket(rx); -} - -} // namespace gdb_rsp - - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.h deleted file mode 100644 index 09f9234..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host.h +++ /dev/null @@ -1,148 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -// This module provides an object for handling RSP responsibilities of -// the host side of the connection. The host behaves like a cache, and -// is responsible for syncronization of state between the Target and Host. -// For example, the Host is responsible for updating the thread context -// before restarting the Target, and for updating its internal array of -// threads whenever the Target stops. - -#ifndef NATIVE_CLIENT_GDB_RSP_HOST_H_ -#define NATIVE_CLIENT_GDB_RSP_HOST_H_ 1 - -#include <map> -#include <string> -#include <vector> - -#include "native_client/src/debug_server/port/std_types.h" - -namespace gdb_rsp { - -class Abi; -class Packet; -class Session; - -class Host { - public: - enum Status { - HS_UNINIT = -1, // Host is uninitialized - HS_RUNNING = 0, // The target is running (no sig since cont.) - HS_STOPPING = 1, // Host has issued a break request - HS_STOPPED = 2, // Host has received a signal and is stopped - HS_EXIT = 3, // Host has received an exit code - HS_TERMINATED = 4 // host has received a termination code - }; - - // The Host::Thread class represents a thread on the Target side, providing - // a cache for its state, which is automatically updated by the parent Host - // object whenever the target starts or stops. - class Thread { - public: - Thread(const Abi *abi, uint32_t id); - ~Thread(); - - public: - uint32_t GetId() const; - const Abi *GetAbi() const; - void GetRegister(uint32_t index, void *dst) const; - void SetRegister(uint32_t index, const void *src); - - private: - uint32_t id_; - uint8_t *ctx_; - const Abi *abi_; - - friend class Host; - }; - - typedef std::map<uint32_t, Host::Thread*> ThreadMap_t; - typedef std::map<std::string, std::string> PropertyMap_t; - typedef std::vector<uint32_t> ThreadVector_t; - - explicit Host(Session *session); - ~Host(); - bool Init(); - - // The following functions are provided cached values when possible. - // For instance, GetSignal, GetThreads, and GetThread, will return - // values that were computed during Update. - // cause a communication between the host and target, so the public - // functions above should be used when possible. - - // Issue a break request if the target is still running. This is - // asynchronous, we won't actually be "broken" until we get the signal - bool Break(); - - // Requests that we cleanly detach from the target. - bool Detach(); - - // Get the current status of the Target. - Status GetStatus(); - - // Get the last signal (which put us into the broken state) - int32_t GetSignal(); - - // Get a list of currently active threads - bool GetThreads(ThreadVector_t *threads) const; - - // Get a thread object by ID. - Thread *GetThread(uint32_t id); - - // Get and set a block of target memory. - bool GetMemory(void *dst, uint64_t addr, uint32_t size); - bool SetMemory(const void *src, uint64_t addr, uint32_t size); - - // Read locally cached properties - bool HasProperty(const char *name) const; - bool ReadProperty(const char *name, std::string *val) const; - - // Read remote object - bool ReadObject(const char *type, const char *name, std::string *val); - - // Set the SINGLE STEP flag on the current thread context, and - // putting the target back into the RUN state. - bool Step(); - - // Issue a step request, putting us back into the RUN state. - bool Continue(); - - // Wait upto the session's packet timeout to see if we receive a break - bool WaitForBreak(); - - // The following functions are internal only and cause communication to - // happen between the target and host. These functions will always - // cause a communication between the host and target, so the public - // functions above should be used when possible. - protected: - // Called whenever the target transitions from running to stopped to - // fetch information about the current state. - bool Update(); - - bool Send(Packet *req, Packet *resp); - bool SendOnly(Packet *req); - - bool Request(const std::string &req, std::string *resp); - bool RequestOnly(const std::string &req); - bool RequestThreadList(ThreadVector_t *ids); - - // Parse a string, returning true and update if a valid stop packet - bool ParseStopPacket(const char *data); - - private: - Session *session_; - const Abi *abi_; - - PropertyMap_t properties_; - ThreadMap_t threads_; - int32_t lastSignal_; - Status status_; -}; - - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_HOST_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host_test.cc deleted file mode 100644 index b578ac2..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/host_test.cc +++ /dev/null @@ -1,131 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <string> -#include <sstream> -#include <vector> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/host.h" -#include "native_client/src/debug_server/gdb_rsp/session_mock.h" -#include "native_client/src/debug_server/gdb_rsp/test.h" - -using gdb_rsp::Abi; -using gdb_rsp::Host; -using gdb_rsp::SessionMock; - -int VerifyProp(Host* host, const char *key, const char *val) { - std::string out; - if (!host->ReadProperty(key, &out)) { - printf("Could not find key: %s.\n", key); - return 1; - } - - if (out != val) { - printf("Property mismatch\n\tVALUE:%s\n\tEXPECTED:%s\n", - out.data(), val); - return 1; - } - - return 0; -} - -int TestHost() { - int errs = 0; - SessionMock *ses = gdb_rsp::GetGoldenSessionMock(false, false); - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - - Host *host = new Host(ses); - std::string val; - if (!host->Init()) { - printf("Failed to init host.\n"); - return 1; - } - - // Verify that the Init/Update transactions were - // correctly applied. - if (!host->HasProperty("qXfer:features:read")) { - printf("Missing property: qXfer:features:read\n"); - errs++; - } - - errs += VerifyProp(host, "PacketSize", "7cf"); - errs += VerifyProp(host, "qXfer:libraries:read", "true"); - Host::Thread* thread = host->GetThread(0x1234); - if (NULL == thread) { - printf("Failed to find expected thead 1234.\n"); - errs++; - } else { - for (uint32_t a = 0; a < abi->GetRegisterCount(); a++) { - const Abi::RegDef* def = abi->GetRegisterDef(a); - uint64_t val; - thread->GetRegister(a, &val); - if (static_cast<uint32_t>(val) != a) { - errs++; - printf("Register %s(%d) failed to match expected value: %x", - def->name_, a, static_cast<int>(val)); - break; - } - } - } - - if (host->GetStatus() != Host::HS_STOPPED) { - printf("We expect to be stopped at this point.\n"); - errs++; - } - - if (host->GetSignal() != 5) { - printf("We expect to see signal 5.\n"); - errs++; - } - - if (ses->PeekAction() != SessionMock::DISCONNECT) { - printf("We did not consume all the actions.\n"); - errs++; - } - - // Pop off the DC, and continue processing. - ses->GetAction(); - - // Verify we are now in a running state - ses->AddAction(SessionMock::SEND, "c"); - host->Continue(); - - // We should be running, and timing out on wait - if (host->GetStatus() != Host::HS_RUNNING) { - printf("We expect to be running at this point.\n"); - errs++; - } - if (host->WaitForBreak()) { - printf("We should have timed out.\n"); - errs++; - } - - // Insert a signal 11 for us to wait on - ses->AddAction(SessionMock::RECV, "S11"); - AddMockUpdate(ses, 0x11); - if (!host->WaitForBreak()) { - printf("We should have gotten a signal.\n"); - errs++; - } - if (host->GetStatus() != Host::HS_STOPPED) { - printf("We expect to be stopped at this point.\n"); - errs++; - } - if (host->GetSignal() != 0x11) { - printf("We expect to see signal 11.\n"); - errs++; - } - - delete host; - delete ses; - return errs; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.cc deleted file mode 100644 index 9061ac9..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.cc +++ /dev/null @@ -1,391 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -#include <assert.h> -#include <string.h> -#include <stdlib.h> - -#include <string> - -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" -#include "native_client/src/debug_server/port/platform.h" - -using std::string; -using port::IPlatform; - - -namespace gdb_rsp { - -#define MIN_PAD 1 -#define GROW_SIZE 64 - -Packet::Packet() { - seq_ = -1; - Clear(); -} - -void Packet::Clear() { - data_.clear(); - data_.resize(GROW_SIZE); - data_[0] = 0; - - read_index_ = 0; - write_index_ = 0; -} - -void Packet::Rewind() { - read_index_ = 0; -} - -bool Packet::EndOfPacket() const { - return (read_index_ >= write_index_); -} - -void Packet::AddRawChar(char ch) { - // Grow by a fixed amount whenever we are within the pad boundry. - // The pad boundry allows for the addition of NUL termination. - if (data_.size() <= (write_index_ + MIN_PAD)) { - data_.resize(data_.size() + GROW_SIZE); - } - - // Add character and always null terminate. - data_[write_index_++] = ch; - data_[write_index_] = 0; -} - -void Packet::AddWord8(uint8_t ch) { - char seq1, seq2; - - IntToNibble(ch >> 4, &seq1); - IntToNibble(ch & 0xF, &seq2); - - AddRawChar(seq1); - AddRawChar(seq2); -} - -void Packet::AddBlock(const void *ptr, uint32_t len) { - assert(ptr); - - const char *p = (const char *) ptr; - - for (uint32_t offs = 0; offs < len; offs++) { - AddWord8(p[offs]); - } -} - -void Packet::AddWord16(uint16_t val) { - AddBlock(&val, sizeof(val)); -} - -void Packet::AddWord32(uint32_t val) { - AddBlock(&val, sizeof(val)); -} - -void Packet::AddWord64(uint64_t val) { - AddBlock(&val, sizeof(val)); -} - -void Packet::AddString(const char *str) { - assert(str); - - while (*str) { - AddRawChar(*str); - str++; - } -} - -void Packet::AddHexString(const char *str) { - assert(str); - - while (*str) { - AddWord8(*str); - str++; - } -} - -void Packet::AddNumberSep(uint64_t val, char sep) { - char out[sizeof(val) * 2]; - int nibbles = 0; - size_t a; - - // Check for -1 optimization - if (val == static_cast<uint64_t>(-1)) { - AddRawChar('-'); - AddRawChar('1'); - } else { - // Assume we have the valuse 0x00001234 - for (a = 0; a < sizeof(val); a++) { - uint8_t byte = static_cast<uint8_t>(val & 0xFF); - - // Stream in with bytes reverse, starting at least significant - // So we store 4, then 3, 2, 1 - IntToNibble(byte & 0xF, &out[nibbles++]); - IntToNibble(byte >> 4, &out[nibbles++]); - - // Get the next 8 bits; - val >>= 8; - - // Supress leading zeros, so we are done when val hits zero - if (val == 0) break; - } - - // Strip the high zero for this byte if needed - if ((nibbles > 1) && (out[nibbles-1] == '0')) nibbles--; - - // Now write it out reverse to correct the order - while (nibbles) { - nibbles--; - AddRawChar(out[nibbles]); - } - } - - // If we asked for a sperator, insert it - if (sep) AddRawChar(sep); -} - -bool Packet::GetNumberSep(uint64_t *val, char *sep) { - uint64_t out = 0; - char ch; - - if (!GetRawChar(&ch)) return false; - - // Check for -1 - if (ch == '-') { - if (!GetRawChar(&ch)) return false; - - if (ch == '1') { - *val = -1; - - ch = 0; - GetRawChar(&ch); - if (sep) *sep = ch; - return true; - } - return false; - } - - do { - int nib; - - // Check for separator - if (!NibbleToInt(ch, &nib)) break; - - // Add this nibble. - out = (out << 4) + nib; - - // Get the next character (if availible) - ch = 0; - if (!GetRawChar(&ch)) break; - } while (1); - - // Set the value; - *val = out; - - // Add the separator if the user wants it... - if (sep != NULL) *sep = ch; - - return true; -} - -bool Packet::GetRawChar(char *ch) { - assert(ch != NULL); - - if (read_index_ >= write_index_) - return false; - - *ch = data_[read_index_++]; - - // Check for RLE X*N, where X is the value, N is the reps. - if (*ch == '*') { - if (read_index_ < 2) { - IPlatform::LogError("Unexpected RLE at start of packet.\n"); - return false; - } - - if (read_index_ >= write_index_) { - IPlatform::LogError("Unexpected EoP during RLE.\n"); - return false; - } - - // GDB does not use "CTRL" characters in the stream, so the - // number of reps is encoded as the ASCII value beyond 28 - // (which when you add a min rep size of 4, forces the rep - // character to be ' ' (32) or greater). - int32_t cnt = (data_[read_index_] - 28); - if (cnt < 3) { - IPlatform::LogError("Unexpected RLE length.\n"); - return false; - } - - // We have just read '*' and incremented the read pointer, - // so here is the old state, and expected new state. - // - // Assume N = 5, we grow by N - size of encoding (3). - // - // OldP: R W - // OldD: 012X*N89 = 8 chars - // Size: 012X*N89__ = 10 chars - // Move: 012X*__N89 = 10 chars - // Fill: 012XXXXX89 = 10 chars - // NewP: R W (shifted 5 - 3) - // - // To accomplish this we must first, resize the vector then move - // all remaining characters to the right, by the delta between - // the run length, and encoding size. This moves one more char - // than needed (the 'N'), but is easier to understand. - // NOTE: We add one to the resize to allow for zero termination. - data_.resize(write_index_ + cnt - 3 + 1); - memmove(&data_[read_index_ + cnt - 3], &data_[read_index_], - write_index_ - read_index_); - - // Now me must go back and fill over the previous '*' with the - // repeated character for the length of the run minus the original - // character which is already correct - *ch = data_[read_index_ - 2]; - memset(&data_[read_index_ - 1], *ch, cnt - 1); - - // Now we update the write_index_, and reterminate the string. - write_index_ = data_.size() - 1; - data_[write_index_] = 0; - } - return true; -} - -bool Packet::GetWord8(uint8_t *ch) { - assert(ch); - - char seq1, seq2; - int val1, val2; - - // Get two ASCII hex values - if (!GetRawChar(&seq1)) return false; - if (!GetRawChar(&seq2)) return false; - - // Convert them to ints - if (!NibbleToInt(seq1, &val1)) return false; - if (!NibbleToInt(seq2, &val2)) return false; - - *ch = (val1 << 4) + val2; - return true; -} - -bool Packet::GetBlock(void *ptr, uint32_t len) { - assert(ptr); - - uint8_t *p = reinterpret_cast<uint8_t *>(ptr); - bool res = true; - - for (uint32_t offs = 0; offs < len; offs++) { - res = GetWord8(&p[offs]); - if (false == res) break; - } - - return res; -} - -bool Packet::GetWord16(uint16_t *ptr) { - assert(ptr); - return GetBlock(ptr, sizeof(*ptr)); -} - -bool Packet::GetWord32(uint32_t *ptr) { - assert(ptr); - return GetBlock(ptr, sizeof(*ptr)); -} - -bool Packet::GetWord64(uint64_t *ptr) { - assert(ptr); - return GetBlock(ptr, sizeof(*ptr)); -} - - -bool Packet::GetString(string* str) { - if (EndOfPacket()) return false; - - *str = &data_[read_index_]; - read_index_ = write_index_; - return true; -} - -bool Packet::GetHexString(string* str) { - char ch; - if (EndOfPacket()) return false; - - // Pull values until we hit a seperator - str->clear(); - while (GetRawChar(&ch)) { - if (NibbleToInt(ch, NULL)) { - *str += ch; - } else { - read_index_--; - break; - } - } - return true; -} - -bool Packet::GetStringCB(void *ctx, StrFunc_t cb) { - assert(NULL != ctx); - - if (EndOfPacket()) { - cb(ctx, NULL); - return false; - } - - cb(ctx, &data_[read_index_]); - read_index_ = write_index_; - return true; -} - -bool Packet::GetHexStringCB(void *ctx, StrFunc_t cb) { - assert(NULL != ctx); - - std::string out; - char ch; - - if (EndOfPacket()) { - cb(ctx, NULL); - return false; - } - - // Pull values until we hit a seperator - while (GetRawChar(&ch)) { - if (NibbleToInt(ch, NULL)) { - out += ch; - } else { - read_index_--; - break; - } - } - - // Call the CB with the availible string - cb(ctx, out.data()); - return true; -} - - -const char *Packet::GetPayload() const { - return &data_[0]; -} - -bool Packet::GetSequence(int32_t *ch) const { - assert(ch); - - if (seq_ != -1) { - *ch = seq_; - return true; - } - - return false; -} - -void Packet::SetSequence(int32_t val) { - seq_ = val; -} - -} // namespace gdb_rsp - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.h deleted file mode 100644 index 1a5847b..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet.h +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module provides interfaces for writing to and reading from a -// GDB RSP packet. A packet represents a single data transfer from one -// RSP endpoint to another excluding all additional encapsulating data -// generated by the session layer. See: -// http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_129.html#SEC134 -// -// The packet object stores the data in a character vector in a cooked format, -// tracking both a read and write position within the stream. An empty -// packet still contains a valid pointer to NULL, so it is always safe to -// get the Payload and use it as a string. In addition packets may be -// sequenced by setting an 8 bit sequence number which helps both sides -// detect when packets have been lost. By default the sequence number is not -// set which is represented as a -1. -// -// This API is not expected to throw unless the underlying vector attempts -// to resize when the system is out of memory, in which case it will throw -// a std::bad_alloc. -#ifndef NATIVE_CLIENT_GDB_RSP_PACKET_H_ -#define NATIVE_CLIENT_GDB_RSP_PACKET_H_ 1 - -#include <string> -#include <vector> - -#include "native_client/src/debug_server/port/std_types.h" - -namespace gdb_rsp { - -class Packet { - typedef void (*StrFunc_t)(void *ctx, const char *str); - - public: - Packet(); - - // Empty the vector and reset the read/write pointers. - void Clear(); - - // Reset the read pointer, allowing the packet to be re-read. - void Rewind(); - - // Return true of the read pointer has reached the write pointer. - bool EndOfPacket() const; - - // Store a single raw 8 bit value - void AddRawChar(char ch); - - // Store a block of data as hex pairs per byte - void AddBlock(const void *ptr, uint32_t len); - - // Store an 8, 16, 32, or 64 bit word as a block without removing preceeding - // zeros. This is used for fixed sized fields. - void AddWord8(uint8_t val); - void AddWord16(uint16_t val); - void AddWord32(uint32_t val); - void AddWord64(uint64_t val); - - // Store a number up to 64 bits, with preceeding zeros removed. Since - // zeros can be removed, the width of this number is unknown, and always - // followed by NUL or a seperator (non hex digit). - void AddNumberSep(uint64_t val, char sep); - - // Add a raw string. This is dangerous since the other side may incorrectly - // interpret certain special characters such as: ":,#$" - void AddString(const char *str); - - // Add a string stored as a stream of ASCII hex digit pairs. It is safe - // to use any character in this stream. If this does not terminate the - // packet, there should be a sperator (non hex digit) immediately following. - void AddHexString(const char *str); - - // Retrieve a single character if available - bool GetRawChar(char *ch); - - // Retreive "len" ASCII character pairs. - bool GetBlock(void *ptr, uint32_t len); - - // Retreive a 8, 16, 32, or 64 bit word as pairs of hex digits. These - // functions will always consume bits/4 characters from the stream. - bool GetWord8(uint8_t *val); - bool GetWord16(uint16_t *val); - bool GetWord32(uint32_t *val); - bool GetWord64(uint64_t *val); - - // Retreive a number and the seperator. If SEP is null, the seperator is - // consumed but thrown away. - bool GetNumberSep(uint64_t *val, char *sep); - - // Get a string from the stream - bool GetString(std::string *str); - bool GetHexString(std::string *str); - - // Callback with the passed in context, and a NUL terminated string. - // These methods provide a means to avoid an extra memcpy. - bool GetStringCB(void *ctx, StrFunc_t cb); - bool GetHexStringCB(void *ctx, StrFunc_t cb); - - // Return a pointer to the entire packet payload - const char *GetPayload() const; - - // Returns true and the sequence number, or false if it is unset. - bool GetSequence(int32_t *seq) const; - - // Set the sequence number. - void SetSequence(int32_t seq); - - private: - int32_t seq_; - std::vector<char> data_; - size_t read_index_; - size_t write_index_; -}; - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_PACKET_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet_test.cc deleted file mode 100644 index c896137..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/packet_test.cc +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <string> -#include <sstream> -#include <vector> - -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/test.h" - -using gdb_rsp::Packet; - -int VerifyPacket(Packet *wr, Packet *rd, void *ctx, PacketFunc_t tx) { - int errs = 0; - char ch; - std::string str; - - uint8_t byte = 0; - uint16_t word16 = 0; - uint32_t word32 = 0; - - // Clear the packet may be reused - wr->Clear(); - - // Verify non alligned writes - wr->AddRawChar('X'); - wr->AddWord16(0x1234); - wr->AddWord32(0x56789ABC); - wr->AddWord8(0xFF); - if (tx) tx(ctx, wr, rd); - rd->GetString(&str); - if (strcmp("X3412bc9a7856ff", str.data())) errs++; - - // Verify rewind - rd->Rewind(); - rd->GetRawChar(&ch); - if (ch != 'X') errs++; - - rd->GetWord16(&word16); - if (word16 != 0x1234) errs++; - - rd->GetWord32(&word32); - if (word32 != 0x56789ABC) errs++; - - rd->GetWord8(&byte); - if (byte != 0xFF) errs++; - - // Check Empty Send - wr->Clear(); - if (tx) tx(ctx, wr, rd); - if (rd->GetRawChar(&ch)) { - errs++; - printf("Was expecting an empty packet\n"); - } - - // Check nibble/byte order - // Check edge cases of 1, 0, -1, -2 - wr->AddNumberSep(0x123, ','); - wr->AddNumberSep(1, ','); - wr->AddNumberSep(0, ','); - wr->AddNumberSep(static_cast<uint64_t>(-1), ','); - wr->AddNumberSep(static_cast<uint64_t>(-2), 0); - if (tx) tx(ctx, wr, rd); - rd->GetString(&str); - if (strcmp("123,1,0,-1,fffffffffffffffe", str.data()) != 0) errs++; - - // We push "compress" which was generated by a real gdbserver, through into - // our packet, then pull it out as a block to decompress, then check against - // the 32b values generated by a real gdb debugger. (Inline golden file) - const char *compress = "0*488c7280038c72800d4c72800030**fd00637702020* 23" - "0*\"2b0*\"2b0*\"2b0*\"530*\"2b0*}00080f83f00c022f8" - "07c022f80f3c80040*&80ff3f0**80ff3f7f030* 30*\"0f*" - " 0* 58050* 85f7196c2b0*\"b0b801010*}0*}0*b801f0* "; - uint32_t vals[16] = { 0, 0, 0, 0x28C788, 0x28C738, 0x28c7d4, 3, 0, 0x776300FD, - 0x202, 0x23, 0x2B, 0x2B, 0x2B, 0x53, 0x2B }; - uint32_t tmp[16]; - - wr->Clear(); - wr->AddString(compress); - if (tx) tx(ctx, wr, rd); - rd->GetBlock(tmp, sizeof(vals)); - if (memcmp(tmp, vals, sizeof(vals))) { - errs++; - printf("Failed to decompress as expected.\n"); - } - - if (errs) - printf("FAILED PACKET TEST\n"); - - return errs; -} - -int TestPacket() { - int errs = 0; - Packet pkt; - - errs += VerifyPacket(&pkt, &pkt, NULL, NULL); - return errs; -} diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.cc deleted file mode 100644 index c90a263..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.cc +++ /dev/null @@ -1,315 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <string.h> -#include <stdlib.h> - -#include <string> -#include <sstream> - -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" - -#include "native_client/src/debug_server/port/mutex.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/transport.h" - -using port::IPlatform; -using port::ITransport; -using port::IMutex; -using port::MutexLock; - -// Use a timeout of 1 second -int const kSessionTimeoutMs = 1000; - -namespace gdb_rsp { - -Session::Session() - : mutex_(NULL), - io_(NULL), - flags_(0), - seq_(0), - connected_(false) { -} - -Session::~Session() { - if (mutex_) IMutex::Free(mutex_); -} - - -bool Session::Init(port::ITransport *transport) { - if (NULL == transport) return false; - - mutex_ = IMutex::Allocate(); - if (NULL == mutex_) return false; - - connected_ = true; - io_ = transport; - return true; -} - -void Session::SetFlags(uint32_t flags) { - flags_ |= flags; -} - -void Session::ClearFlags(uint32_t flags) { - flags_ &= ~flags; -} - -uint32_t Session::GetFlags() { - return flags_; -} - -bool Session::DataAvailable() { - assert(io_); - - return io_->ReadWaitWithTimeout(kSessionTimeoutMs); -} - -bool Session::Connected() { - return connected_; -} - -bool Session::GetChar(char *ch) { - assert(io_); - - // Attempt to select this IO for reading. - if (DataAvailable() == false) return false; - - int32_t len = io_->Read(ch, 1); - - // If data is "availible" but we can't read, it must be closed. - if (len < 1) { - io_->Disconnect(); - connected_ = false; - return false; - } - - return true; -} - - -bool Session::SendPacket(Packet *pkt) { - MutexLock lock(mutex_); - char ch; - - do { - if (!SendPacketOnly(pkt)) return false; - - // If ACKs are off, we are done. - if (GetFlags() & IGNORE_ACK) break; - - // Otherwise, poll for '+' - if (!GetChar(&ch)) return false; - - // Retry if we didn't get a '+' - } while (ch != '+'); - - return true; -} - - -bool Session::SendPacketOnly(Packet *pkt) { - MutexLock lock(mutex_); - - const char *ptr; - char ch; - std::stringstream outstr; - - char run_xsum = 0; - int32_t seq; - - ptr = pkt->GetPayload(); - - if (!pkt->GetSequence(&seq) && (GetFlags() & USE_SEQ)) { - pkt->SetSequence(seq_++); - } - - // Signal start of response - outstr << '$'; - - // If there is a sequence, send as two nibble 8bit value + ':' - if (pkt->GetSequence(&seq)) { - IntToNibble((seq & 0xFF) >> 4, &ch); - outstr << ch; - run_xsum += ch; - - IntToNibble(seq & 0xF, &ch); - outstr << ch; - run_xsum += ch; - - ch = ':'; - outstr << ch; - run_xsum += ch; - } - - // Send the main payload - int offs = 0; - while ((ch = ptr[offs++]) != 0) { - outstr << ch; - run_xsum += ch; - } - - // Send XSUM as two nible 8bit value preceeded by '#' - outstr << '#'; - IntToNibble((run_xsum >> 4) & 0xF, &ch); - outstr << ch; - IntToNibble(run_xsum & 0xF, &ch); - outstr << ch; - - return SendStream(outstr.str().data()); -} - -// We do not take the mutex here since we already have it -// this function is protected so it can't be called directly. -bool Session::SendStream(const char *out) { - int32_t len = static_cast<int32_t>(strlen(out)); - int32_t sent = 0; - - assert(io_); - - while (sent < len) { - const char *cur = &out[sent]; - int32_t tx = io_->Write(cur, len - sent); - - if (tx <= 0) { - IPlatform::LogWarning("Send of %d bytes : '%s' failed.\n", len, out); - io_->Disconnect(); - connected_ = false; - return false; - } - - sent += tx; - } - - if (GetFlags() & DEBUG_SEND) IPlatform::LogInfo("TX %s\n", out); - return true; -} - - -// Attempt to receive a packet -bool Session::GetPacket(Packet *pkt) { - assert(io_); - - MutexLock lock(mutex_); - - char run_xsum, fin_xsum, ch; - std::string in; - int has_seq, offs; - - // If nothing is waiting, return false - if (!io_->ReadWaitWithTimeout(kSessionTimeoutMs)) return false; - - // Toss characters until we see a start of command - do { - if (!GetChar(&ch)) return false; - in += ch; - } while (ch != '$'); - - retry: - has_seq = 1; - offs = 0; - - // If nothing is waiting, return NONE - if (!io_->ReadWaitWithTimeout(kSessionTimeoutMs)) return false; - - // Clear the stream - pkt->Clear(); - - // Prepare XSUM calc - run_xsum = 0; - fin_xsum = 0; - - // Stream in the characters - while (1) { - if (!GetChar(&ch)) return false; - - in += ch; - // Check SEQ statemachine xx: - switch (offs) { - case 0: - case 1: - if (!NibbleToInt(ch, 0)) has_seq = 0; - break; - - case 2: - if (ch != ':') has_seq = 0; - break; - } - offs++; - - // If we see a '#' we must be done with the data - if (ch == '#') break; - - // If we see a '$' we must have missed the last cmd - if (ch == '$') { - IPlatform::LogInfo("RX Missing $, retry.\n"); - goto retry; - } - // Keep a running XSUM - run_xsum += ch; - pkt->AddRawChar(ch); - } - - - // Get two Nibble XSUM - if (!GetChar(&ch)) return false; - in += ch; - - int val; - NibbleToInt(ch, & val); - fin_xsum = val << 4; - - if (!GetChar(&ch)) return false; - in += ch; - NibbleToInt(ch, &val); - fin_xsum |= val; - - if (GetFlags() & DEBUG_RECV) IPlatform::LogInfo("RX %s\n", in.data()); - - // Pull off teh sequence number if we have one - if (has_seq) { - uint8_t seq; - char ch; - - pkt->GetWord8(&seq); - pkt->SetSequence(seq); - pkt->GetRawChar(&ch); - if (ch != ':') { - IPlatform::LogError("RX mismatched SEQ.\n"); - return false; - } - } - - // If ACKs are off, we are done. - if (GetFlags() & IGNORE_ACK) return true; - - // If the XSUMs don't match, signal bad packet - if (fin_xsum == run_xsum) { - char out[4] = { '+', 0, 0, 0}; - int32_t seq; - - // If we have a sequence number - if (pkt->GetSequence(&seq)) { - // Respond with Sequence number - IntToNibble(seq >> 4, &out[1]); - IntToNibble(seq & 0xF, &out[2]); - } - return SendStream(out); - } else { - // Resend a bad XSUM and look for retransmit - SendStream("-"); - - IPlatform::LogInfo("RX Bad XSUM, retry\n"); - goto retry; - } - - return true; -} - -} // End of namespace gdb_rsp - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.h deleted file mode 100644 index ebd5c6f..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session.h +++ /dev/null @@ -1,85 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module provides interfaces for writing to and reading from a -// GDB RSP connection. The connection uses a generic transport -// object for sending packets from one endpoint to another. The session -// is responsible to delievery including generation of checksums and -// retransmits and handling timeouts as needed. See: -// http:// ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_129.html#SEC134 -// -// All data is read one character at a time through 'GetChar' which will -// poll on DataAvail and timeout after one second, allowing the session -// to handle blocking transports. -// -// The session object is not reentrant, and will have unpredictable -// results if two threads attempt to read from the session at the same -// time. -// -// This module may throw a std::bad_alloc if there is an error while trying -// to resize the packet. In addition, the underlying ITransport is free -// to throw an exception if the connection is lost, which will pass out -// of any packet send or receive function. -#ifndef NATIVE_CLIENT_GDB_RSP_SESSION_H_ -#define NATIVE_CLIENT_GDB_RSP_SESSION_H_ 1 - -#include <sstream> - -#include "native_client/src/debug_server/port/std_types.h" -#include "native_client/src/debug_server/port/mutex.h" -#include "native_client/src/debug_server/port/transport.h" - -namespace gdb_rsp { - -class Packet; - -// Session is not inteded to be derived from, protected members are -// protected only for unit testing purposes. -class Session { - public: - Session(); - virtual ~Session(); - - enum { - IGNORE_ACK = 1, // Do not emit or wait for '+' from RSP stream. - USE_SEQ = 2, // Automatically use a sequence number - DEBUG_SEND = 4, // Log all SENDs - DEBUG_RECV = 8, // Log all RECVs - DEBUG_MASK = (DEBUG_SEND | DEBUG_RECV) - }; - - public: - virtual bool Init(port::ITransport *transport); - virtual void SetFlags(uint32_t flags); - virtual void ClearFlags(uint32_t flags); - virtual uint32_t GetFlags(); - - virtual bool SendPacketOnly(Packet *packet); - virtual bool SendPacket(Packet *packet); - virtual bool GetPacket(Packet *packet); - virtual bool DataAvailable(); - virtual bool Connected(); - - protected: - virtual bool GetChar(char *ch); - virtual bool SendStream(const char *str); - - private: - Session(const Session&); - Session &operator=(const Session&); - - protected: - port::IMutex *mutex_; // Lock to enforce correct response order. - port::ITransport *io_; // Transport object not owned by the Session. - uint32_t flags_; // Session flags for Sequence/Ack generation. - uint8_t seq_; // Next sequence number to use or -1. - bool connected_; // Is the connection still valid. -}; - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_SESSION_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.cc deleted file mode 100644 index 58b38a09..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.cc +++ /dev/null @@ -1,191 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#include <string> -#include <sstream> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/session_mock.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/thread.h" -#include "native_client/src/debug_server/port/transport.h" - -#ifdef WIN32 -#define snprintf _snprintf -#endif - -namespace gdb_rsp { - -SessionMock::SessionMock(bool target) : Session() { - target_ = target; - cur_ = 0; - - Session::Init(new TransportMock); - SetFlags(IGNORE_ACK); -} - -SessionMock::~SessionMock() { - for (size_t a = 0; a < actions_.size(); a++) - delete actions_[a]; - - delete static_cast<TransportMock*>(io_); -} - -bool SessionMock::SendPacketOnly(gdb_rsp::Packet *packet) { - if (PeekAction() == SEND) { - Action *pact = GetAction(); - const char *str = packet->GetPayload(); - - if (GetFlags() & DEBUG_SEND) port::IPlatform::LogInfo("TX %s\n", str); - - // Check if we match - if (pact->str_ == str) return true; - - port::IPlatform::LogInfo("Mismatch:\n\tSENDING: %s\n\tEXPECT: %s\n", - str, pact->str_.data()); - } - return false; -} - -bool SessionMock::GetPacket(gdb_rsp::Packet *packet) { - if (PeekAction() == RECV) { - Action *pact = GetAction(); - packet->Clear(); - packet->AddString(pact->str_.data()); - if (GetFlags() & DEBUG_RECV) { - port::IPlatform::LogInfo("RX %s\n", pact->str_.data()); - } - return true; - } - return false; -} - -bool SessionMock::DataAvailable() { - return PeekAction() == RECV; -} - -SessionMock::ActionType SessionMock::PeekAction() { - if (cur_ < actions_.size()) { - Action* pact = actions_[cur_]; - ActionType at = pact->type_; - if (DISCONNECT == at) { - connected_ = false; - } - return at; - } - return TIMEOUT; -} - -SessionMock::Action* SessionMock::GetAction() { - if (cur_ < actions_.size()) return actions_[cur_++]; - return NULL; -} - -void SessionMock::AddAction(ActionType act, const char *str) { - Action *pact = new Action; - - pact->type_ = act; - pact->str_ = str; - actions_.push_back(pact); -} - -void SessionMock::AddTransaction(const char *snd, const char *rcv) { - if (target_) { - // If we are a target, we get a command, then respond - AddAction(RECV, snd); - AddAction(SEND, rcv); - } else { - // If we are a host, we send a command, and expect a reply - AddAction(SEND, snd); - AddAction(RECV, rcv); - } -} - -void AddMockInit(SessionMock* ses) { - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - - // Setup supported query - ses->AddTransaction( - "qSupported", - "PacketSize=7cf;qXfer:libraries:read+;qXfer:features:read+"); - - // Setup arch query - std::string str = "l<target><architecture>"; - str += abi->GetName(); - str += "</architecture></target>"; - ses->AddTransaction( - "qXfer:features:read:target.xml:0,7cf", - str.data()); -} - -void AddMockUpdate(SessionMock* ses, uint8_t sig) { - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - - // Setup thread query - ses->AddTransaction( - "qfThreadInfo", - "m1234"); - ses->AddTransaction( - "qsThreadInfo", - "l"); - ses->AddTransaction( - "Hg1234", - "OK"); - - // Setup Register Query - std::string str = ""; - port::IThread *thread = port::IThread::Acquire(0x1234, true); - for (uint32_t a = 0; a < abi->GetRegisterCount(); a++) { - char tmp[8]; - const Abi::RegDef* def = abi->GetRegisterDef(a); - uint64_t val = static_cast<uint64_t>(a); - uint8_t *pval = reinterpret_cast<uint8_t*>(&val); - - // Create a hex version of the register number of - // the specified zero padded to the correct size - for (uint32_t b = 0; b < def->bytes_; b++) { - snprintf(tmp, sizeof(tmp), "%02x", pval[b]); - str += tmp; - } - - thread->SetRegister(a, &val, def->bytes_); - } - ses->AddTransaction("g", str.data()); - - char tmp[8]; - snprintf(tmp, sizeof(tmp), "S%02x", sig); - ses->AddTransaction("?", tmp); -} - -// GetGoldenSessionMock -// -// The function bellow generates a mock session and preloads it -// with expected inputs and outputs for a common connection case. -// For GDB, that's: -// 1) qSupported - Querry for supported features -// 2) qXfer:features:read:target.xml:0,7cf - Query for target arch. -// 3) qfThreadInfo/qsThreadInfo - Query for active threads -// 4) Hg1234 - Set current register context to retreived thread id -// 5) g - Get current thread registers -// 6) disconnect -SessionMock *GetGoldenSessionMock(bool target, bool debug) { - SessionMock *ses = new SessionMock(target); - - if (debug) ses->SetFlags(Session::DEBUG_RECV | Session::DEBUG_SEND); - - AddMockInit(ses); - AddMockUpdate(ses, 5); - - ses->AddAction(SessionMock::DISCONNECT, ""); - return ses; -} - -} // namespace gdb_rsp diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.h deleted file mode 100644 index f59297b..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_mock.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ -#ifndef NATIVE_CLIENT_GDB_RSP_SESSION_MOCK_H_ -#define NATIVE_CLIENT_GDB_RSP_SESSION_MOCK_H_ 1 - -#include <string> -#include <vector> - -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/transport.h" - -namespace gdb_rsp { - -class SessionMock : public Session { - public: - enum ActionType { - SEND, - RECV, - TIMEOUT, - DISCONNECT - }; - - struct Action { - std::string str_; - ActionType type_; - }; - - class TransportMock : public port::ITransport { - public: - virtual int32_t Read(void *ptr, int32_t len) { - (void) ptr; - (void) len; - return -1; - } - virtual int32_t Write(const void *ptr, int32_t len) { - (void) ptr; - (void) len; - return -1; - } - virtual bool ReadWaitWithTimeout(uint32_t ms) { - (void) ms; - return false; - } - virtual void Disconnect() { } - }; - - explicit SessionMock(bool target); - ~SessionMock(); - - bool SendPacketOnly(gdb_rsp::Packet *packet); - bool GetPacket(gdb_rsp::Packet *packet); - bool DataAvailable(); - ActionType PeekAction(); - Action *GetAction(); - - void AddAction(ActionType act, const char *str); - void AddTransaction(const char *snd, const char *rcv); - - private: - std::vector<Action*> actions_; - size_t cur_; - bool target_; -}; - -SessionMock *GetGoldenSessionMock(bool target, bool debug); -void AddMockInit(SessionMock *ses); -void AddMockUpdate(SessionMock *ses, uint8_t sig); - - - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_SESSION_MOCK_H_ diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_test.cc deleted file mode 100644 index 3dfb98f..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/session_test.cc +++ /dev/null @@ -1,284 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <string> -#include <sstream> - -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/test.h" -#include "native_client/src/debug_server/port/platform.h" - -using gdb_rsp::Session; -using gdb_rsp::Packet; - -// Transport simulation class, this stores data and a r/w index -// to simulate one direction of a pipe, or a pipe to self. -class SharedVector { - public: - SharedVector() : rd(0), wr(0) {} - - public: - std::vector<char> data; - volatile uint32_t rd; - volatile uint32_t wr; -}; - -// Simulates a transport (such as a socket), the reports "ready" -// when polled, but fails on TX/RX. -class DCSocketTransport : public port::ITransport { - public: - virtual int32_t Read(void *ptr, int32_t len) { - (void) ptr; - (void) len; - return -1; - } - - virtual int32_t Write(const void *ptr, int32_t len) { - (void) ptr; - (void) len; - return -1; - } - - virtual bool ReadWaitWithTimeout(uint32_t ms) { - (void) ms; - return true; - } - - virtual void Disconnect() {} - virtual bool DataAvail() { return true; } -}; - - -// Simulate a transport transmitting data Q'd in TX and verifying that -// inbound data matches expected "golden" string. -class GoldenTransport : public port::ITransport { - public: - GoldenTransport(const char *rx, const char *tx, int cnt) { - rx_ = rx; - tx_ = tx; - cnt_ = cnt; - txCnt_ = 0; - rxCnt_ = 0; - errs_ = 0; - disconnected_ = false; - } - - virtual int32_t Read(void *ptr, int32_t len) { - if (disconnected_) return -1; - memcpy(ptr, &rx_[rxCnt_], len); - rxCnt_ += len; - if (static_cast<int>(strlen(rx_)) < rxCnt_) { - printf("End of RX\n"); - errs_++; - } - return len; - } - - // Read from this link, return a negative value if there is an error - virtual int32_t Write(const void *ptr, int32_t len) { - const char *str = reinterpret_cast<const char *>(ptr); - if (disconnected_) return -1; - if (strncmp(str, &tx_[txCnt_], len) != 0) { - printf("TX mismatch in %s vs %s.\n", str, &tx_[txCnt_]); - errs_++; - } - txCnt_ += len; - return len; - } - - virtual bool ReadWaitWithTimeout(uint32_t ms) { - if (disconnected_) return true; - - for (int loop = 0; loop < 8; loop++) { - if (DataAvail()) return true; - port::IPlatform::Relinquish(ms >> 3); - } - return false; - } - - virtual void Disconnect() { - disconnected_ = true; - } - - virtual bool DataAvail() { - return rxCnt_ < static_cast<int>(strlen(rx_)); - } - - int errs() { return errs_; } - - - protected: - const char *rx_; - const char *tx_; - int cnt_; - int rxCnt_; - int txCnt_; - int errs_; - bool disconnected_; -}; - - -class TestTransport : public port::ITransport { - public: - TestTransport(SharedVector *rvec, SharedVector *wvec) { - rvector_ = rvec; - wvector_ = wvec; - disconnected_ = false; - } - - virtual int32_t Read(void *ptr, int32_t len) { - if (disconnected_) return -1; - DataAvail(); - - int max = rvector_->wr - rvector_->rd; - if (max > len) - max = len; - - if (max > 0) { - char *src = &rvector_->data[rvector_->rd]; - memcpy(ptr, src, max); - } - rvector_->rd += max; - return max; - } - - virtual int32_t Write(const void *ptr, int32_t len) { - if (disconnected_) return -1; - - wvector_->data.resize(wvector_->wr + len); - memcpy(&wvector_->data[wvector_->wr], ptr, len); - wvector_->wr += len; - return len; - } - - virtual bool ReadWaitWithTimeout(uint32_t ms) { - if (disconnected_) return true; - - for (int loop = 0; loop < 8; loop++) { - if (DataAvail()) return true; - port::IPlatform::Relinquish(ms >> 3); - } - return false; - } - - virtual void Disconnect() { - disconnected_ = true; - } - - // Return true if vec->data is availible ( - virtual bool DataAvail() { - return (rvector_->rd < rvector_->wr); - } - - protected: - SharedVector *rvector_; - SharedVector *wvector_; - bool disconnected_; -}; - - -int TestSession() { - int errs = 0; - Packet pktOut; - Packet pktIn; - SharedVector vec; - - // Create a "loopback" session by using the same - // FIFO for ingress and egress. - Session cli; - Session srv; - - if (cli.Init(NULL)) { - printf("Initializing with NULL did not fail.\n"); - errs++; - } - - cli.Init(new TestTransport(&vec, &vec)); - srv.Init(new TestTransport(&vec, &vec)); - - // Check, Set,Clear,Get flags. - cli.ClearFlags(static_cast<uint32_t>(-1)); - cli.SetFlags(Session::IGNORE_ACK | Session::DEBUG_RECV); - if (cli.GetFlags() != (Session::IGNORE_ACK + Session::DEBUG_RECV)) { - printf("SetFlag failed.\n"); - errs++; - } - cli.ClearFlags(Session::IGNORE_ACK | Session::DEBUG_SEND); - if (cli.GetFlags() != Session::DEBUG_RECV) { - printf("ClearFlag failed.\n"); - errs++; - } - - // Check Send Packet of known value. - const char *str = "1234"; - - pktOut.AddString(str); - cli.SendPacketOnly(&pktOut); - srv.GetPacket(&pktIn); - std::string out; - pktIn.GetString(&out); - if (out != str) { - printf("Send Only failed.\n"); - errs++; - } - - // Check send against golden transactions - const char tx[] = { "$1234#ca+" }; - const char rx[] = { "+$OK#9a" }; - GoldenTransport gold(rx, tx, 2); - Session uni; - uni.Init(&gold); - - pktOut.Clear(); - pktOut.AddString(str); - if (!uni.SendPacket(&pktOut)) { - printf("Send failed.\n"); - errs++; - } - if (!uni.GetPacket(&pktIn)) { - printf("Get failed.\n"); - errs++; - } - pktIn.GetString(&out); - if (out != "OK") { - printf("Send/Get failed.\n"); - errs++; - } - - // Check that a closed Transport reports to session - if (!uni.Connected()) { - printf("Expecting uni to be connected.\n"); - errs++; - } - gold.Disconnect(); - uni.GetPacket(&pktIn); - if (uni.Connected()) { - printf("Expecting uni to be disconnected.\n"); - errs++; - } - - // Check that a failed read/write reports DC - DCSocketTransport dctrans; - Session dctest; - dctest.Init(&dctrans); - if (!dctest.Connected()) { - printf("Expecting dctest to be connected.\n"); - errs++; - } - dctest.GetPacket(&pktIn); - if (dctest.Connected()) { - printf("Expecting dctest to be disconnected.\n"); - errs++; - } - - errs += gold.errs(); - return errs; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.cc deleted file mode 100644 index 7a1babe..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.cc +++ /dev/null @@ -1,635 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <string.h> -#include <stdlib.h> -#include <stdio.h> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/target.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" - -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/thread.h" - -#ifdef WIN32 -#define snprintf sprintf_s -#endif - -using std::string; - -using port::IEvent; -using port::IMutex; -using port::IPlatform; -using port::IThread; -using port::MutexLock; - -namespace gdb_rsp { - - -Target::Target(const Abi* abi) - : abi_(abi), - mutex_(NULL), - sig_start_(NULL), - sig_done_(NULL), - send_done_(false), - ctx_(NULL), - cur_signal_(-1), - sig_thread_(0), - run_thread_(-1), - reg_thread_(-1) { - if (NULL == abi_) abi_ = Abi::Get(); -} - -Target::~Target() { - Destroy(); -} - -bool Target::Init() { - string targ_xml = "l<target><architecture>"; - - targ_xml += abi_->GetName(); - targ_xml += "</architecture></target>"; - - // Set a more specific result which won't change. - properties_["target.xml"] = targ_xml; - properties_["Supported"] = - "PacketSize=7cf;qXfer:libraries:read+;qXfer:features:read+"; - - mutex_ = IMutex::Allocate(); - sig_start_ = IEvent::Allocate(); - sig_done_ = IEvent::Allocate(); - ctx_ = new uint8_t[abi_->GetContextSize()]; - - if ((NULL == mutex_) || (NULL == sig_start_) || (NULL == sig_done_) - || (NULL == ctx_)) { - Destroy(); - return false; - } - - // Allow one exception to happen - sig_start_->Signal(); - return true; -} - -void Target::Destroy() { - if (mutex_) IMutex::Free(mutex_); - if (sig_start_) IEvent::Free(sig_start_); - if (sig_done_) IEvent::Free(sig_done_); - - delete[] ctx_; -} - -bool Target::AddTemporaryBreakpoint(uint64_t address) { - const Abi::BPDef *bp = abi_->GetBreakpointDef(); - - // If this ABI does not support breakpoints then fail - if (NULL == bp) return false; - - // If we alreay have a breakpoint here then don't add it - BreakMap_t::iterator itr = breakMap_.find(address); - if (itr != breakMap_.end()) return false; - - uint8_t *data = new uint8_t[bp->size_]; - if (NULL == data) return false; - - // Copy the old code from here - if (IPlatform::GetMemory(address, bp->size_, data) == false) { - delete[] data; - return false; - } - if (IPlatform::SetMemory(address, bp->size_, bp->code_) == false) { - delete[] data; - return false; - } - - breakMap_[address] = data; - return true; -} - -bool Target::RemoveTemporaryBreakpoints() { - const Abi::BPDef *bp = abi_->GetBreakpointDef(); - - // Iterate through the map, removing breakpoints - while (!breakMap_.empty()) { - // Copy the key/value locally - BreakMap_t::iterator cur = breakMap_.begin(); - uint64_t addr = cur->first; - uint8_t *data = cur->second; - - // Then remove it from the map - breakMap_.erase(cur); - - // Copy back the old code, and free the data - IPlatform::SetMemory(addr, bp->size_, data); - delete[] data; - } - - return true; -} - - - -void Target::Signal(uint32_t id, int8_t sig, bool wait) { - // Wait for this signal's turn in the signal Q. - sig_start_->Wait(); - { - // Now lock the target, sleeping all active threads - MutexLock lock(mutex_); - - // Suspend all threads except this one - uint32_t curId; - bool more = GetFirstThreadId(&curId); - while (more) { - if (curId != id) { - IThread *thread = threads_[curId]; - thread->Suspend(); - } - more = GetNextThreadId(&curId); - } - - // Signal the stub (Run thread) that we are ready to process - // a trap, by updating the signal information and releasing - // the lock. - reg_thread_ = id; - run_thread_ = id; - cur_signal_ = sig; - } - - // Wait for permission to continue - if (wait) sig_done_->Wait(); -} - -void Target::Run(Session *ses) { - bool first = true; - do { - // Give everyone else a chance to use the lock - IPlatform::Relinquish(100); - - // Lock to prevent anyone else from modifying threads - // or updating the signal information. - MutexLock lock(mutex_); - Packet recv, reply; - - uint32_t id = 0; - - // If no signal is waiting for this iteration... - if (-1 == cur_signal_) { - // but the debugger is talking to us then force a break - if (ses->DataAvailable()) { - // set signal to 0 to signify paused - cur_signal_ = 0; - - // put all the threads to sleep. - uint32_t curId; - bool more = GetFirstThreadId(&curId); - while (more) { - if (curId != id) { - IThread *thread = threads_[curId]; - thread->Suspend(); - } - more = GetNextThreadId(&curId); - } - } else { - // otherwise, nothing to do so try again. - continue; - } - } else { - // otherwise there really is an exception so get the id of the thread - id = GetRegThreadId(); - } - - // If we got this far, then there is some kind of signal. - // So first, remove the breakpoints - RemoveTemporaryBreakpoints(); - - // Next update the current thread info - char tmp[16]; - snprintf(tmp, sizeof(tmp), "QC%x", id); - properties_["C"] = tmp; - - if (first) { - // First time on a connection, we don't sent the signal - first = false; - } else { - // All other times, send the signal that triggered us - Packet pktOut; - pktOut.AddRawChar('S'); - pktOut.AddWord8(cur_signal_); - ses->SendPacketOnly(&pktOut); - } - - // Now we are ready to process commands - // Loop through packets until we process a continue - // packet. - do { - if (ses->GetPacket(&recv)) { - reply.Clear(); - if (ProcessPacket(&recv, &reply)) { - // If this is a continue command, break out of this loop - break; - } else { - // Othwerise send the reponse - ses->SendPacket(&reply); - } - } - } while (ses->Connected()); - - - // Now that we are done, we want to continue in the "correct order". - // This means letting the active thread go first, in case we are single - // stepping and want to catch it again. This is a desired behavior but - // it is not guaranteed since another thread may already be in an - // exception state and next in line to notify the target. - - // If the run thread is not the exception thread, wake it up now. - uint32_t run_thread = GetRunThreadId(); - if (run_thread != id - && run_thread != static_cast<uint32_t>(-1)) { - IThread* thread = threads_[run_thread]; - thread->Resume(); - } - - // Next, wake up the exception thread, if there is one and it needs - // to wake up. - if (id && send_done_) sig_done_->Signal(); - - // Now wake up everyone else - uint32_t curId; - bool more = GetFirstThreadId(&curId); - while (more) { - if ((curId != id) && (curId != GetRunThreadId())) { - IThread *thread = threads_[curId]; - thread->Resume(); - } - more = GetNextThreadId(&curId); - } - - // Reset the signal value - cur_signal_ = -1; - - // If we took an exception, let the handler resume and allow - // the next exception to come in. - if (cur_signal_) { - sig_done_->Signal(); - sig_start_->Signal(); - } - - // Continue running until the connection is lost. - } while (ses->Connected()); -} - - - - -bool Target::GetFirstThreadId(uint32_t *id) { - threadItr_ = threads_.begin(); - return GetNextThreadId(id); -} - -bool Target::GetNextThreadId(uint32_t *id) { - if (threadItr_ == threads_.end()) return false; - - *id = (*threadItr_).first; - threadItr_++; - - return true; -} - - - -bool Target::ProcessPacket(Packet* pktIn, Packet* pktOut) { - char cmd; - int32_t seq = -1; - ErrDef err = NONE; - - // Clear the outbound message - pktOut->Clear(); - - // Pull out the sequence. - pktIn->GetSequence(&seq); - if (seq != -1) pktOut->SetSequence(seq); - - // Find the command - pktIn->GetRawChar(&cmd); - - switch (cmd) { - // IN : $? - // OUT: $Sxx - case '?': - pktOut->AddRawChar('S'); - pktOut->AddWord8(cur_signal_); - break; - - // IN : $d - // OUT: -NONE- - case 'd': - Detach(); - break; - - // IN : $g - // OUT: $xx...xx - case 'g': { - uint32_t id = GetRegThreadId(); - if (0 == id) { - err = BAD_ARGS; - break; - } - - IThread *thread = GetThread(id); - if (NULL == thread) { - err = BAD_ARGS; - break; - } - - // Copy OS preserved registers to GDB payload - for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { - const Abi::RegDef *def = abi_->GetRegisterDef(a); - thread->GetRegister(a, &ctx_[def->offset_], def->bytes_); - } - - pktOut->AddBlock(ctx_, abi_->GetContextSize()); - break; - } - - // IN : $Gxx..xx - // OUT: $OK - case 'G': { - uint32_t id = GetRegThreadId(); - if (0 == id) { - err = BAD_ARGS; - break; - } - - IThread *thread = threads_[id]; - if (NULL == thread) { - err = BAD_ARGS; - break; - } - - // GDB payload to OS registers - for (uint32_t a = 0; a < abi_->GetRegisterCount(); a++) { - const Abi::RegDef *def = abi_->GetRegisterDef(a); - thread->SetRegister(a, &ctx_[def->offset_], def->bytes_); - } - pktOut->AddBlock(ctx_, abi_->GetContextSize()); - break; - } - - // IN : $H(c/g)(-1,0,xxxx) - // OUT: $OK - case 'H': { - char type; - uint64_t id; - - if (!pktIn->GetRawChar(&type)) { - err = BAD_FORMAT; - break; - } - if (!pktIn->GetNumberSep(&id, 0)) { - err = BAD_FORMAT; - break; - } - - if (threads_.begin() == threads_.end()) { - err = BAD_ARGS; - break; - } - - // If we are using "any" get the first thread - if (id == static_cast<uint64_t>(-1)) id = threads_.begin()->first; - - // Verify that we have the thread - if (threads_.find(static_cast<uint32_t>(id)) == threads_.end()) { - err = BAD_ARGS; - break; - } - - pktOut->AddString("OK"); - switch (type) { - case 'g': - reg_thread_ = static_cast<uint32_t>(id); - break; - - case 'c': - run_thread_ = static_cast<uint32_t>(id); - break; - - default: - err = BAD_ARGS; - break; - } - break; - } - - // IN : $maaaa,llll - // OUT: $xx..xx - case 'm': { - uint64_t addr; - uint64_t wlen; - uint32_t len; - if (!pktIn->GetNumberSep(&addr, 0)) { - err = BAD_FORMAT; - break; - } - - if (!pktIn->GetNumberSep(&wlen, 0)) { - err = BAD_FORMAT; - break; - } - - len = static_cast<uint32_t>(wlen); - uint8_t *block = new uint8_t[len]; - if (!port::IPlatform::GetMemory(addr, len, block)) err = FAILED; - - pktOut->AddBlock(block, len); - break; - } - - // IN : $Maaaa,llll:xx..xx - // OUT: $OK - case 'M': { - uint64_t addr; - uint64_t wlen; - uint32_t len; - - if (!pktIn->GetNumberSep(&addr, 0)) { - err = BAD_FORMAT; - break; - } - if (!pktIn->GetNumberSep(&wlen, 0)) { - err = BAD_FORMAT; - break; - } - - len = static_cast<uint32_t>(wlen); - uint8_t *block = new uint8_t[len]; - pktIn->GetBlock(block, len); - - if (!port::IPlatform::SetMemory(addr, len, block)) err = FAILED; - - pktOut->AddString("OK"); - break; - } - - case 'q': { - string tmp; - const char *str = &pktIn->GetPayload()[1]; - stringvec toks = StringSplit(str, ":;"); - PropertyMap_t::const_iterator itr = properties_.find(toks[0]); - - // If this is a thread query - if (!strcmp(str, "fThreadInfo") || !strcmp(str, "sThreadInfo")) { - uint32_t curr; - bool more = false; - if (str[0] == 'f') { - more = GetFirstThreadId(&curr); - } else { - more = GetNextThreadId(&curr); - } - - if (!more) { - pktOut->AddString("l"); - } else { - pktOut->AddString("m"); - pktOut->AddNumberSep(curr, 0); - } - break; - } - - // Check for architecture query - tmp = "Xfer:features:read:target.xml"; - if (!strncmp(str, tmp.data(), tmp.length())) { - stringvec args = StringSplit(&str[tmp.length()+1], ","); - if (args.size() != 2) break; - - const char *out = properties_["target.xml"].data(); - int offs = strtol(args[0].data(), NULL, 16); - int max = strtol(args[1].data(), NULL, 16) + offs; - int len = static_cast<int>(strlen(out)); - - if (max >= len) max = len; - - while (offs < max) { - pktOut->AddRawChar(out[offs]); - offs++; - } - break; - } - - // Check the property cache - if (itr != properties_.end()) { - pktOut->AddString(itr->second.data()); - } - break; - } - - case 'T': { - uint64_t id; - if (!pktIn->GetNumberSep(&id, 0)) { - err = BAD_FORMAT; - break; - } - - if (GetThread(static_cast<uint32_t>(id)) == NULL) { - err = BAD_ARGS; - break; - } - - pktOut->AddString("OK"); - break; - } - - case 's': { - IThread *thread = GetThread(GetRunThreadId()); - if (thread) thread->SetStep(true); - return true; - } - - case 'c': - return true; - - default: { - // If the command is not recognzied, ignore it by sending an - // empty reply. - string str; - pktIn->GetString(&str); - port::IPlatform::LogError("Unknown command: %s", str.data()); - return false; - } - } - - // If there is an error, return the error code instead of a payload - if (err) { - pktOut->Clear(); - pktOut->AddRawChar('E'); - pktOut->AddWord8(err); - } - return false; -} - - -void Target::TrackThread(IThread* thread) { - uint32_t id = thread->GetId(); - mutex_->Lock(); - threads_[id] = thread; - mutex_->Unlock(); -} - -void Target::IgnoreThread(IThread* thread) { - uint32_t id = thread->GetId(); - mutex_->Lock(); - ThreadMap_t::iterator itr = threads_.find(id); - - if (itr != threads_.end()) threads_.erase(itr); - mutex_->Lock(); -} - - -void Target::Detach() { - port::IPlatform::LogInfo("Requested Detach.\n"); -} - - -uint32_t Target::GetRegThreadId() const { - ThreadMap_t::const_iterator itr; - - switch (reg_thread_) { - // If we wany "any" then try the signal'd thread first - case 0: - case 0xFFFFFFFF: - itr = threads_.begin(); - break; - - default: - itr = threads_.find(reg_thread_); - break; - } - - if (itr == threads_.end()) return 0; - - return itr->first; -} - -uint32_t Target::GetRunThreadId() const { - return run_thread_; -} - -IThread* Target::GetThread(uint32_t id) { - ThreadMap_t::const_iterator itr; - itr = threads_.find(id); - if (itr != threads_.end()) return itr->second; - - return NULL; -} - - -} // namespace gdb_rsp - - - - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.h deleted file mode 100644 index 93f434d..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target.h +++ /dev/null @@ -1,158 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module provides interfaces for accessing the debugging state of -// the target. The target can use either the thread that took the -// exception or run in its own thread. To respond to the host, the -// application must call the run function with a valid Transport -// which will then be polled for commands. The target will return -// from Run when the host disconnects, or requests a continue. -// -// The object is protected by a mutex, so that it is legal to track or -// ignore threads as an exception takes place. -// -// The Run function expects that all threads of interest are stopped -// with the Step flag cleared before Run is called. It is expected that -// and that all threads are updated with thier modified contexts and -// restarted when the target returns from Run. - -#ifndef NATIVE_CLIENT_GDB_RSP_TARGET_H_ -#define NATIVE_CLIENT_GDB_RSP_TARGET_H_ 1 - -#include <map> -#include <string> - -#include "native_client/src/debug_server/gdb_rsp/util.h" - -#include "native_client/src/debug_server/port/event.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/mutex.h" -#include "native_client/src/debug_server/port/thread.h" - -namespace gdb_rsp { - -class Abi; -class Packet; -class Session; - -class Target { - public: - enum ErrDef { - NONE = 0, - BAD_FORMAT = 1, - BAD_ARGS = 2, - FAILED = 3 - }; - - enum State { - UNINIT = 0, - RUNNING = 1, - STOPPED = 2 - }; - - typedef ErrDef (*QFunc_t)(Target *, stringvec&, std::string); - typedef std::map<uint32_t, port::IThread*> ThreadMap_t; - typedef std::map<std::string, std::string> PropertyMap_t; - typedef std::map<uint64_t, uint8_t*> BreakMap_t; - - public: - // Contruct a Target object. By default use the native ABI. - explicit Target(const Abi *abi = NULL); - ~Target(); - - // Init must be the first function called to correctlty - // build the Target internal structures. - bool Init(); - - // Add and remove temporary breakpoints. These breakpoints - // must be added just before we start running, and removed - // just before we stop running to prevent the debugger from - // seeing the modified memory. - bool AddTemporaryBreakpoint(uint64_t address); - bool RemoveTemporaryBreakpoints(); - - // This function should be called by a tracked thread when it takes - // an exception. It takes sig_start_ to prevent other exceptions - // from signalling thread. If wait is true, it will then block on - // sig_done_ until a continue is issued by the host. - void Signal(uint32_t id, int8_t sig, bool wait); - - // This function will spin on a session, until it closes. If an - // exception is caught, it will signal the exception thread by - // setting sig_done_. - void Run(Session *ses); - - // This function causes the target to track the state - // of the specified thread and make it availible to - // a connected host. - void TrackThread(port::IThread *thread); - - // This function causes the target to stop tracking the - // state of the specified thread, which will no longer - // be visible to the host. - void IgnoreThread(port::IThread *thread); - - protected: - // This function always succeedes, since all errors - // are reported as an error string of "E<##>" where - // the two digit number. The error codes are not - // not documented, so this implementation uses - // ErrDef as errors codes. This function returns - // true a request to continue (or step) is processed. - bool ProcessPacket(Packet *pktIn, Packet *pktOut); - - void Destroy(); - void Detach(); - - bool GetFirstThreadId(uint32_t *id); - bool GetNextThreadId(uint32_t *id); - - uint32_t GetRegThreadId() const; - uint32_t GetRunThreadId() const; - port::IThread *GetThread(uint32_t id); - - public: - const Abi *abi_; - - // This mutex protects debugging state (threads_, cur_signal, sig_thread_) - port::IMutex *mutex_; - - // This event is signalled when the target is really to process an - // exception. It ensures only one exception is processed at a time. - port::IEvent *sig_start_; - - // This event is signalled when the target done processing an exception. - port::IEvent *sig_done_; - - // This value is set if the exception cather is requesting a continue signal - bool send_done_; - - ThreadMap_t threads_; - ThreadMap_t::const_iterator threadItr_; - BreakMap_t breakMap_; - - - PropertyMap_t properties_; - - uint8_t *ctx_; // Context Scratchpad - - // The current signal and signaling thread data is protected by - // the mutex, and can only be owned by one thread at a time. - // These values should only be written via the "Signal" member, - // which will ensure that a new signal does not overwrite a - // previous signal. - volatile int8_t cur_signal_; - volatile uint32_t sig_thread_; - - uint32_t run_thread_; // Which thread to issue step commands on - uint32_t reg_thread_; // Which thread to issue context (reg) commands on -}; - - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_TARGET_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target_test.cc deleted file mode 100644 index 44bdc4a..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/target_test.cc +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <assert.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <string> -#include <sstream> -#include <vector> - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/session_mock.h" -#include "native_client/src/debug_server/gdb_rsp/target.h" -#include "native_client/src/debug_server/gdb_rsp/test.h" - -using gdb_rsp::Abi; -using gdb_rsp::SessionMock; -using gdb_rsp::Target; - -int TestTarget() { - int errs = 0; - - SessionMock *ses = gdb_rsp::GetGoldenSessionMock(true, false); - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - - Target *target = new Target(NULL); - if (!target->Init()) { - printf("Failed to INIT target.\n"); - return 1; - } - - // Create a pseudo thread with registers set to their index - port::IThread *thread = port::IThread::Acquire(0x1234, true); - for (uint32_t a = 0; a < abi->GetRegisterCount(); a++) { - const Abi::RegDef* def = abi->GetRegisterDef(a); - uint64_t val = static_cast<uint64_t>(a); - thread->SetRegister(a, &val, def->bytes_); - } - target->TrackThread(thread); - - // Pretend we just got a signal on that thread - target->Signal(thread->GetId(), 5, false); - - // Run the session to completion. - target->Run(ses); - - if (ses->PeekAction() != SessionMock::DISCONNECT) { - printf("We did not consume all the actions.\n"); - errs++; - } - - delete target; - delete ses; - return errs; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.cc deleted file mode 100644 index 0da26e5..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.cc +++ /dev/null @@ -1,151 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdarg.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "native_client/src/debug_server/gdb_rsp/test.h" -#include "native_client/src/debug_server/port/platform.h" - -// Mock portability objects -namespace port { -void IPlatform::Relinquish(uint32_t msec) { - (void) msec; - return; -} - -void IPlatform::LogInfo(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - vprintf(fmt, argptr); -} - -void IPlatform::LogWarning(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - vprintf(fmt, argptr); -} - -void IPlatform::LogError(const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - vprintf(fmt, argptr); -} - -// The unit tests are singly threaded, so we just do nothing -// for synchronization -class MutexMock : public IMutex { - void Lock() {} - void Unlock() {} - bool Try() { return true; } -}; - -IMutex* IMutex::Allocate() { return new MutexMock; } -void IMutex::Free(IMutex* mtx) { delete static_cast<MutexMock*>(mtx); } - -class EventMock : public IEvent { - void Signal() {} - void Wait() {} -}; - -IEvent* IEvent::Allocate() { return new EventMock; } -void IEvent::Free(IEvent* e) { delete static_cast<EventMock*>(e); } - -class ThreadMock : public IThread { - public: - explicit ThreadMock(uint32_t id) { - id_ = id; - ctx_ = new uint8_t[gdb_rsp::Abi::Get()->GetContextSize()]; - } - ~ThreadMock() { delete[] ctx_; } - - uint32_t GetId() { return id_; } - State GetState() { return IThread::SIGNALED; } - - bool SetStep(bool on) { - (void) on; - return true; - } - - bool GetRegister(uint32_t index, void *dst, uint32_t len) { - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index); - memcpy(dst, ctx_ + reg->offset_, len); - return true; - } - - bool SetRegister(uint32_t index, void *src, uint32_t len) { - const gdb_rsp::Abi* abi = gdb_rsp::Abi::Get(); - const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index); - memcpy(ctx_ + reg->offset_, src, len); - return true; - } - - bool Suspend() { return true; } - bool Resume() { return true; } - - virtual void *GetContext() { return ctx_; } - - private: - uint8_t *ctx_; - uint32_t id_; -}; - -IThread* IThread::Acquire(uint32_t id, bool create) { - if (create) return new ThreadMock(id); - return NULL; -} - - -bool port::IPlatform::GetMemory(uint64_t addr, uint32_t len, void *dst) { - intptr_t iptr = static_cast<intptr_t>(addr); - void *src = reinterpret_cast<void*>(iptr); - memcpy(dst, src, len); - return true; -} - -bool port::IPlatform::SetMemory(uint64_t addr, uint32_t len, void *src) { - intptr_t iptr = static_cast<intptr_t>(addr); - void *dst = reinterpret_cast<void*>(iptr); - memcpy(dst, src, len); - return true; -} - - -} // End of namespace port - -int main(int argc, const char *argv[]) { - int errs = 0; - - (void) argc; - (void) argv; - - printf("Testing Utils.\n"); - errs += TestUtil(); - - printf("Testing ABI.\n"); - errs += TestAbi(); - - printf("Testing Packets.\n"); - errs += TestPacket(); - - printf("Testing Session.\n"); - errs += TestSession(); - - printf("Testing Host.\n"); - errs += TestHost(); - - printf("Testing Target.\n"); - errs += TestTarget(); - - if (errs) printf("FAILED with %d errors.\n", errs); - return errs; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.h deleted file mode 100644 index 2f88ac3..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/test.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ -#ifndef NATIVE_CLIENT_GDB_RSP_TEST_H_ -#define NATIVE_CLIENT_GDB_RSP_TEST_H_ 1 - -#include <vector> - -#include "native_client/src/debug_server/port/std_types.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/transport.h" - -#include "native_client/src/debug_server/gdb_rsp/abi.h" -#include "native_client/src/debug_server/gdb_rsp/host.h" -#include "native_client/src/debug_server/gdb_rsp/packet.h" -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/target.h" -#include "native_client/src/debug_server/gdb_rsp/util.h" - -typedef void (*PacketFunc_t)(void *ctx, - gdb_rsp::Packet *wr, - gdb_rsp::Packet *rd); - -int VerifyPacket(gdb_rsp::Packet *wr, gdb_rsp::Packet *rd, - void *ctx, PacketFunc_t tx); - -int TestAbi(); -int TestHost(); -int TestPacket(); -int TestSession(); -int TestTarget(); -int TestUtil(); - -#endif // NATIVE_CLIENT_GDB_RSP_TEST_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.cc deleted file mode 100644 index 6abf238..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.cc +++ /dev/null @@ -1,124 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <stdarg.h> -#include <string.h> - -#include <string> -#include <vector> - -#include "native_client/src/debug_server/gdb_rsp/util.h" -#include "native_client/src/debug_server/port/std_types.h" - -using std::string; - -namespace gdb_rsp { - -bool NibbleToInt(char ch, int *val) { - // Check for nibble of a-f - if ((ch >= 'a') && (ch <= 'f')) { - if (val) *val = (ch - 'a' + 10); - return true; - } - - // Check for nibble of A-F - if ((ch >= 'A') && (ch <= 'F')) { - if (val) *val = (ch - 'A' + 10); - return true; - } - - // Check for nibble of 0-9 - if ((ch >= '0') && (ch <= '9')) { - if (val) *val = (ch - '0'); - return true; - } - - // Not a valid nibble representation - return false; -} - -bool IntToNibble(int nibble, char *ch) { - // Verify this value fits in a nibble - if (nibble != (nibble & 0xF)) return false; - - nibble &= 0xF; - if (nibble < 10) { - if (ch) *ch = '0' + nibble; - } else { - // Although uppercase maybe more readible GDB - // expects lower case values. - if (ch) *ch = 'a' + (nibble - 10); - } - - return true; -} - -bool NibblesToByte(const char *inStr, int *outInt) { - int o1, o2; - - if (NibbleToInt(inStr[0], &o1) && NibbleToInt(inStr[1], &o2)) { - *outInt = (o1 << 4) + o2; - return true; - } - - return false; -} - -#ifdef WIN32 -int snprintf(char *buf, size_t size, const char *fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - - int len = vsnprintf(buf, size, fmt, argptr); - return len; -} -#endif - -stringvec StringSplit(const string &instr, const char *delim) { - int count = 0; - const char *in = instr.data(); - const char *start = in; - - stringvec ovec; - - // Check if we have nothing to do - if (NULL == in) return ovec; - if (NULL == delim) { - ovec.push_back(string(in)); - return ovec; - } - - while (*in) { - int len = 0; - // Toss all preceeding delimiters - while (*in && strchr(delim, *in)) in++; - - // If we still have something to process - if (*in) { - std::string token; - start = in; - len = 0; - // Keep moving forward for all valid chars - while (*in && (strchr(delim, *in) == NULL)) { - len++; - in++; - } - - // Build this token and add it to the array. - ovec.resize(count + 1); - ovec[count].assign(start, len); - count++; - } - } - - return ovec; -} - - - -} // End of namespace gdb_rsp - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.h b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.h deleted file mode 100644 index a2655d7..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef NATIVE_CLIENT_GDB_RSP_UTIL_H_ -#define NATIVE_CLIENT_GDB_RSP_UTIL_H_ 1 - -#include <sstream> -#include <string> -#include <vector> - -#include "native_client/src/debug_server/port/std_types.h" - -namespace gdb_rsp { - -typedef std::vector<std::string> stringvec; - -// Convert from ASCII (0-9,a-f,A-F) to 4b unsigned or return -// false if the input char is unexpected. -bool NibbleToInt(char inChar, int *outInt); - -// Convert from 0-15 to ASCII (0-9,a-f) or return false -// if the input is not a value from 0-15. -bool IntToNibble(int inInt, char *outChar); - -// Convert a pair of nibbles to a value from 0-255 or return -// false if ethier input character is not a valid nibble. -bool NibblesToByte(const char *inStr, int *outInt); - -#ifdef WIN32 -int snprintf(char *str, size_t size, const char *fmt, ...); -#endif - -stringvec StringSplit(const std::string& instr, const char *delim); - -} // namespace gdb_rsp - -#endif // NATIVE_CLIENT_GDB_RSP_UTIL_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util_test.cc b/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util_test.cc deleted file mode 100644 index 7b2ae00..0000000 --- a/native_client_sdk/src/build_tools/debug_server/gdb_rsp/util_test.cc +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <string> - -#include "native_client/src/debug_server/gdb_rsp/util.h" - -using std::string; -using gdb_rsp::NibbleToInt; -using gdb_rsp::IntToNibble; -using gdb_rsp::stringvec; - - -int TestUtil() { - char goodStr[] = "0123456789abcdefABCDEF"; - int good; - int val; - int a; - int errCnt = 0; - - // Make sure we find expected and only expected conversions (0-9,a-f,A-F) - good = 0; - for (a = 0; a < 256; a++) { - // NOTE: Exclude 'zero' since the terminator is found by strchr - bool found = a && (strrchr(goodStr, a) != NULL); - bool xvert = NibbleToInt(static_cast<char>(a), &val); - if (xvert != found) { - printf("FAILED NibbleToInt of '%c'(#%d), convertion %s.\n", - a, a, xvert ? "succeeded" : "failed"); - errCnt++; - } - } - - good = 0; - for (a = -256; a < 256; a++) { - char ch; - bool xvert = IntToNibble(a, &ch); - - if (xvert) { - good++; - if (!NibbleToInt(ch, &val)) { - printf("FAILED IntToNibble on good NibbleToInt of #%d\n.\n", a); - errCnt++; - } - // NOTE: check if IntToNible matches NibbleToInt looking at both - // possitive and negative values of -15 to +15 - if (val != a) { - printf("FAILED IntToNibble != NibbleToInt of #%d\n.\n", a); - errCnt++; - } - } - } - - // Although we check -15 to +15 above, we realy only want -7 to +15 - // to verify unsiged (0-15) plus signed (-7 to -1). - if (good != 16) { - printf("FAILED IntToNibble range of 0 to 15.\n"); - errCnt++; - } - - string xml = "qXfer:features:read:target.xml:0,7ca"; - string str; - stringvec vec, vec2; - - return errCnt; -} - diff --git a/native_client_sdk/src/build_tools/debug_server/nacl_debug.cc b/native_client_sdk/src/build_tools/debug_server/nacl_debug.cc deleted file mode 100644 index 195d25f..0000000 --- a/native_client_sdk/src/build_tools/debug_server/nacl_debug.cc +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -#include <vector> -#include <map> - -/* - * NaCl Functions for intereacting with debuggers - */ - -#include "native_client/src/debug_server/gdb_rsp/session.h" -#include "native_client/src/debug_server/gdb_rsp/target.h" -#include "native_client/src/debug_server/port/platform.h" -#include "native_client/src/debug_server/port/thread.h" - -#include "native_client/src/include/nacl_string.h" -#include "native_client/src/shared/platform/nacl_log.h" -#include "native_client/src/shared/platform/nacl_threads.h" -#include "native_client/src/debug_server/debug_stub/debug_stub.h" -#include "native_client/src/trusted/service_runtime/nacl_app_thread.h" -#include "native_client/src/debug_server/nacl_debug.h" - -#include "native_client/src/trusted/service_runtime/sel_ldr.h" - -using port::IPlatform; -using port::IThread; -using port::ITransport; - -using gdb_rsp::Session; -using gdb_rsp::Target; - -#ifdef WIN32 -/* Disable warning for unwind disabled when exceptions used */ -#pragma warning(disable:4530) -#endif - -/* - * These macro wraps all debugging stub calls to prevent C++ code called - * by the debugging stub to throw and exception past the C API. We use - * this technique to allow the use of STL templates. We catch bad_alloc - * seperately purely to provide information for debugging purposes. - */ -#define DBG_CATCH_ALL \ - catch(std::bad_alloc) { \ - NaClLog(LOG_FATAL, "nacl_debug(%d) : Failed to allocate.\n", __LINE__); \ - exit(-1); \ - } \ - catch(std::exception e) { \ - NaClLog(LOG_FATAL, "nacl_debug(%d) : Caught exception: %s.\n", \ - __LINE__ , e.what()); \ - exit(-1); \ - } \ - catch(...) { \ - NaClLog(LOG_FATAL, "nacl_debug(%d) : Unexpected exception.\n", __LINE__);\ - exit(-1); \ - } - - -enum NaClDebugStatus { - NDS_DISABLED = 0, - NDS_ENABLED = 1, - NDS_STOPPED = 2 -}; - -/* - * Remove name mangling to make it easier to find, incase we want to toggle - * internal stub debugging from an external debugger. - */ -extern "C" { - uint32_t nacl_debug_allowed = 0; -} - -struct NaClDebugState { - NaClDebugState() : target_(NULL), app_(NULL), break_(false), - errCode_(0), status_(NDS_DISABLED) { -#ifdef _DEBUG - /* - * When compiling DEBUG we allow an environment variable to enable - * debugging, otherwise debugging could be allowed on a release - * build by modifying nacl_debug_allowed. - */ - if (NULL != getenv("NACL_DEBUG_ENABLE")) nacl_debug_allowed = 1; -#endif - status_ = nacl_debug_allowed ? NDS_ENABLED : NDS_DISABLED; - - /* Initialize the stub if and only if debugging is enabled. */ - if (status_) { - NaClDebugStubInit(); - target_ = new Target(); - - /* If we failed to initialize the target, turn off debugging */ - if ((NULL == target_) || (!target_->Init())) status_ = NDS_DISABLED; - } - } - - ~NaClDebugState() { - delete target_; - } - - Target* target_; - struct NaClApp *app_; - bool break_; - volatile int errCode_; - NaClDebugStatus status_; - nacl::string path_; - std::vector<const char *> arg_; - std::vector<const char *> env_; -}; - -/* - * NOTE: We use a singleton to delay construction allowing someone - * to enable debugging only before the first use of this object. - */ -static NaClDebugState *NaClDebugGetState() { - static NaClDebugState state; - return &state; -} - -void NaClDebugSetAllow(int enable) throw() { -#ifdef NACL_DEBUG_STUB - nacl_debug_allowed = enable; -#else - UNREFERENCED_PARAMETER(enable); -#endif -} - -void NaClDebugSetStartBroken(int enable) throw() { -#ifdef NACL_DEBUG_STUB - NaClDebugState* state = NaClDebugGetState(); - state->break_ = enable ? true : false; -#else - UNREFERENCED_PARAMETER(enable); -#endif -} - - - -void WINAPI NaClStubThread(void *ptr) { -#ifdef NACL_DEBUG_STUB - uint32_t id = static_cast<uint32_t>(GetCurrentThreadId()); - printf("---> NaClStubThread(void *ptr) thread id = %d == 0x%X\n", id, id); - - Target *targ = reinterpret_cast<Target*>(ptr); - while (1) { - ITransport* trans = NULL; - Session* ses = NULL; - - try { - // Wait for a connection. - printf("---> %d\n", __LINE__); fflush(stdout); - trans = ITransport::Accept("0.0.0.0:4014"); - printf("---> %d\n", __LINE__); fflush(stdout); - if (NULL == trans) continue; - printf("---> %d\n", __LINE__); fflush(stdout); - - // Create a new session for this connection - ses = new Session(); - ses->Init(trans); - ses->SetFlags(Session::DEBUG_MASK); - - // Run this session for as long as it lasts - targ->Run(ses); - } - catch(...) { - printf("---> %d\n", __LINE__); fflush(stdout); - delete ses; - printf("---> %d\n", __LINE__); fflush(stdout); - ITransport::Free(trans); - printf("---> %d\n", __LINE__); fflush(stdout); - } - printf("---> %d\n", __LINE__); fflush(stdout); - } -#else - UNREFERENCED_PARAMETER(ptr); -#endif -} - -void NaClExceptionCatcher(uint32_t id, int8_t sig, void *cookie) { -#ifdef NACL_DEBUG_STUB - Target* targ = static_cast<Target*>(cookie); - - /* Signal the target that we caught something */ - IPlatform::LogWarning("Caught signal %d on thread %Xh.\n", sig, id); - targ->Signal(id, sig, true); -#else - UNREFERENCED_PARAMETER(id); - UNREFERENCED_PARAMETER(sig); - UNREFERENCED_PARAMETER(cookie); -#endif -} - - -int NaClDebugIsEnabled(void) throw() { -#ifdef NACL_DEBUG_STUB - try { - return (NDS_ENABLED == NaClDebugGetState()->status_) ? 1 : 0; - } DBG_CATCH_ALL -#endif - - return false; -} - -void NaClDebugSetAppPath(const char *path) throw() { - try { - if (NaClDebugIsEnabled()) NaClDebugGetState()->path_ = path; - } DBG_CATCH_ALL -} - - -void NaClDebugSetAppInfo(struct NaClApp *app) throw() { -#ifdef NACL_DEBUG_STUB - if (NaClDebugIsEnabled()) { - NaClDebugState *state = NaClDebugGetState(); - state->app_ = app; - } -#else - UNREFERENCED_PARAMETER(app); -#endif -} - - -void NaClDebugSetAppEnvironment(int argc, char const * const argv[], - int envc, char const * const envv[]) throw() { - if (NaClDebugIsEnabled()) { - int a; - try { - /* - * Copy the pointer arrays. We use ptrs instead of strings - * since the data persits and it prevents an extra copy. - */ - NaClDebugGetState()->arg_.resize(argc); - for (a = 0; a < argc; a++) NaClDebugGetState()->arg_[a] = argv[a]; - NaClDebugGetState()->env_.resize(envc); - for (a = 0; a < envc; a++) NaClDebugGetState()->env_[a] = envv[a]; - } DBG_CATCH_ALL - } -} - -void NaClDebugThreadPrepDebugging(struct NaClAppThread *natp) throw() { - UNREFERENCED_PARAMETER(natp); - -#ifdef NACL_DEBUG_STUB - if (NaClDebugIsEnabled()) { - NaClDebugState *state = NaClDebugGetState(); - uint32_t id = IPlatform::GetCurrentThread(); - IThread* thread = IThread::Acquire(id, true); - state->target_->TrackThread(thread); - - /* - * TODO(noelallen) We need to associate the natp with this thread - * so we can get to the untrusted context preserved on a syscall. - */ - } -#endif -} - -void NaClDebugThreadStopDebugging(struct NaClAppThread *natp) throw() { - UNREFERENCED_PARAMETER(natp); - -#ifdef NACL_DEBUG_STUB - if (NaClDebugIsEnabled()) { - NaClDebugState *state = NaClDebugGetState(); - uint32_t id = IPlatform::GetCurrentThread(); - IThread* thread = IThread::Acquire(id, false); - state->target_->IgnoreThread(thread); - IThread::Release(thread); - - /* - * TODO(noelallen) We need to associate the natp with this thread - * so we can get to the thread once we support freeing a thread - * from a different thread than the executing one. - */ - } -#endif -} - - -int NaClDebugStart(void) throw() { -#ifdef NACL_DEBUG_STUB - if (NaClDebugIsEnabled()) { - NaClThread *thread = new NaClThread; - - if (NULL == thread) return false; - NaClDebugState *state = NaClDebugGetState(); - - /* If break on start has been requested, add a temp breakpoint. */ - if (state->break_) { - struct NaClApp* app = state->app_; - state->target_->AddTemporaryBreakpoint(app->entry_pt + app->mem_start); - } - - NaClLog(LOG_WARNING, "nacl_debug(%d) : Debugging started.\n", __LINE__); - IThread::SetExceptionCatch(NaClExceptionCatcher, state->target_); - return NaClThreadCtor(thread, NaClStubThread, state->target_, - NACL_KERN_STACK_SIZE); - } -#endif - return 0; -} - -void NaClDebugStop(int ErrCode) throw() { -#ifdef NACL_DEBUG_STUB - - /* - * We check if debugging is enabled since this check is the only - * mechanism for allocating the state object. We free the - * resources but not the object itself. Instead we mark it as - * STOPPED to prevent it from getting recreated. - */ - if (NaClDebugIsEnabled()) { - NaClDebugGetState()->status_ = NDS_STOPPED; - NaClDebugGetState()->errCode_ = ErrCode; - } -#else - UNREFERENCED_PARAMETER(ErrCode); -#endif -} - diff --git a/native_client_sdk/src/build_tools/debug_server/nacl_debug.h b/native_client_sdk/src/build_tools/debug_server/nacl_debug.h deleted file mode 100644 index f9a803b..0000000 --- a/native_client_sdk/src/build_tools/debug_server/nacl_debug.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -/* - * This module provides a 'C' style interface to the NaCl debugging - * related functions, and drives the C++ debugging stub. The functions - * defined here are safe to call, because they always check if debugging - * is enabled and catch all exceptions throws by underlying C++ libraries. - * For this reason, the debug stub library should not be called directly. - * - * The behavior of the debug stub is controlled through a combination of - * a set of environment (described bellow), and conditional compilation - * based on definition of _DEBUG. - * - * These functions are non-reentrant except for the functions notifying - * the debug stub that thread has been created or is about to be - * destroyed. It is expected the other functions will all be called by - * the main thread. - */ - -#ifndef NATIVE_CLIENT_SERVICE_RUNTIME_NACL_DEBUG_H_ -#define NATIVE_CLIENT_SERVICE_RUNTIME_NACL_DEBUG_H_ - -#include "native_client/src/include/nacl_base.h" -#include "native_client/src/include/portability.h" - -EXTERN_C_BEGIN - -struct NaClApp; -struct NaClAppThread; - -/* - * Allows debugging if the feature has been enabled by compile flags. - * The conditional compile means setting this to non-zero only signals - * that debugging is requested, NaClDebugIsEnabled will need to be called - * to determine if debugging is actually enabled. - */ -void NaClDebugSetAllow(int val) NO_THROW; - -/* - * If debugging is enabled, setting this to true will cause the NEXE - * to break immediately to allow a debugger to attach. - */ -void NaClDebugSetStartBroken(int val) NO_THROW; - -/* - * Returns non-zero if debugging is allowed. This check is done via the - * NACL_DEBUG_ENABLE environment variable. - */ -//int NaClDebugIsEnabled(void) NO_THROW; //??? - -/* - * These functions should be called before the debug server has started - * to prevent a debugger from attaching and failing to retrieve - * information about the App (NEXE) that is running. These functions are - * safe to call even if debugging has not been enabled. - */ -//void NaClDebugSetAppPath(const char *path) NO_THROW; //??? -void NaClDebugSetAppInfo(struct NaClApp *app) NO_THROW; -void NaClDebugSetAppEnvironment(int argc, char const * const argv[], - int envc, char const * const envv[]) NO_THROW; - -/* - * This function must be called each time we start a new App thread by the - * by the untrusted thread itself as early as possible. The function will - * notifying the debuging stub of it's existance, and preparing the thread - * for signal or exception handling. For each thread that calls this - * function, if debugging is: - * - * ENABLED : all exceptions will be sent to the debug stub. - * DISABLED: all exceptions will be sent to breakpad. - */ -void NaClDebugThreadPrepDebugging(struct NaClAppThread *natp) NO_THROW; - - -/* - * This function notifies the debug stub that the provided thread - * should no longer be debugged. This is typically because the thread - * is about to halt. TODO(noelallen) Unlike "Prep", this function can - * be called by any thread. - */ -void NaClDebugThreadStopDebugging(struct NaClAppThread *natp) NO_THROW; - - -/* - * This function notifies the debug stub that the system is ready to - * allow debugging, and should finish preparation for debuggers to attach. - * The function will launch a new thread to act as a sever processing GDB - * RSP based connections. How a remote debugger connects to the debugging - * stub is controlled by the following environment variables: - * NACL_DEBUG_ENABLE - if defined, debugging is allowed - * NACL_DEBUG_IP - IPv4 address on which to bind (default "127.0.0.1") - * NACL_DEBUG_PORT - Port(s) on which to listen (default "8000:8010") - */ -int NaClDebugStart(void) NO_THROW; - - -/* - * Signals the debugging thread (if one has started), that it should - * release all debugging resources and halt. Prior to closing any - * connections, the debugging stub has the opportunity to notify - * an attached debugger (assuming it is in a state to receive the - * message) of the App exit code. - */ -void NaClDebugStop(int exitCode) NO_THROW; - - -EXTERN_C_END - -#endif /* NATIVE_CLIENT_SERVICE_RUNTIME_NACL_DEBUG_H_ */ diff --git a/native_client_sdk/src/build_tools/debug_server/port/event.h b/native_client_sdk/src/build_tools/debug_server/port/event.h deleted file mode 100644 index 613a1de..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/event.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module defines the interface for using platform specific events. -// It is expected that the Allocation function will return NULL on any -// failure instead of throwing an exception. This module is expected -// to throw a std::exception when an unexpected OS error is encoutered. -#ifndef NATIVE_CLIENT_PORT_EVENT_H_ -#define NATIVE_CLIENT_PORT_EVENT_H_ 1 - -namespace port { - -class IEvent { - public: - virtual void Signal() = 0; // Free one waiting thread - virtual void Wait() = 0; // Suspend this thread waiting for signal - - static IEvent *Allocate(); // Allocate an IEvent - static void Free(IEvent *e); // Free the IEvent - - protected: - virtual ~IEvent() {} // Prevent delete of base pointer -}; - - -} // namespace port - -#endif // NATIVE_CLIENT_PORT_EVENT_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/port/mutex.h b/native_client_sdk/src/build_tools/debug_server/port/mutex.h deleted file mode 100644 index 40d0a05..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/mutex.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module defines the interface for using platform specific mutexes. -// It is expected that the Allocation function will return NULL on any -// failure instead of throwing an exception. This module is expected -// to throw a std::exception when an unexpected OS error is encoutered. -// -// The mutex is owned by a single thread at a time. The thread that -// owns the mutex is free to call Lock multiple times, however it must -// call Unlock the same number of times to release the lock. -#ifndef NATIVE_CLIENT_PORT_MUTEX_H_ -#define NATIVE_CLIENT_PORT_MUTEX_H_ 1 - -#include <assert.h> -#include <stddef.h> - -namespace port { - -class IMutex { - public: - virtual void Lock() = 0; // Block until the mutex is taken - virtual void Unlock() = 0; // Unlock the mutext - virtual bool Try() = 0; // Try to lock, but return immediately - - static IMutex *Allocate(); // Allocate a mutex - static void Free(IMutex *mtx); // Free a mutex - - protected: - virtual ~IMutex() {} // Prevent delete of base pointer -}; - - -// MutexLock -// A MutexLock object will lock on construction and automatically -// unlock on destruction of the object as the object goes out of scope. -class MutexLock { - public: - explicit MutexLock(IMutex *mutex) : mutex_(mutex) { - assert(NULL != mutex_); - mutex_->Lock(); - } - ~MutexLock() { - mutex_->Unlock(); - } - - private: - IMutex *mutex_; - MutexLock(const MutexLock&); - MutexLock &operator=(const MutexLock&); -}; - - -} // namespace port - -#endif // NATIVE_CLIENT_PORT_MUTEX_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/port/platform.h b/native_client_sdk/src/build_tools/debug_server/port/platform.h deleted file mode 100644 index 00eb26a..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/platform.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module defines the interface for platform specific support -// functions, such as thread creation, logging, exception catching, -// etc... This API is not expected to throw, and instead will return -// false on any function that can fail. Since this is a collection -// of helpers functions there is expected to be only one platform object -// which can be retrieved with the static "Get" member. -#ifndef NATIVE_CLIENT_PORT_PLATFORM_H_ -#define NATIVE_CLIENT_PORT_PLATFORM_H_ 1 - -#include "native_client/src/debug_server/port/std_types.h" -#include "native_client/src/debug_server/port/transport.h" - -namespace port { - -class IPlatform { - public: - typedef void (*ThreadFunc_t)(void *cookie); - - // Get the id of the currently executing thread - static uint32_t GetCurrentThread(); - - // Called to request the platform start/stop the thread - static uint32_t CreateThread(ThreadFunc_t func, void *cookie); - - // Request the current thread relinquish execution of msec milliseconds - static void Relinquish(uint32_t msec); - - // Called to get or set process memory. - // NOTE: These functions should change the protection of the underlying - // page if needed to provide access. It should only return false if - // the page is not mapped into the debugged process. - static bool GetMemory(uint64_t address, uint32_t length, void *dst); - static bool SetMemory(uint64_t address, uint32_t length, void *src); - - // Log a message - static void LogInfo(const char *fmt, ...); - static void LogWarning(const char *fmt, ...); - static void LogError(const char *fmt, ...); -}; - -} // namespace port - - -#endif // NATIVE_CLIENT_PORT_PLATFORM_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/port/port.gyp b/native_client_sdk/src/build_tools/debug_server/port/port.gyp deleted file mode 100644 index a0d9dc2..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/port.gyp +++ /dev/null @@ -1,54 +0,0 @@ -# -*- python -*- -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -{ - 'includes': [ - '../../src/build/common.gypi', - ], - 'variables': { - 'common_sources': [ - 'event.h', - 'mutex.h', - 'platform.h', - 'thread.h', - 'transport.h', - 'std_types.h', - ], - }, - 'targets': [ - { - 'target_name': 'port', - 'type': 'static_library', - 'sources': [ - '<@(common_sources)', - ], - }, - ], -} diff --git a/native_client_sdk/src/build_tools/debug_server/port/std_types.h b/native_client_sdk/src/build_tools/debug_server/port/std_types.h deleted file mode 100644 index 002b1ec..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/std_types.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef NATIVE_CLIENT_PORT_STD_TYPES_H_ -#define NATIVE_CLIENT_PORT_STD_TYPES_H_ - -#ifdef WIN32 - -// Disable warning for Windows "safe" vsprintf_s, strcpy_s, etc... -// since we use the same version for Linux/Mac. -#pragma warning(disable:4996) - -// For intptr_t -#include <crtdefs.h> - -typedef signed char int8; -typedef short int16; -typedef int int32; -typedef long long int64; - -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; -typedef unsigned long long uint64; - -typedef signed char int8_t; -typedef short int16_t; -typedef int int32_t; -typedef long long int64_t; - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; - -#else -#include <stdint.h> -#endif - -#endif // NATIVE_CLIENT_PORT_STD_TYPES_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/port/thread.h b/native_client_sdk/src/build_tools/debug_server/port/thread.h deleted file mode 100644 index 626ed31..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/thread.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module defines the interface for interacting with platform specific -// threads . This API provides a mechanism to query for a thread, by using -// the acquire method with the ID of a pre-existing thread. The register -// accessors are expected to return false if the thread is not in a state -// where the registers can be accessed, such RUNNING or SYSCALL. This API -// will throw: -// std::exception - if a unexpected OS Error is encountered. -// std::out_of_range - if the register index is out of range. - -#ifndef NATIVE_CLIENT_PORT_THREAD_H_ -#define NATIVE_CLIENT_PORT_THREAD_H_ 1 - -#include <stdlib.h> -#include <map> - -#include "native_client/src/debug_server/port/std_types.h" - -namespace port { - -class IThread { - public: - enum State { - DEAD =-1, // The thread has exited or been killed - RUNNING = 0, // The thread is currently running - SUSPENDED= 1, // The thread has been suspended - SIGNALED = 2, // The thread is signaled - SYSCALL = 3 // In a sys call, its registers can not be modified. - }; - - typedef void (*CatchFunc_t)(uint32_t id, int8_t sig, void *cookie); - typedef std::map<uint32_t, IThread*> ThreadMap_t; - - virtual uint32_t GetId() = 0; - virtual State GetState() = 0; - - virtual bool SetStep(bool on) = 0; - - virtual bool GetRegister(uint32_t index, void *dst, uint32_t len) = 0; - virtual bool SetRegister(uint32_t index, void *src, uint32_t len) = 0; - - virtual bool Suspend() = 0; - virtual bool Resume() = 0; - - virtual void *GetContext() = 0; - - static IThread *Acquire(uint32_t id, bool create = true); - static void Release(IThread *thread); - static void SetExceptionCatch(CatchFunc_t func, void *cookie); - - protected: - virtual ~IThread() {} // Prevent delete of base pointer -}; - -} // namespace port - -#endif // PORT_THREAD_H_ - diff --git a/native_client_sdk/src/build_tools/debug_server/port/transport.h b/native_client_sdk/src/build_tools/debug_server/port/transport.h deleted file mode 100644 index 343fc56..0000000 --- a/native_client_sdk/src/build_tools/debug_server/port/transport.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -// This module provides interfaces for an IO stream. The stream is -// expected to throw a std::exception if the stream is terminated on -// either side. -#ifndef NATIVE_CLIENT_PORT_TRANSPORT_H_ -#define NATIVE_CLIENT_PORT_TRANSPORT_H_ - -#include "native_client/src/debug_server/port/std_types.h" - -namespace port { - -class ITransport { - public: - // Read from this transport, return a negative value if there is an error - // otherwise return the number of bytes actually read. - virtual int32_t Read(void *ptr, int32_t len) = 0; - - // Write to this transport, return a negative value if there is an error - // otherwise return the number of bytes actually written. - virtual int32_t Write(const void *ptr, int32_t len) = 0; - - // Return true once read will not block or false after ms milliseconds. - virtual bool ReadWaitWithTimeout(uint32_t ms) = 0; - - // Disconnect the transport, R/W and Select will now throw an exception - virtual void Disconnect() = 0; - - // Attempt to connect to, or accept connection at the specified address - static ITransport *Connect(const char *addr); - static ITransport *Accept(const char *addr); - static void Free(ITransport *transport); - - protected: - virtual ~ITransport() {} // Prevent delete of base pointer -}; - - -} // namespace port - -#endif // NATIVE_CLIENT_PORT_TRANSPORT_H_ - diff --git a/native_client_sdk/src/build_tools/generate_installers.py b/native_client_sdk/src/build_tools/generate_installers.py deleted file mode 100755 index d5cbb04..0000000 --- a/native_client_sdk/src/build_tools/generate_installers.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Assemble the final installer for each platform. - -At this time this is just a tarball. -""" - -import build_utils -import installer_contents -import optparse -import os -import re -import shutil -import stat -import string -import subprocess -import sys - -EXCLUDE_DIRS = ['.download', - '.svn'] - -INSTALLER_NAME = 'nacl-sdk.tgz' - - -# A list of all platforms that should use the Windows-based build strategy -# (which makes a self-extracting zip instead of a tarball). -WINDOWS_BUILD_PLATFORMS = ['cygwin', 'win32'] - - -# Return True if |file| should be excluded from the tarball. -def ExcludeFile(dir, file): - return (file.startswith('.DS_Store') or - file.startswith('._') or file == "make.cmd" or - file == 'DEPS' or file == 'codereview.settings' or - (file == "httpd.cmd")) - - -def main(argv): - bot = build_utils.BotAnnotator() - bot.Print('generate_installers is starting.') - - # Cache the current location so we can return here before removing the - # temporary dirs. - script_dir = os.path.abspath(os.path.dirname(__file__)) - home_dir = os.path.realpath(os.path.dirname(os.path.dirname(script_dir))) - - version_dir = build_utils.VersionString() - parent_dir = os.path.dirname(script_dir) - deps_file = os.path.join(parent_dir, 'DEPS') - - # Create a temporary directory using the version string, then move the - # contents of src to that directory, clean the directory of unwanted - # stuff and finally tar it all up using the platform's tar. There seems to - # be a problem with python's tarfile module and symlinks. - temp_dir = os.path.join(script_dir, 'installers_temp') - installer_dir = os.path.join(temp_dir, version_dir) - bot.Print('generate_installers chose installer directory: %s' % - (installer_dir)) - try: - os.makedirs(installer_dir, mode=0777) - except OSError: - pass - - # Decide environment to run in per platform. - env = os.environ.copy() - # Set up the required env variables for the scons builders. - env['NACL_SDK_ROOT'] = parent_dir - env['NACL_TARGET_PLATFORM'] = '.' # Use the repo's toolchain. - - # Use native tar to copy the SDK into the build location - # because copytree has proven to be error prone and is not supported on mac. - # We use a buffer for speed here. -1 causes the default OS size to be used. - bot.BuildStep('copy to install dir') - bot.Print('generate_installers is copying contents to install directory.') - tar_src_dir = os.path.realpath(os.curdir) - all_contents = (installer_contents.INSTALLER_CONTENTS + - installer_contents.DOCUMENTATION_FILES) - if sys.platform == 'darwin': - all_contents += installer_contents.MAC_ONLY_CONTENTS - else: - all_contents += installer_contents.LINUX_ONLY_CONTENTS - - total_contents = ( - installer_contents.GetFilesFromPathList(all_contents) + - installer_contents.GetDirectoriesFromPathList(all_contents) - ) - for item in total_contents: - itemf = installer_contents.FilterPathLayout(item) - src = itemf[0] - src_dir = os.path.join(tar_src_dir, itemf[1]) - dst_dir = os.path.join(installer_dir, itemf[2]) - print 'Tarring "%s" in "%s" then untarring in "%s"' % ( - src, src_dir, dst_dir) - if not os.path.exists(dst_dir): - os.makedirs(dst_dir) - tar_cf = subprocess.Popen('tar cf - %s' % src, - bufsize=-1, - cwd=src_dir, env=env, shell=True, - stdout=subprocess.PIPE) - tar_xf = subprocess.Popen('tar xfv -', - cwd=dst_dir, env=env, shell=True, - stdin=tar_cf.stdout) - assert tar_xf.wait() == 0 - assert tar_cf.poll() == 0 - - # This loop prunes the result of os.walk() at each excluded dir, so that it - # doesn't descend into the excluded dir. - bot.Print('generate_installers is pruning installer directory') - for root, dirs, files in os.walk(installer_dir): - rm_dirs = [] - for excl in EXCLUDE_DIRS: - if excl in dirs: - dirs.remove(excl) - rm_dirs.append(os.path.join(root, excl)) - for rm_dir in rm_dirs: - shutil.rmtree(rm_dir) - rm_files = [os.path.join(root, f) for f in files if ExcludeFile(root, f)] - for rm_file in rm_files: - os.remove(rm_file) - - # Update the README file with date and version number - build_utils.UpdateReadMe(os.path.join(installer_dir, 'README')) - - bot.BuildStep('create archive') - bot.Print('generate_installers is creating the installer archive') - # Now that the SDK directory is copied and cleaned out, tar it all up using - # the native platform tar. - - # Set the default shell command and output name. Create a compressed tar - # archive from the contents of |input|. The contents of the tar archive - # have to be relative to |input| without including |input| in the path. - # Then copy the resulting archive to the |output| directory and make it - # read-only to group and others. - ar_cmd = ('tar -cvzf %(INSTALLER_NAME)s -C %(input)s . && ' - 'cp %(INSTALLER_NAME)s %(output)s && chmod 644 %(output)s') - - archive = os.path.join(home_dir, INSTALLER_NAME) - subprocess.check_call( - ar_cmd % ( - {'INSTALLER_NAME':INSTALLER_NAME, - 'input':installer_dir, - 'output':archive}), - cwd=temp_dir, - env=env, - shell=True) - - # Clean up. - shutil.rmtree(temp_dir) - return 0 - - -if __name__ == '__main__': - print "Directly running generate_installers.py is no longer supported." - print "Please instead run './scons installer' from the src directory." - sys.exit(1) diff --git a/native_client_sdk/src/build_tools/generate_windows_installer.py b/native_client_sdk/src/build_tools/generate_windows_installer.py deleted file mode 100755 index 1ffba00..0000000 --- a/native_client_sdk/src/build_tools/generate_windows_installer.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Assemble the final installer for windows.""" - -import build_utils -import installer_contents -import make_nsis_installer -import optparse -import os -import shutil -import stat -import string -import subprocess -import sys -import tar_archive - -IGNORE_PATTERN = ('.download*', '.svn*') - -def main(argv): - bot = build_utils.BotAnnotator() - bot.Print('generate_windows_installer is starting.') - - # Make sure that we are running python version 2.6 or higher - (major, minor) = sys.version_info[:2] - assert major == 2 and minor >= 6 - # Cache the current location so we can return here before removing the - # temporary dirs. - script_dir = os.path.abspath(os.path.dirname(__file__)) - home_dir = os.path.realpath(os.path.dirname(os.path.dirname(script_dir))) - - version_dir = build_utils.VersionString() - parent_dir = os.path.dirname(script_dir) - deps_file = os.path.join(parent_dir, 'DEPS') - - # Create a temporary directory using the version string, then move the - # contents of src to that directory, clean the directory of unwanted - # stuff and finally create an installer. - temp_dir = '/naclsdk_temp' - installer_dir = os.path.join(temp_dir, version_dir) - bot.Print('generate_windows_installer chose installer directory: %s' % - (installer_dir)) - try: - os.makedirs(installer_dir, mode=0777) - except OSError: - pass - - env = os.environ.copy() - # Set up the required env variables for the scons builders. - env['NACL_SDK_ROOT'] = parent_dir - env['NACL_TARGET_PLATFORM'] = '.' # Use the repo's toolchain. - - # Build the experimental projects. - # DISABLED FOR NOW. - if False: - bot.BuildStep('build experimental') - bot.Print('generate_windows_installer is ' - 'building the experimental projects.') - experimental_path = os.path.join(home_dir, 'src', 'experimental') - scons_path = os.path.join(experimental_path, 'scons.bat') - scons_cmd = scons_path + ' --nacl-platform="."' - subprocess.check_call(scons_cmd, cwd=experimental_path, env=env) - - # On windows we use copytree to copy the SDK into the build location - # because there is no native tar and using cygwin's version has proven - # to be error prone. - - # In case previous run didn't succeed, clean this out so copytree can make - # its target directories. - bot.BuildStep('copy to install dir') - bot.Print('generate_windows_installer is cleaning out install directory.') - shutil.rmtree(installer_dir) - bot.Print('generate_windows_installer: copying files to install directory.') - all_contents = installer_contents.INSTALLER_CONTENTS + \ - installer_contents.WINDOWS_ONLY_CONTENTS - for copy_source_dir in installer_contents.GetDirectoriesFromPathList( - all_contents): - itemf = installer_contents.FilterPathLayout(copy_source_dir) - dst_dir = os.path.join(installer_dir, itemf[2]) - if not os.path.exists(dst_dir): - os.makedirs(dst_dir) - copy_target_dir = os.path.join(dst_dir, itemf[0]) - bot.Print("Copying %s to %s" % (copy_source_dir, copy_target_dir)) - shutil.copytree(copy_source_dir, - copy_target_dir, - symlinks=True, - ignore=shutil.ignore_patterns(*IGNORE_PATTERN)) - for copy_source_file in installer_contents.GetFilesFromPathList( - all_contents): - itemf = installer_contents.FilterPathLayout(copy_source_file) - copy_target_file = os.path.join(installer_dir, itemf[2], itemf[0]) - bot.Print("Copying %s to %s" % (copy_source_file, copy_target_file)) - if not os.path.exists(os.path.dirname(copy_target_file)): - os.makedirs(os.path.dirname(copy_target_file)) - shutil.copy(copy_source_file, copy_target_file) - - # Do special processing on the user-readable documentation files. - for copy_source_file in installer_contents.DOCUMENTATION_FILES: - copy_target_file = os.path.join(installer_dir, copy_source_file + '.txt') - bot.Print("Copying %s to %s" % (copy_source_file, copy_target_file)) - with open(copy_source_file, "U") as source_file: - text = source_file.read().replace("\n", "\r\n") - with open(copy_target_file, "wb") as dest_file: - dest_file.write(text) - - # Update the README.txt file with date and version number - build_utils.UpdateReadMe(os.path.join(installer_dir, 'README.txt')) - - # Clean out the cruft. - bot.Print('generate_windows_installer: cleaning up installer directory.') - - # Make everything read/write (windows needs this). - for root, dirs, files in os.walk(installer_dir): - def UpdatePermissions(list): - for file in map(lambda f: os.path.join(root, f), list): - os.chmod(file, os.lstat(file).st_mode | stat.S_IWRITE | stat.S_IREAD) - UpdatePermissions(dirs) - UpdatePermissions(files) - - bot.BuildStep('create Windows installer') - bot.Print('generate_windows_installer is creating the windows installer.') - build_tools_dir = os.path.join(home_dir, 'src', 'build_tools') - make_nsis_installer.MakeNsisInstaller( - installer_dir, - cwd=build_tools_dir, - toolchain_manifests=None) - bot.Print("Installer created!") - - # Clean up. - shutil.rmtree(temp_dir) - return 0 - - -if __name__ == '__main__': - print "Directly running generate_windows_installer.py is no longer supported." - print "Please instead run 'scons.bat installer' from the src directory." - sys.exit(1) diff --git a/native_client_sdk/src/build_tools/html_checker.py b/native_client_sdk/src/build_tools/html_checker.py deleted file mode 100755 index 1c313fb..0000000 --- a/native_client_sdk/src/build_tools/html_checker.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -'''This file provides a simple HTML checker, based on the standard HTMLParser -library.''' - -import HTMLParser -import os -import sys - - -class HTMLChecker(HTMLParser.HTMLParser): - '''A simple html parser that can find attribute tags and validate syntax''' - - def __init__(self): - self.tag_list = [] - self.links = set() - HTMLParser.HTMLParser.__init__(self) - - def handle_starttag(self, tag, attrs): - attributes = dict(attrs) - # Skip tags if they're within a <script> tag so that we don't get confused. - if not self.tag_list or self.tag_list[-1] != 'script': - self.tag_list.append(tag) - if tag == 'a' and attributes.get('href'): - self.links.add(attributes['href']) - - def handle_endtag(self, tag): - try: - matching_tag = self.tag_list.pop() - except IndexError: - raise Exception('Unmatched tag %s at %s' % (tag, self.getpos())) - if matching_tag != tag: - if matching_tag == 'script': - self.tag_list.append(matching_tag) - else: - raise Exception('Wrong tag: Expected %s but got %s at %s' % - (matching_tag, tag, self.getpos())) - - def close(self): - if self.tag_list: - raise Exception('Reached end-of-file with unclosed tags: %s' - % self.tag_list) - HTMLParser.HTMLParser.close(self) - - -def ValidateFile(filename): - '''Run simple html syntax checks on given file to validate tags and links - - Args: - filename: Name of file to validate - - Returns: - tuple containing: - set of urls from this file - set of absolute paths from this file''' - (directory, basename) = os.path.split(os.path.abspath(filename)) - parser = HTMLChecker() - with open(filename, 'r') as file: - parser.feed(file.read()) - parser.close() - files = set() - urls = set() - for link in parser.links: - if link.startswith('http://') or link.startswith('https://'): - urls.add(link) - else: - files.add(os.path.abspath(os.path.join(directory, link))) - return urls, files - - -def ValidateAllLinks(filenames): - '''Validate all the links in filename and all linked files on this domain''' - validated_files = set() - validated_urls = set() - need_to_validate = set([os.path.abspath(file) for file in filenames]) - while need_to_validate: - file = need_to_validate.pop() - print 'Evaluating %s' % file - urls, files = ValidateFile(file) - validated_files.add(file) - need_to_validate |= files - validated_files - - -def main(argv): - '''Run ValidateFile on each argument - - Args: - argv: Command-line arguments''' - ValidateAllLinks(argv) - return 0 - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/install_boost/install_boost.py b/native_client_sdk/src/build_tools/install_boost/install_boost.py deleted file mode 100755 index 02ca9b1..0000000 --- a/native_client_sdk/src/build_tools/install_boost/install_boost.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Install boost headers into a list of toolchains, in such a way that it gets -pulled into the SDK installer. Note that this script only installs boost -headers, and does not build any of the boost libraries that require building. -""" - -import build_utils -import os -import shutil -import sys -import tarfile -import tempfile -import urllib - -from optparse import OptionParser - -# The original boost distro can be found here: -# http://sourceforge.net/projects/boost/files/boost/1.47.0/\ -# boost_1_47_0.tar.gz/download -BOOST_URL = ('http://commondatastorage.googleapis.com/nativeclient-mirror' - '/nacl/boost_1_47_0.tar.gz') -BOOST_PATH = 'boost_1_47_0' - - -def DownloadAndExtract(working_dir, url, path): - boost_path = os.path.abspath(os.path.join(working_dir, path)) - print 'Download: %s' % url - try: - (tgz_file, headers) = urllib.urlretrieve(url, '%s.tgz' % boost_path) - tar = None - try: - tar = tarfile.open(tgz_file) - tar.extractall(working_dir) - finally: - if tar: - tar.close() - except (URLError, ContentTooShortError): - print 'Error retrieving %s' % url - raise - - -# Install the boost headers into the toolchains. -def InstallBoost(options): - # Create a temporary working directory. This is where all the tar files go - # and where the packages get built prior to installation in the toolchain. - working_dir = tempfile.mkdtemp(prefix='boost') - try: - DownloadAndExtract(working_dir, BOOST_URL, BOOST_PATH) - except: - print "Error in download" - return 1 - boost_include = options.third_party_dir - build_utils.ForceMakeDirs(boost_include) - boost_path = os.path.abspath(os.path.join(working_dir, BOOST_PATH)) - # Copy the headers. - print 'Installing boost headers into %s...' % boost_include - dst_include_dir = os.path.join(boost_include, 'boost') - shutil.rmtree(dst_include_dir, ignore_errors=True) - shutil.copytree(os.path.join(boost_path, 'boost'), - dst_include_dir, - symlinks=True) - # Copy the license file. - print 'Installing boost license...' - shutil.copy(os.path.join(boost_path, 'LICENSE_1_0.txt'), dst_include_dir) - - # Clean up. - shutil.rmtree(working_dir, ignore_errors=True) - return 0 - - -# Parse the command-line args and set up the options object. There is one -# command-line switch: -# --toolchain=<path to the platform-specific toolchain> -# e.g.: --toolchain=../toolchain/mac-x86 -# default is 'toolchain'. -# --toolchain can appear more than once, the Boost library is -# installed into each toolchain listed. -def main(argv): - parser = OptionParser() - parser.add_option( - '-t', '--toolchain', dest='toolchains', - action='append', - type='string', - help='NaCl toolchain directory') - parser.add_option( - '--third-party', dest='third_party_dir', - type='string', - default='third_party', - help='location of third_party directory') - (options, args) = parser.parse_args(argv) - if args: - print 'WARNING: unrecognized argument: %s' % str(args) - parser.print_help() - - if not options.toolchains: - options.toolchains = [build_utils.TOOLCHAIN_AUTODETECT] - options.toolchains = [build_utils.NormalizeToolchain(tc) - for tc in options.toolchains] - - print "Installing boost into %s" % str(options.third_party_dir) - return InstallBoost(options) - - -if __name__ == '__main__': - main(sys.argv[1:]) diff --git a/native_client_sdk/src/build_tools/install_gtest/install_gtest.py b/native_client_sdk/src/build_tools/install_gtest/install_gtest.py deleted file mode 100755 index 104589f..0000000 --- a/native_client_sdk/src/build_tools/install_gtest/install_gtest.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Install GTest and GMock that can be linked to a NaCl module. By default -this script builds both the 32- and 64-bit versions of the libraries, and -installs them in <toolchain>/nacl/usr/lib and <toolchain>/nacl64/usr/lib. The -header files are also installed in <toolchain>/<ncal_spec>/usr/include. -""" - -import build_utils -import os -import shutil -import subprocess -import sys -import tempfile -import urllib - -from optparse import OptionParser - -# Default values for the --toolchain and --bit-spec command line arguments. -BIT_SPEC_DEFAULT = "32,64" - -# The original gtest distro can be found here: -# http://code.google.com/p/googletest/downloads/detail?name=gtest-1.5.0.tar.gz -GTEST_URL = ("http://commondatastorage.googleapis.com/nativeclient-mirror/nacl/" - "gtest-1.5.0.tgz") -GTEST_PATH = "gtest-1.5.0" -GTEST_PATCH_FILE = "nacl-gtest-1.5.0.patch" - -# The original gmock distro can be found here: -# http://googlemock.googlecode.com/files/gmock-1.5.0.tar.gz -GMOCK_URL = ("http://commondatastorage.googleapis.com/nativeclient-mirror/nacl/" - "gmock-1.5.0.tgz") -GMOCK_PATH = "gmock-1.5.0" -GMOCK_PATCH_FILE = "nacl-gmock-1.5.0.patch" - - -# Create a temporary working directory. This is where all the tar files go -# and where the packages get built prior to installation in the toolchain. -def MakeWorkingDir(options): - # Pick work directory. - if not options.working_dir: - options.working_dir = tempfile.mkdtemp(prefix='gtest') - options.must_clean_up = True - # Go into working area. - options.old_cwd = os.getcwd() - os.chdir(options.working_dir) - - -# Download GTest and GMock into the working directory, then extract them. -def DownloadAndExtractAll(options): - def DownloadAndExtract(url, path): - print "Download: %s" % url - (zip_file, headers) = urllib.urlretrieve(url, '%s.tgz' % path) - p = subprocess.Popen('tar xzf %s' % (zip_file), - env=options.shell_env, - shell=True) - assert p.wait() == 0 - - os.chdir(options.working_dir) - try: - DownloadAndExtract(GTEST_URL, GTEST_PATH) - DownloadAndExtract(GMOCK_URL, GMOCK_PATH) - except (URLError, ContentTooShortError): - os.chdir(options.old_cwd) - print "Error retrieving %s" % url - raise - - os.chdir(options.old_cwd) - - -# Apply the patch files to the extracted GTest and GMock pacakges. -def PatchAll(options): - def Patch(abs_path, patch_file): - print "Patching %s with: %s" % (abs_path, patch_file) - p = subprocess.Popen('chmod -R a+w . && patch -p0 < %s' % (patch_file), - cwd=abs_path, - env=options.shell_env, - shell=True) - assert p.wait() == 0 - - Patch(options.working_dir, os.path.join(options.script_dir, GTEST_PATCH_FILE)) - Patch(options.working_dir, os.path.join(options.script_dir, GMOCK_PATCH_FILE)) - - -# Build GTest and GMock, then install them into the toolchain. Note that -# GTest has to be built and installed into the toolchain before GMock can be -# built, because GMock relies on headers from GTest. This method sets up all -# the necessary shell environment variables for the makefiles, such as CC and -# CXX. -def BuildAndInstallAll(options): - def BuildInPath(abs_path, shell_env): - # Run make clean and make in |abs_path|. Assumes there is a makefile in - # |abs_path|, if not then the assert will trigger. - print "Building in %s" % (abs_path) - p = subprocess.Popen('make clean && make -j4', - cwd=abs_path, - env=shell_env, - shell=True) - assert p.wait() == 0 - - def InstallLib(lib, src_path, dst_path, shell_env): - # Use the install untility to install |lib| from |src_path| into - # |dst_path|. - p = subprocess.Popen("install -m 644 %s %s" % (lib, dst_path), - cwd=src_path, - env=shell_env, - shell=True) - assert p.wait() == 0 - - # Build and install for each bit-spec. - for bit_spec in options.bit_spec.split(','): - if bit_spec == '64': - nacl_spec = 'x86_64-nacl' - else: - nacl_spec = 'i686-nacl' - - print 'Building gtest and gmock for NaCl spec: %s.' % nacl_spec - # Make sure the target directories exist. - nacl_usr_include = os.path.join(options.toolchain, - nacl_spec, - 'usr', - 'include') - nacl_usr_lib = os.path.join(options.toolchain, - nacl_spec, - 'usr', - 'lib') - build_utils.ForceMakeDirs(nacl_usr_include) - build_utils.ForceMakeDirs(nacl_usr_lib) - - # Set up the nacl-specific environment variables used by make. - build_env = options.shell_env.copy() - toolchain_bin = os.path.join(options.toolchain, 'bin') - build_env['CC'] = os.path.join(toolchain_bin, '%s-gcc' % nacl_spec) - build_env['CXX'] = os.path.join(toolchain_bin, '%s-g++' % nacl_spec) - build_env['AR'] = os.path.join(toolchain_bin, '%s-ar' % nacl_spec) - build_env['RANLIB'] = os.path.join(toolchain_bin, '%s-ranlib' % nacl_spec) - build_env['LD'] = os.path.join(toolchain_bin, '%s-ld' % nacl_spec) - build_env['NACL_TOOLCHAIN_ROOT'] = options.toolchain - - # GTest has to be built & installed before GMock can be built. - gtest_path = os.path.join(options.working_dir, GTEST_PATH) - BuildInPath(gtest_path, build_env) - gtest_tar_excludes = "--exclude='gtest-death-test.h' \ - --exclude='gtest-death-test-internal.h'" - tar_cf = subprocess.Popen("tar cf - %s gtest" % gtest_tar_excludes, - cwd=os.path.join(gtest_path, 'include'), - env=build_env, - shell=True, - stdout=subprocess.PIPE) - tar_xf = subprocess.Popen("tar xfp -", - cwd=nacl_usr_include, - env=build_env, - shell=True, - stdin=tar_cf.stdout) - tar_copy_err = tar_xf.communicate()[1] - InstallLib('libgtest.a', gtest_path, nacl_usr_lib, build_env) - - gmock_path = os.path.join(options.working_dir, GMOCK_PATH) - BuildInPath(gmock_path, build_env) - tar_cf = subprocess.Popen("tar cf - gmock", - cwd=os.path.join(gmock_path, 'include'), - env=options.shell_env, - shell=True, - stdout=subprocess.PIPE) - tar_xf = subprocess.Popen("tar xfp -", - cwd=nacl_usr_include, - env=options.shell_env, - shell=True, - stdin=tar_cf.stdout) - tar_copy_err = tar_xf.communicate()[1] - InstallLib('libgmock.a', gmock_path, nacl_usr_lib, build_env) - - -# Main driver method that creates a working directory, then downloads and -# extracts GTest and GMock, patches and builds them both, then installs them -# into the toolchain specified in |options.toolchain|. -def InstallTestingLibs(options): - MakeWorkingDir(options) - try: - DownloadAndExtractAll(options) - PatchAll(options) - except: - return 1 - - BuildAndInstallAll(options) - # Clean up. - if options.must_clean_up: - shutil.rmtree(options.working_dir, ignore_errors=True) - return 0 - - -# Parse the command-line args and set up the options object. There are two -# command-line switches: -# --toolchain=<path to the platform-specific toolchain> -# e.g.: --toolchain=../toolchain/mac-x86 -# default is |TOOLCHAIN_AUTODETECT| which means try to determine -# the toolchain dir from |sys.platform|. -# --bit-spec=<comma-separated list of instruction set bit-widths -# e.g.: --bit_spec=32,64 -# default is "32,64" which means build 32- and 64-bit versions -# of the libraries. -def main(argv): - shell_env = os.environ; - if not build_utils.CheckPatchVersion(shell_env): - sys.exit(0) - - parser = OptionParser() - parser.add_option( - '-t', '--toolchain', dest='toolchain', - default=build_utils.TOOLCHAIN_AUTODETECT, - help='where to put the testing libraries') - parser.add_option( - '-b', '--bit-spec', dest='bit_spec', - default=BIT_SPEC_DEFAULT, - help='comma separated list of instruction set bit-widths') - parser.add_option( - '-w', '--working_dir', dest='working_dir', - default=None, - help='where to untar and build the test libs.') - (options, args) = parser.parse_args(argv) - if args: - print 'ERROR: invalid argument: %s' % str(args) - parser.print_help() - sys.exit(1) - - options.must_clean_up = False - options.shell_env = shell_env - options.script_dir = os.path.abspath(os.path.dirname(__file__)) - options.toolchain = build_utils.NormalizeToolchain(options.toolchain) - print "Installing testing libs into toolchain %s" % options.toolchain - - return InstallTestingLibs(options) - - -if __name__ == '__main__': - main(sys.argv[1:]) diff --git a/native_client_sdk/src/build_tools/install_gtest/nacl-gmock-1.5.0.patch b/native_client_sdk/src/build_tools/install_gtest/nacl-gmock-1.5.0.patch deleted file mode 100644 index 0f22bb1..0000000 --- a/native_client_sdk/src/build_tools/install_gtest/nacl-gmock-1.5.0.patch +++ /dev/null @@ -1,29 +0,0 @@ -diff -Naur gmock-1.5.0/Makefile gmock-1.5.0.nacl/Makefile ---- gmock-1.5.0/Makefile 1969-12-31 17:00:00.000000000 -0700 -+++ gmock-1.5.0.nacl/Makefile 2010-07-07 14:28:27.000000000 -0600 -@@ -0,0 +1,25 @@ -+CXXFLAGS = -O0 -g -+INCLUDE = -Iinclude \ -+ -I. \ -+ -I$(NACL_TOOLCHAIN_ROOT)/nacl/usr/include \ -+ -I$(NACL_TOOLCHAIN_ROOT)/nacl64/usr/include -+LIB_GMOCK = libgmock.a -+OBJ_DIR = obj -+ -+OBJ_FILES = gmock-all.o \ -+ gmock_main.o -+ -+all: $(LIB_GMOCK) -+ @echo "Making libgmock" -+ -+clean: -+ rm -rf $(OBJ_DIR) $(LIB_GMOCK) -+ -+$(OBJ_DIR): -+ mkdir $(OBJ_DIR) -+ -+$(OBJ_FILES): %.o: src/%.cc $(OBJ_DIR) -+ $(CXX) -c $(INCLUDE) $(CXXFLAGS) $< -o $(OBJ_DIR)/$@ -+ -+$(LIB_GMOCK): $(OBJ_DIR) $(OBJ_FILES) -+ cd $(OBJ_DIR) && $(AR) rcs ../$(LIB_GMOCK) $(OBJ_FILES) diff --git a/native_client_sdk/src/build_tools/install_gtest/nacl-gtest-1.5.0.patch b/native_client_sdk/src/build_tools/install_gtest/nacl-gtest-1.5.0.patch deleted file mode 100644 index 389c51f..0000000 --- a/native_client_sdk/src/build_tools/install_gtest/nacl-gtest-1.5.0.patch +++ /dev/null @@ -1,226 +0,0 @@ -diff -Naur gtest-1.5.0/Makefile gtest-1.5.0.nacl/Makefile ---- gtest-1.5.0/Makefile 1969-12-31 17:00:00.000000000 -0700 -+++ gtest-1.5.0.nacl/Makefile 2010-07-08 09:49:37.000000000 -0600 -@@ -0,0 +1,25 @@ -+CXXFLAGS = -O0 -g -+INCLUDE = -Iinclude -I. -+LIB_GTEST = libgtest.a -+OBJ_DIR = obj -+ -+OBJ_FILES = gtest.o \ -+ gtest-filepath.o \ -+ gtest-port.o \ -+ gtest-test-part.o \ -+ gtest-typed-test.o -+ -+all: $(LIB_GTEST) -+ @echo "Making libgtest" -+ -+clean: -+ rm -rf $(OBJ_DIR) $(LIB_GTEST) -+ -+$(OBJ_DIR): -+ mkdir $(OBJ_DIR) -+ -+$(OBJ_FILES): %.o: src/%.cc $(OBJ_DIR) -+ $(CXX) -c $(INCLUDE) $(CXXFLAGS) $< -o $(OBJ_DIR)/$@ -+ -+$(LIB_GTEST): $(OBJ_DIR) $(OBJ_FILES) -+ cd $(OBJ_DIR) && $(AR) rcs ../$(LIB_GTEST) $(OBJ_FILES) -diff -Naur gtest-1.5.0/include/gtest/gtest.h gtest-1.5.0.nacl/include/gtest/gtest.h ---- gtest-1.5.0/include/gtest/gtest.h 2010-04-15 16:02:03.000000000 -0600 -+++ gtest-1.5.0.nacl/include/gtest/gtest.h 2010-07-08 09:49:37.000000000 -0600 -@@ -56,7 +56,6 @@ - - #include <gtest/internal/gtest-internal.h> - #include <gtest/internal/gtest-string.h> --#include <gtest/gtest-death-test.h> - #include <gtest/gtest-message.h> - #include <gtest/gtest-param-test.h> - #include <gtest/gtest_prod.h> -diff -Naur gtest-1.5.0/include/gtest/internal/gtest-port.h gtest-1.5.0.nacl/include/gtest/internal/gtest-port.h ---- gtest-1.5.0/include/gtest/internal/gtest-port.h 2010-04-15 16:02:02.000000000 -0600 -+++ gtest-1.5.0.nacl/include/gtest/internal/gtest-port.h 2010-07-08 09:49:37.000000000 -0600 -@@ -222,14 +222,13 @@ - #endif // __CYGWIN__ - - #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_SYMBIAN || \ -- GTEST_OS_SOLARIS || GTEST_OS_AIX -+ GTEST_OS_SOLARIS || GTEST_OS_AIX && !defined(__native_client__) - - // On some platforms, <regex.h> needs someone to define size_t, and - // won't compile otherwise. We can #include it here as we already - // included <stdlib.h>, which is guaranteed to define size_t through - // <stddef.h>. - #include <regex.h> // NOLINT --#include <strings.h> // NOLINT - #include <sys/types.h> // NOLINT - #include <time.h> // NOLINT - #include <unistd.h> // NOLINT -@@ -485,7 +484,9 @@ - #if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ - GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX) -+#if !defined(__native_client__) - #define GTEST_HAS_DEATH_TEST 1 -+#endif - #include <vector> // NOLINT - #endif - -@@ -839,11 +840,7 @@ - // testing Google Test's own constructs. Don't use it in user tests, - // either directly or indirectly. - inline void SleepMilliseconds(int n) { -- const timespec time = { -- 0, // 0 seconds. -- n * 1000L * 1000L, // And n ms. -- }; -- nanosleep(&time, NULL); -+ usleep(100 * n); - } - - // Allows a controller thread to pause execution of newly created -diff -Naur gtest-1.5.0/src/gtest-death-test.cc gtest-1.5.0.nacl/src/gtest-death-test.cc ---- gtest-1.5.0/src/gtest-death-test.cc 2010-04-15 16:02:04.000000000 -0600 -+++ gtest-1.5.0.nacl/src/gtest-death-test.cc 2010-07-08 09:49:38.000000000 -0600 -@@ -34,6 +34,8 @@ - #include <gtest/gtest-death-test.h> - #include <gtest/internal/gtest-port.h> - -+#undef GTEST_HAS_DEATH_TEST -+ - #if GTEST_HAS_DEATH_TEST - - #if GTEST_OS_MAC -diff -Naur gtest-1.5.0/src/gtest-filepath.cc gtest-1.5.0.nacl/src/gtest-filepath.cc ---- gtest-1.5.0/src/gtest-filepath.cc 2010-04-15 16:02:04.000000000 -0600 -+++ gtest-1.5.0.nacl/src/gtest-filepath.cc 2010-07-08 09:49:38.000000000 -0600 -@@ -96,21 +96,6 @@ - #endif - } - --// Returns the current working directory, or "" if unsuccessful. --FilePath FilePath::GetCurrentDir() { --#if GTEST_OS_WINDOWS_MOBILE -- // Windows CE doesn't have a current directory, so we just return -- // something reasonable. -- return FilePath(kCurrentDirectoryString); --#elif GTEST_OS_WINDOWS -- char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; -- return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); --#else -- char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; -- return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); --#endif // GTEST_OS_WINDOWS_MOBILE --} -- - // Returns a copy of the FilePath with the case-insensitive extension removed. - // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns - // FilePath("dir/file"). If a case-insensitive extension is not -diff -Naur gtest-1.5.0/src/gtest-internal-inl.h gtest-1.5.0.nacl/src/gtest-internal-inl.h ---- gtest-1.5.0/src/gtest-internal-inl.h 2010-04-15 16:02:04.000000000 -0600 -+++ gtest-1.5.0.nacl/src/gtest-internal-inl.h 2010-07-08 09:49:39.000000000 -0600 -@@ -67,13 +67,6 @@ - - namespace testing { - --// Declares the flags. --// --// We don't want the users to modify this flag in the code, but want --// Google Test's own unit tests to be able to access it. Therefore we --// declare it here as opposed to in gtest.h. --GTEST_DECLARE_bool_(death_test_use_fork); -- - namespace internal { - - // The value of GetTestTypeId() as seen from within the Google Test -@@ -154,10 +147,7 @@ - break_on_failure_ = GTEST_FLAG(break_on_failure); - catch_exceptions_ = GTEST_FLAG(catch_exceptions); - color_ = GTEST_FLAG(color); -- death_test_style_ = GTEST_FLAG(death_test_style); -- death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); - filter_ = GTEST_FLAG(filter); -- internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); - list_tests_ = GTEST_FLAG(list_tests); - output_ = GTEST_FLAG(output); - print_time_ = GTEST_FLAG(print_time); -@@ -174,10 +164,7 @@ - GTEST_FLAG(break_on_failure) = break_on_failure_; - GTEST_FLAG(catch_exceptions) = catch_exceptions_; - GTEST_FLAG(color) = color_; -- GTEST_FLAG(death_test_style) = death_test_style_; -- GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; - GTEST_FLAG(filter) = filter_; -- GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; - GTEST_FLAG(list_tests) = list_tests_; - GTEST_FLAG(output) = output_; - GTEST_FLAG(print_time) = print_time_; -@@ -193,10 +180,7 @@ - bool break_on_failure_; - bool catch_exceptions_; - String color_; -- String death_test_style_; -- bool death_test_use_fork_; - String filter_; -- String internal_run_death_test_; - bool list_tests_; - String output_; - bool print_time_; -@@ -699,18 +683,6 @@ - void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - TestInfo * test_info) { -- // In order to support thread-safe death tests, we need to -- // remember the original working directory when the test program -- // was first invoked. We cannot do this in RUN_ALL_TESTS(), as -- // the user may have changed the current directory before calling -- // RUN_ALL_TESTS(). Therefore we capture the current directory in -- // AddTestInfo(), which is called to register a TEST or TEST_F -- // before main() is reached. -- if (original_working_dir_.IsEmpty()) { -- original_working_dir_.Set(FilePath::GetCurrentDir()); -- GTEST_CHECK_(!original_working_dir_.IsEmpty()) -- << "Failed to get the current working directory."; -- } - - GetTestCase(test_info->test_case_name(), - test_info->test_case_comment(), -diff -Naur gtest-1.5.0/src/gtest.cc gtest-1.5.0.nacl/src/gtest.cc ---- gtest-1.5.0/src/gtest.cc 2010-04-15 16:02:04.000000000 -0600 -+++ gtest-1.5.0.nacl/src/gtest.cc 2010-07-08 09:49:40.000000000 -0600 -@@ -57,7 +57,9 @@ - #include <limits.h> - #include <sched.h> - // Declares vsnprintf(). This header is not available on Windows. -+#if !defined(__native_client__) - #include <strings.h> -+#endif - #include <sys/mman.h> - #include <sys/time.h> - #include <unistd.h> -@@ -4597,13 +4599,7 @@ - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || -- ParseStringFlag(arg, kDeathTestStyleFlag, -- >EST_FLAG(death_test_style)) || -- ParseBoolFlag(arg, kDeathTestUseFork, -- >EST_FLAG(death_test_use_fork)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || -- ParseStringFlag(arg, kInternalRunDeathTestFlag, -- >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || -diff -Naur gtest-1.5.0/src/gtest_main.cc gtest-1.5.0.nacl/src/gtest_main.cc ---- gtest-1.5.0/src/gtest_main.cc 2010-04-15 16:02:04.000000000 -0600 -+++ gtest-1.5.0.nacl/src/gtest_main.cc 2010-07-08 10:14:13.000000000 -0600 -@@ -33,7 +33,6 @@ - - int main(int argc, char **argv) { - std::cout << "Running main() from gtest_main.cc\n"; -- - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); - } diff --git a/native_client_sdk/src/build_tools/install_nsis.py b/native_client_sdk/src/build_tools/install_nsis.py deleted file mode 100644 index 3b696ab..0000000 --- a/native_client_sdk/src/build_tools/install_nsis.py +++ /dev/null @@ -1,161 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Install the NSIS compiler and its SDK.""" - -import os -import shutil -import subprocess -import zipfile - - -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -SDK_SRC_DIR = os.path.dirname(SCRIPT_DIR) -SRC_DIR = os.path.dirname(os.path.dirname(SDK_SRC_DIR)) -THIRD_PARTY_DIR = os.path.join(SRC_DIR, 'third_party') -BIN_DIR = os.path.join(THIRD_PARTY_DIR, 'nacl_sdk_binaries') - -# The name of the archive that contains the AccessControl extensions. -ACCESS_CONTROL_ZIP = os.path.join(BIN_DIR, 'AccessControl.zip') -# The AccessControl plugin. The installer check for this before installing. -ACCESS_CONTROL_DLL = 'AccessControl.dll' -# The name of the MkLnk extension DLL. This is checked into the SDK repo. -MKLINK_DLL = os.path.join(SCRIPT_DIR, - 'MkLink', 'Release Unicode', 'MkLink.dll') -# The NSIS compiler. The installer checks for this before installing. -NSIS_COMPILER = 'makensis.exe' -# The default directory name for the NSIS installation. -NSIS_DIR = 'NSIS' -# The name of the NSIS installer. This file is checked into the SDK repo. -NSIS_INSTALLER = os.path.join(BIN_DIR, 'nsis-2.46-Unicode-setup.exe') - -def MakeDirsIgnoreExist(dir_path, mode=0755): - '''Recursively make a directory path. - - Recursively makes all the paths in |dir_path|. If |dir_path| already exists, - do nothing. - - Args: - dir_path: A directory path. All necessary comonents of this path are - created. - mode: The mode to use if creating |dir_path|. Default is 0755. - ''' - if not os.path.exists(dir_path): - os.makedirs(dir_path, mode=mode) - - -def InstallNsis(installer_exe, target_dir, force=False): - '''Install NSIS into |target_dir|. - - Args: - installer_exe: The full path to the NSIS self-extracting installer. - - target_dir: The target directory for NSIS. The installer is run in this - directory and produces a directory named NSIS that contains the NSIS - compiler, etc. Must be defined. - - force: Whether or not to force an installation. - ''' - if not os.path.exists(installer_exe): - raise IOError('%s not found' % installer_exe) - - if not os.path.isabs(installer_exe): - raise ValueError('%s must be an absolute path' % installer_exe) - if not os.path.isabs(target_dir): - raise ValueError('%s must be an absolute path' % target_dir) - - if force or not os.path.exists(os.path.join(target_dir, NSIS_COMPILER)): - MakeDirsIgnoreExist(target_dir) - subprocess.check_call([installer_exe, - '/S', - '/D=%s' % target_dir], - cwd=os.path.dirname(installer_exe), - shell=True) - - -def InstallAccessControlExtensions(cwd, - access_control_zip, - target_dir, - force=False): - '''Install the AccessControl extensions into the NSIS directory. - - Args: - cwd: The current working directory. - - access_control_zip: The full path of the AccessControl.zip file. The - contents of this file are extracted using python's zipfile package. - - target_dir: The full path of the target directory for the AccessControl - extensions. - - force: Whether or not to force an installation. - ''' - if not os.path.exists(access_control_zip): - raise IOError('%s not found' % access_control_zip) - - dst_plugin_dir = os.path.join(target_dir, 'Plugins') - if force or not os.path.exists(os.path.join(dst_plugin_dir, - ACCESS_CONTROL_DLL)): - MakeDirsIgnoreExist(dst_plugin_dir) - zip_file = zipfile.ZipFile(access_control_zip, 'r') - try: - zip_file.extractall(target_dir) - finally: - zip_file.close() - # Move the AccessControl plugin DLLs into the main NSIS Plugins directory. - access_control_plugin_dir = os.path.join(target_dir, - 'AccessControl', - 'Plugins') - access_control_plugins = [os.path.join(access_control_plugin_dir, p) - for p in os.listdir(access_control_plugin_dir)] - for plugin in access_control_plugins: - shutil.copy(plugin, dst_plugin_dir) - - -def InstallMkLinkExtensions(mklink_dll, target_dir, force=False): - '''Install the AccessControl extensions into the NSIS directory. - - Args: - mklink_dll: The full path of the MkLink.dll file. - - target_dir: The full path of the target directory for the MkLink - extensions. - - force: Whether or not to force an installation. - ''' - if not os.path.exists(mklink_dll): - raise IOError('%s not found' % mklink_dll) - - dst_plugin_dir = os.path.join(target_dir, 'Plugins') - dst_mklink_dll = os.path.join(dst_plugin_dir, os.path.basename(mklink_dll)) - if force or not os.path.exists(dst_mklink_dll): - MakeDirsIgnoreExist(dst_plugin_dir) - # Copy the MkLink plugin DLLs into the main NSIS Plugins directory. - shutil.copy(mklink_dll, dst_mklink_dll) - - -def Install(cwd, target_dir=None, force=False): - '''Install the entire NSIS compiler and SDK with extensions. - - Installs the NSIS SDK and extensions into |target_dir|. By default, the - target directory is NSIS_DIR under |cwd|. - - If NSIS is already installed and |force| is False, do nothing. If |force| - is True or NSIS is not already installed, then install NSIS and the necessary - extensions. - - Args: - cwd: The current working directory. - - target_dir: NSIS is installed here. If |target_dir| is None, then NSIS is - installed in its default location, which is NSIS_DIR under |cwd|. - - force: True means install NSIS whether it already exists or not. - ''' - # If the NSIS compiler and SDK hasn't been installed, do so now. - nsis_dir = target_dir or os.path.join(cwd, NSIS_DIR) - InstallNsis(os.path.join(cwd, NSIS_INSTALLER), nsis_dir, force=force) - InstallMkLinkExtensions(os.path.join(cwd, MKLINK_DLL), nsis_dir, force=force) - InstallAccessControlExtensions( - cwd, os.path.join(cwd, ACCESS_CONTROL_ZIP), nsis_dir, force=force) diff --git a/native_client_sdk/src/build_tools/install_third_party.py b/native_client_sdk/src/build_tools/install_third_party.py deleted file mode 100755 index e683b66..0000000 --- a/native_client_sdk/src/build_tools/install_third_party.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Build and install all the third-party tools and libraries required to build -the SDK code. To add a script, add it to the array |THIRD_PARTY_SCRIPTS|. -Before running the scripts, a couple of environment variables get set: - PYTHONPATH - append this script's dir to the search path for module import. - NACL_SDK_ROOT - forced to point to the root of this repo. -""" - -import os -import subprocess -import sys - -from optparse import OptionParser - -# Append to PYTHONPATH in this very non-compliant way so that this script can be -# run from a DEPS hook, where the normal path rules don't apply. -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -SDK_SRC_DIR = os.path.dirname(SCRIPT_DIR) -SRC_DIR = os.path.dirname(os.path.dirname(SDK_SRC_DIR)) -THIRD_PARTY_DIR = os.path.join(SRC_DIR, 'third_party') -SCONS_DIR = os.path.join(THIRD_PARTY_DIR, 'scons-2.0.1', 'engine') -sys.path.append(SCRIPT_DIR) -sys.path.append(SCONS_DIR) - -import build_utils - - -THIRD_PARTY_SCRIPTS = [ - os.path.join('install_boost', 'install_boost.py'), -] - - -def main(argv): - parser = OptionParser() - parser.add_option( - '-a', '--all-toolchains', dest='all_toolchains', - action='store_true', - help='Install into all available toolchains.') - (options, args) = parser.parse_args(argv) - if args: - print 'ERROR: invalid argument: %s' % str(args) - parser.print_help() - sys.exit(1) - - python_paths = [SCRIPT_DIR, SCONS_DIR] - shell_env = os.environ.copy() - python_paths += [shell_env.get('PYTHONPATH', '')] - shell_env['PYTHONPATH'] = os.pathsep.join(python_paths) - - # Force NACL_SDK_ROOT to point to the toolchain in this repo. - nacl_sdk_root = os.path.dirname(SCRIPT_DIR) - shell_env['NACL_SDK_ROOT'] = nacl_sdk_root - - script_argv = [arg for arg in argv if not arg in ['-a', '--all-toolchains']] - if options.all_toolchains: - script_argv += [ - '--toolchain=%s' % ( - build_utils.NormalizeToolchain(base_dir=nacl_sdk_root, - arch='x86', - variant='glibc')), - '--toolchain=%s' % ( - build_utils.NormalizeToolchain(base_dir=nacl_sdk_root, - arch='x86', - variant='newlib')), - '--third-party=%s' % THIRD_PARTY_DIR, - ] - - for script in THIRD_PARTY_SCRIPTS: - print "Running install script: %s" % os.path.join(SCRIPT_DIR, script) - py_command = [sys.executable, os.path.join(SCRIPT_DIR, script)] - subprocess.check_call(py_command + script_argv, env=shell_env) - - -if __name__ == '__main__': - main(sys.argv[1:]) diff --git a/native_client_sdk/src/build_tools/installer_contents.py b/native_client_sdk/src/build_tools/installer_contents.py deleted file mode 100644 index bda6213..0000000 --- a/native_client_sdk/src/build_tools/installer_contents.py +++ /dev/null @@ -1,213 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""White-list of directories and files that get installed in the SDK. - -Note that the list of directories is kept separate from the list of files -because copying a directory is treated differently than copying files on -Windows. -""" - -import os -import sys -from nacl_sdk_scons import nacl_utils - - -# For each path in this list, its entire contents are added to the SDK -# installer. Directories are denoted by a trailing '/' - this is important -# because they have to be treated separately on Windows for plain files (the -# copy mechanism is different). Note that the path separator is hard-coded to -# be '/'. When accessing these lists, use the Get*() functions, which replace -# the '/' with the correct platform-specific path separator as defined by -# os.path. -INSTALLER_CONTENTS = [ - 'build_tools/nacl_sdk_scons/make_nacl_env.py', - 'build_tools/nacl_sdk_scons/nacl_utils.py', - 'build_tools/nacl_sdk_scons/site_tools/', - 'examples/build.scons', - 'examples/common/', - 'examples/favicon.ico', - 'examples/geturl/', - 'examples/hello_world/', - 'examples/hello_world_c/', - 'examples/httpd.py', - 'examples/index.html', - 'examples/index_staging.html', - 'examples/input_events/', - 'examples/load_progress/', - 'examples/mouselock/', - 'examples/multithreaded_input_events/', - 'examples/pi_generator/', - 'examples/pong/', - 'examples/scons', - 'examples/sine_synth/', - 'examples/tumbler/', - 'examples/fullscreen_tumbler/', - 'project_templates/README', - 'project_templates/c/', - 'project_templates/cc/', - 'project_templates/html/', - 'project_templates/init_project.py', - 'project_templates/scons', - 'project_templates/vs/', - '../../third_party/scons-2.0.1/', -] - -INSTALLER_CONTENTS.append('%s/' % nacl_utils.ToolchainPath( - base_dir='../../native_client', variant='newlib')) -INSTALLER_CONTENTS.append('%s/' % nacl_utils.ToolchainPath( - base_dir='../../native_client', variant='glibc')) - -LINUX_ONLY_CONTENTS = [ - '../../ppapi/', -] - -MAC_ONLY_CONTENTS = [ - '../../ppapi/', -] - -WINDOWS_ONLY_CONTENTS = [ - 'examples/httpd.cmd', - 'examples/scons.bat', - 'project_templates/scons.bat', -# Dropping debugger. -# 'debugger/nacl-gdb_server/x64/Release/', -# 'debugger/nacl-gdb_server/Release/', -# 'debugger/nacl-bpad/x64/Release/' -] - -# These files are user-readable documentation files, and as such get some -# further processing on Windows (\r\n line-endings and .txt file suffix). -# On non-Windows platforms, the installer content list is the union of -# |INSTALLER_CONTENTS| and |DOCUMENTATION_FILES|. -DOCUMENTATION_FILES = [ - 'AUTHORS', - 'COPYING', - 'LICENSE', - 'NOTICE', - 'README', -] - - -def GetToolchainManifest(toolchain): - '''Get the toolchain manifest file. - - These manifest files are used to create NSIS file sections for the - toolchains. The manifest files are considered the source of truth for - symbolic links and other filesystem-specific information that is not - discoverable using python in Windows. - - Args: - toolchain: The toolchain variant. Currently supported values are 'newlib' - and 'glibc'. - - Returns: - The os-specific path to the toolchain manifest file, relative to the SDK's - src directory. - ''' - WINDOWS_TOOLCHAIN_MANIFESTS = { - 'newlib': 'naclsdk_win_x86.tgz.manifest', - 'glibc': 'toolchain_win_x86.tar.xz.manifest', - } - MAC_TOOLCHAIN_MANIFESTS = { - 'newlib': 'naclsdk_mac_x86.tgz.manifest', - 'glibc': 'toolchain_mac_x86.tar.bz2.manifest', - } - LINUX_TOOLCHAIN_MANIFESTS = { - 'newlib': 'naclsdk_linux_x86.tgz.manifest', - 'glibc': 'toolchain_linux_x86.tar.xz.manifest', - } - manifest_file = None - if sys.platform == 'win32': - manifest_file = WINDOWS_TOOLCHAIN_MANIFESTS[toolchain] - elif sys.platform == 'darwin': - manifest_file = MAC_TOOLCHAIN_MANIFESTS[toolchain] - elif sys.platform == 'linux2': - manifest_file = LINUX_TOOLCHAIN_MANIFESTS[toolchain] - if manifest_file: - return os.path.join('build_tools', 'toolchain_archives', manifest_file) - else: - return None - - -def ConvertToOSPaths(path_list): - '''Convert '/' path separators to OS-specific path separators. - - For each file in |path_list|, replace each occurence of the '/' path - separator to the OS-specific separator as defined by os.path. - - Args: - path_list: A list of file paths that use '/' as the path sparator. - - Returns: - A new list where each element represents the same file paths as in - |path_list|, but using the os-specific path separator. - ''' - return [os.path.join(*path.split('/')) for path in path_list] - - -def GetDirectoriesFromPathList(path_list): - '''Return a list of all the content directories. - - The paths in the returned list are formatted to be OS-specific, and are - ready to be used in file IO operations. - - Args: - path_list: A list of paths that use '/' as the path separator. - - Returns: - A list of paths to be included in the SDK installer. The paths all have - OS-specific separators. - ''' - return ConvertToOSPaths( - [dir for dir in path_list if dir.endswith('/')]) - - -def GetFilesFromPathList(path_list): - '''Return a list of all the content files. - - The paths in the returned list are formatted to be OS-specific, and are - ready to be used in file IO operations. - - Args: - path_list: A list of paths that use '/' as the path separator. - - Returns: - A list of paths to be included in the SDK installer. The paths all have - OS-specific separators. - ''' - return ConvertToOSPaths( - [dir for dir in path_list if not dir.endswith('/')]) - - -def FilterPathLayout(path): - '''Given a path, decide how it should be copied. - - The SDK was originally layed out homogeneously with the generated - installer. Inside the chromium tree, this is not longer desireable. - This function compenstates. - - Args: - path: A path to install. - - Returns: - A list of [src path to tar, cwd when taring src, dst to untar in]. - ''' - # Toolchain moved up to top of tree. - nacl_dir = '../../native_client/'.replace('/', os.sep) - top_dir = '../../'.replace('/', os.sep) - ppapi_dir = '../../ppapi/'.replace('/', os.sep) - - # Use toolchain from nacl_dir. - if path.startswith(nacl_dir): - return [os.path.join('.', path[len(nacl_dir):]), nacl_dir, '.'] - # Use ppapi directly, but put in third_party. - if path.startswith(ppapi_dir): - return [os.path.join('.', path[len(ppapi_dir):]), ppapi_dir, - 'third_party/ppapi'] - # Third party is used from top of tree (for scons). - if path.startswith(top_dir): - return [os.path.join('.', path[len(top_dir):]), top_dir, '.'] - # Normal case. - return [path, '.', '.'] diff --git a/native_client_sdk/src/build_tools/make_nacl_tools.py b/native_client_sdk/src/build_tools/make_nacl_tools.py deleted file mode 100755 index d20bd8c..0000000 --- a/native_client_sdk/src/build_tools/make_nacl_tools.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Build NaCl tools (e.g. sel_ldr and ncval) at a given revision.""" - -import build_utils -import optparse -import os -import shutil -import subprocess -import sys -import tempfile - -bot = build_utils.BotAnnotator() - - -# The suffix used for NaCl moduels that are installed, such as irt_core. -NEXE_SUFFIX = '.nexe' - -def MakeInstallDirs(options): - '''Create the necessary install directories in the SDK staging area. - ''' - install_dir = os.path.join(options.toolchain, 'bin'); - if not os.path.exists(install_dir): - os.makedirs(install_dir) - runtime_dir = os.path.join(options.toolchain, 'runtime'); - if not os.path.exists(runtime_dir): - os.makedirs(runtime_dir) - - -def Build(options): - '''Build 32-bit and 64-bit versions of needed NaCL tools and libs.''' - nacl_dir = os.path.join(options.nacl_dir, 'native_client') - toolchain_option = 'naclsdk_mode=custom:%s' % options.toolchain - libc_option = '' if options.lib == 'newlib' else ' --nacl_glibc' - if sys.platform == 'win32': - scons = os.path.join(nacl_dir, 'scons.bat') - bits32 = 'vcvarsall.bat x86 && ' - bits64 = 'vcvarsall.bat x86_amd64 && ' - else: - scons = os.path.join(nacl_dir, 'scons') - bits32 = '' - bits64 = '' - - # Build sel_ldr and ncval. - def BuildTools(prefix, bits, target): - cmd = '%s%s -j %s --mode=%s platform=x86-%s naclsdk_validate=0 %s %s%s' % ( - prefix, scons, options.jobs, options.variant, bits, target, - toolchain_option, libc_option) - bot.Run(cmd, shell=True, cwd=nacl_dir) - - BuildTools(bits32, '32', 'sdl=none sel_ldr ncval') - BuildTools(bits64, '64', 'sdl=none sel_ldr ncval') - - # Build irt_core, which is needed for running .nexes with sel_ldr. - def BuildIRT(bits): - cmd = '%s -j %s irt_core --mode=opt-host,nacl platform=x86-%s %s' % ( - scons, options.jobs, bits, toolchain_option) - bot.Run(cmd, shell=True, cwd=nacl_dir) - - # only build the IRT using the newlib chain. glibc does not support IRT. - if options.lib == 'newlib': - BuildIRT(32) - BuildIRT(64) - - # Build and install untrusted libraries. - def BuildAndInstallLibsAndHeaders(bits): - cmd = ('%s install --mode=opt-host,nacl libdir=%s includedir=%s ' - 'platform=x86-%s force_sel_ldr=none %s%s') % ( - scons, - os.path.join(options.toolchain, - 'x86_64-nacl', - 'lib32' if bits == 32 else 'lib'), - os.path.join(options.toolchain, 'x86_64-nacl', 'include'), - bits, - toolchain_option, - libc_option) - bot.Run(cmd, shell=True, cwd=nacl_dir) - - BuildAndInstallLibsAndHeaders(32) - BuildAndInstallLibsAndHeaders(64) - - -def Install(options, tools=[], runtimes=[]): - '''Install the NaCl tools and runtimes into the SDK staging area. - - Assumes that all necessary artifacts are built into the NaCl scons-out/staging - directory, and copies them from there into the SDK staging area under - toolchain. - - Args: - options: The build options object. This is populated from command-line - args at start-up. - tools: A list of tool names, these should *not* have any executable - suffix - this utility adds that (e.g. '.exe' on Windows). - runtimes: A list of IRT runtimes. These artifacts should *not* have any - suffix attached - this utility adds the '.nexe' suffix along with an - ISA-specific string (e.g. '_x86_32'). - ''' - # TODO(bradnelson): add an 'install' alias to the main build for this. - nacl_dir = os.path.join(options.nacl_dir, 'native_client') - tool_build_path_32 = os.path.join(nacl_dir, - 'scons-out', - '%s-x86-32' % (options.variant), - 'staging') - tool_build_path_64 = os.path.join(nacl_dir, - 'scons-out', - '%s-x86-64' % (options.variant), - 'staging') - - for nacl_tool in tools: - shutil.copy(os.path.join(tool_build_path_32, - '%s%s' % (nacl_tool, options.exe_suffix)), - os.path.join(options.toolchain, - 'bin', - '%s_x86_32%s' % (nacl_tool, options.exe_suffix))) - shutil.copy(os.path.join(tool_build_path_64, - '%s%s' % (nacl_tool, options.exe_suffix)), - os.path.join(options.toolchain, - 'bin', - '%s_x86_64%s' % (nacl_tool, options.exe_suffix))) - - irt_build_path_32 = os.path.join(nacl_dir, - 'scons-out', - 'nacl_irt-x86-32', - 'staging') - irt_build_path_64 = os.path.join(nacl_dir, - 'scons-out', - 'nacl_irt-x86-64', - 'staging') - for nacl_irt in runtimes: - shutil.copy(os.path.join(irt_build_path_32, - '%s%s' % (nacl_irt, NEXE_SUFFIX)), - os.path.join(options.toolchain, - 'runtime', - '%s_x86_32%s' % (nacl_irt, NEXE_SUFFIX))) - shutil.copy(os.path.join(irt_build_path_64, - '%s%s' % (nacl_irt, NEXE_SUFFIX)), - os.path.join(options.toolchain, - 'runtime', - '%s_x86_64%s' % (nacl_irt, NEXE_SUFFIX))) - - -def BuildNaClTools(options): - if(options.clean): - bot.Print('Removing scons-out') - scons_out = os.path.join(options.nacl_dir, 'native_client', 'scons-out') - build_utils.CleanDirectory(scons_out) - else: - MakeInstallDirs(options) - Build(options) - Install(options, tools=['sel_ldr', 'ncval'], runtimes=['irt_core']) - return 0 - - -def main(argv): - if sys.platform in ['win32', 'cygwin']: - exe_suffix = '.exe' - else: - exe_suffix = '' - - script_dir = os.path.abspath(os.path.dirname(__file__)) - - parser = optparse.OptionParser() - parser.add_option( - '-t', '--toolchain', dest='toolchain', - default='toolchain', - help='where to put the NaCl tool binaries') - parser.add_option( - '-l', '--lib', dest='lib', - default='newlib', - help='whether to build against newlib (default) or glibc') - parser.add_option( - '-c', '--clean', action='store_true', dest='clean', - default=False, - help='whether to clean up the checkout files') - parser.add_option( - '-j', '--jobs', dest='jobs', default='1', - help='Number of parallel jobs to use while building nacl tools') - parser.add_option( - '-n', '--nacl_dir', dest='nacl_dir', - default=os.path.join(script_dir, 'packages', 'native_client'), - help='Location of Native Client repository used for building tools') - (options, args) = parser.parse_args(argv) - if args: - parser.print_help() - bot.Print('ERROR: invalid argument(s): %s' % args) - return 1 - - options.toolchain = os.path.abspath(options.toolchain) - options.exe_suffix = exe_suffix - # Pick variant. - if sys.platform in ['win32', 'cygwin']: - variant = 'dbg-win' - elif sys.platform == 'darwin': - variant = 'dbg-mac' - elif sys.platform in ['linux', 'linux2']: - variant = 'dbg-linux' - else: - assert False - options.variant = variant - - if options.lib not in ['newlib', 'glibc']: - bot.Print('ERROR: --lib must either be newlib or glibc') - return 1 - - return BuildNaClTools(options) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/make_nsis_installer.py b/native_client_sdk/src/build_tools/make_nsis_installer.py deleted file mode 100644 index 28772b6..0000000 --- a/native_client_sdk/src/build_tools/make_nsis_installer.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Create the NSIS installer for the SDK.""" - -import os -import subprocess - -from build_tools import build_utils -from build_tools import install_nsis -from build_tools import nsis_script - -# TODO(dspringer): |toolchain_manifests| is not currently used by any callers. -def MakeNsisInstaller(installer_dir, - sdk_version=None, - cwd=None, - toolchain_manifests=None): - '''Create the NSIS installer - - Args: - installer_dir: The directory containing all the artifacts that get packaged - in the NSIS installer. - - sdk_version: A string representing the SDK version. The string is expected - to be a '.'-separated triple representing <major>.<minor>.<build>. If - this argument is None, then the default is the value returned by - build_utils.RawVersion() - - cwd: The current working directory. Various artifacts (such as the NSIS - installer) are expected to be in this directory. Defaults to the - script's directory. - - toolchain_manifests: A dictionary of manifests for things in the - toolchain directory. The dictionary can have these keys: - 'files': a set of plain files - 'dirs': a set of directories - 'symlinks': a dictionary of symbolic links - 'links': a dictionary of hard links. - For more details on these sets and dictionaries, please see the - tar_archive module. - ''' - if not sdk_version: - sdk_version = build_utils.RawVersion() - sdk_full_name = 'native_client_sdk_%s' % sdk_version.replace('.', '_') - - if not cwd: - cwd = os.path.abspath(os.path.dirname(__file__)) - - install_nsis.Install(cwd) - script = nsis_script.NsisScript(os.path.join(cwd, 'make_sdk_installer.nsi')) - script.install_dir = os.path.join('C:%s' % os.sep, sdk_full_name) - script.InitFromDirectory(installer_dir) - if toolchain_manifests: - toolchain_manifests.PrependPath(installer_dir) - script |= toolchain_manifests - script.Compile() diff --git a/native_client_sdk/src/build_tools/make_sdk_installer.nsi b/native_client_sdk/src/build_tools/make_sdk_installer.nsi deleted file mode 100644 index 9cae0af..0000000 --- a/native_client_sdk/src/build_tools/make_sdk_installer.nsi +++ /dev/null @@ -1,103 +0,0 @@ -!include "FileFunc.nsh" -!include "LogicLib.nsh" -!include "MUI2.nsh" -!include "Sections.nsh" -!include "x64.nsh" - -RequestExecutionLevel user -SetCompressor /solid lzma -SetCompressorDictSize 128 -Name "Native Client SDK" -OutFile ../../nacl-sdk.exe - -; The full SDK install name is generated from the version string. -!include sdk_install_name.nsh - -Var SVV_CmdLineParameters -Var SVV_SelChangeInProgress - -!define MUI_HEADERIMAGE -!define MUI_WELCOMEFINISHPAGE_BITMAP \ - "${NSISDIR}\Contrib\Graphics\Wizard\win.bmp" - -!define MUI_WELCOMEPAGE_TITLE "Welcome to the Native Client SDK Setup Wizard" -!define MUI_WELCOMEPAGE_TEXT "This wizard will guide you through the \ -installation of the Native Client SDK $\r$\n$\r$\nThe Native Client SDK \ -includes a GNU toolchain adopted for Native Client use and some examples. You \ -need Google Chrome to test the examples.$\r$\n$\r$\nYou will also need to \ -install Python (please visit www.python.org/download)$\r$\n$\r$\n$_CLICK" - -!define MUI_COMPONENTSPAGE_SMALLDESC - -!insertmacro MUI_PAGE_WELCOME -!insertmacro MUI_PAGE_COMPONENTS -!insertmacro MUI_PAGE_DIRECTORY -!insertmacro MUI_PAGE_INSTFILES - -!define MUI_FINISHPAGE_LINK \ - "Visit the Native Client site for news, FAQs and support" -!define MUI_FINISHPAGE_LINK_LOCATION \ - "http://code.google.com/chrome/nativeclient" - -!define MUI_FINISHPAGE_SHOWREADME -!define MUI_FINISHPAGE_SHOWREADME_TEXT "Show release notes" -!define MUI_FINISHPAGE_SHOWREADME_FUNCTION ShowReleaseNotes - -!insertmacro MUI_PAGE_FINISH - -!insertmacro MUI_LANGUAGE "English" - -Section "" sec_Preinstall - Push $R0 - CreateDirectory "$INSTDIR" - ; Owner can do anything - AccessControlW::GrantOnFile "$INSTDIR" "(S-1-3-0)" "FullAccess" - ; Group can read - AccessControlW::GrantOnFile "$INSTDIR" "(S-1-3-1)" "Traverse + GenericRead" - ; "Everyone" can read too - AccessControlW::GrantOnFile "$INSTDIR" "(S-1-1-0)" "Traverse + GenericRead" - FileClose $R0 - Pop $R0 -SectionEnd - -; The SDK Section commands are in a generated file. -!include sdk_section.nsh - -!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN - !insertmacro MUI_DESCRIPTION_TEXT \ - ${NativeClientSDK} \ - "Native Client SDK - toolchain and examples" -!insertmacro MUI_FUNCTION_DESCRIPTION_END - -Function .onInit - ${GetParameters} $SVV_CmdLineParameters - Push $R0 - ClearErrors - ${GetOptions} $SVV_CmdLineParameters "/?" $R0 - IfErrors +1 HelpMessage - ${GetOptions} $SVV_CmdLineParameters "--help" $R0 - IfErrors +3 +1 -HelpMessage: - MessageBox MB_OK "Recognized common options:$\n \ - /D=InstDir - use InstDir as target instead of usual $INSTDIR$\n \ - /NCRC - disables the CRC check$\n \ - /S - Silent install" - Abort - Pop $R0 -FunctionEnd - -Function .onSelChange - ${If} $SVV_SelChangeInProgress == 0 - StrCpy $SVV_SelChangeInProgress 1 - Push $R0 - IntOp $R0 ${SF_SELECTED} | ${SF_BOLD} - SectionSetFlags ${NativeClientSDK} $R0 - Pop $R0 - StrCpy $SVV_SelChangeInProgress 0 - ${EndIf} -FunctionEnd - -Function ShowReleaseNotes - ExecShell "open" \ - "http://code.google.com/chrome/nativeclient/docs/releasenotes.html" -FunctionEnd diff --git a/native_client_sdk/src/build_tools/make_sdk_tools.py b/native_client_sdk/src/build_tools/make_sdk_tools.py deleted file mode 100755 index 5339fe9..0000000 --- a/native_client_sdk/src/build_tools/make_sdk_tools.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Create the base (auto)updater for the Native Client SDK""" - -import py_compile -import optparse -import os -import shutil -import sys -import tarfile -import zipfile - -from build_tools.sdk_tools import update_manifest -from build_tools.sdk_tools import sdk_update - -NACL_SDK = 'nacl_sdk' - - -def ZipDirectory(dirpath, zippath): - '''Create a zipfile from the contents of a given directory. - - The path of the resulting contents in the zipfile will match that of the - last directory name in dirpath. - - Args: - dirpath: Path to directory to add to zipfile - zippath: filename of resulting zipfile - ''' - zip = None - try: - zip = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED) - basedir = '%s%s' % (os.path.dirname(dirpath), os.sep) - for root, dirs, files in os.walk(dirpath): - if os.path.basename(root)[0] == '.': - continue # skip hidden directories - dirname = root.replace(basedir, '') - for file in files: - zip.write(os.path.join(root, file), os.path.join(dirname, file)) - finally: - if zip: - zip.close() - - -def WriteTarFile(outname, in_dir, tar_dir=''): - '''Create a new compressed tarball from a given directory - - Args: - outname: path and filename of the gzipped tar file - in_dir: source directory that will be tar'd and gzipped - tar_dir: root directory within the tarball''' - tar_file = None - try: - tar_file = tarfile.open(outname, 'w:gz') - tar_file.add(in_dir, tar_dir) - finally: - if tar_file: - tar_file.close() - - -def MakeSdkTools(nacl_sdk_filename, sdk_tools_filename): - '''Make the nacl_sdk and sdk_tools tarballs - - The nacl_sdk package contains these things: - - nacl_sdk/ - naclsdk(.bat) - The main entry point for updating the SDK - sdk_tools/ - sdk_update.py - Performs the work in checking for updates - python/ - python.exe - (optional) python executable, shipped with Windows - ... - other python files and directories - sdk_cache/ - naclsdk_manifest.json - manifest file with information about sdk_tools - - Args: - nacl_sdk_filename: name of zipfile that the user directly downloads - sdk_tools_filename: name of tarball that has the sdk_tools directory - ''' - base_dir = os.path.abspath(os.path.dirname(__file__)) - base_dir_parent = os.path.dirname(base_dir) - temp_dir = os.path.join(base_dir, NACL_SDK) - if os.path.exists(temp_dir): - shutil.rmtree(temp_dir) - os.mkdir(temp_dir) - for dir in ['sdk_tools', 'sdk_cache']: - os.mkdir(os.path.join(temp_dir, dir)) - shutil.copy2(os.path.join(base_dir, 'naclsdk'), temp_dir) - shutil.copy2(os.path.join(base_dir, 'naclsdk.bat'), temp_dir) - with open(os.path.join(base_dir_parent, 'LICENSE'), "U") as source_file: - text = source_file.read().replace("\n", "\r\n") - with open(os.path.join(temp_dir, 'sdk_tools', 'LICENSE'), "wb") as dest_file: - dest_file.write(text) - - tool_list = ['sdk_update.py', 'set_nacl_env.py'] - for tool in tool_list: - shutil.copy2(os.path.join(base_dir, 'sdk_tools', tool), - os.path.join(temp_dir, 'sdk_tools')) - py_compile.compile(os.path.join(temp_dir, 'sdk_tools', tool)) - - update_manifest_options = [ - '--bundle-revision=%s' % sdk_update.MINOR_REV, - '--bundle-version=%s' % sdk_update.MAJOR_REV, - '--description=Native Client SDK Tools, revision %s.%s' % ( - sdk_update.MAJOR_REV, sdk_update.MINOR_REV), - '--bundle-name=sdk_tools', - '--recommended=yes', - '--stability=stable', - '--manifest-version=%s' % sdk_update.SDKManifest().MANIFEST_VERSION, - '--manifest-file=%s' % - os.path.join(temp_dir, 'sdk_cache', 'naclsdk_manifest.json')] - if 0 != update_manifest.main(update_manifest_options): - raise Exception('update_manifest terminated abnormally.') - ZipDirectory(temp_dir, nacl_sdk_filename) - WriteTarFile(sdk_tools_filename, os.path.join(temp_dir, 'sdk_tools'), '') - shutil.rmtree(temp_dir, ignore_errors=True) - - -def main(argv): - parser = optparse.OptionParser() - parser.add_option( - '-n', '--nacl-sdk', dest='nacl_sdk', default='nacl_sdk.zip', - help='name of the resulting nacl_sdk zipfile') - parser.add_option( - '-s', '--sdk-tools', dest='sdk_tools', default='sdk_tools.tgz', - help='name of the resulting sdk_tools tarball') - (options, args) = parser.parse_args(argv) - MakeSdkTools(options.nacl_sdk, options.sdk_tools) - return 0 - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/__init__.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/__init__.py deleted file mode 100644 index 2424608..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""build_tools/nacl_sdk_scons Package - -This package contains general python scons utilities that are used for -creating the Native Client SDK.""" diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/make_nacl_env.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/make_nacl_env.py deleted file mode 100644 index 7d0f530..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/make_nacl_env.py +++ /dev/null @@ -1,205 +0,0 @@ -# -*- python -*- -# -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -'''Construct an Environment that uses the NaCl toolchain to build C/C++ code. -The base dir for the NaCl toolchain is in the NACL_SDK_ROOT environment -variable. -''' - -import nacl_utils -import os - -from SCons import Script - -def NaClEnvironment(use_c_plus_plus_libs=False, - nacl_platform=None, - toolchain_arch=None, - toolchain_variant=None, - use_ppapi=True, - install_subdir=None, - lib_prefix=None): - '''Make an Environment that uses the NaCl toolchain to build sources. - - This modifies a default construction Environment to point the compilers and - other bintools at the NaCl-specific versions, adds some tools that set certain - build flags needed by the NaCl-specific tools, and adds a custom Builder that - generates .nmf files. - - Args: - use_c_plus_plus_libs: Indicate whether to insert the C++ NaCl libs at the - right place in the list of LIBS. - nacl_platform: The target NaCl/Chrome/Papper platform for which the - environment, e.g. 'pepper_14'. - toolchain_arch: The target architecture of the toolchain (e.g., x86, pnacl) - toolchain_variant: The libc of the toolchain (e.g., newlib, glibc) - use_ppapi: flag indicating whether to compile again ppapi libraries - install_subdir: subdirectory within the NACL_INSTALL_ROOT for this project. - lib_prefix: an optional list of path components to prepend to the library - path. These components are joined with appropriate path separators - Examples: ['..', '..'], ['..', 'peer_directory']. - Returns: - A SCons Environment with all the various Tool and keywords set to build - NaCl modules. - ''' - - def GetCommandLineOption(option_name, option_value, option_default): - '''Small helper function to get a command line option. - - Returns a command-line option value, which can be overridden. If the - option is set on the command line, then that value is favoured over the - internally set value. If option is neither set on the command line nor - given a value, its default is used. - - Args: - option_name: The name of the command line option, e.g. "variant". - option_value: The initial value of the option. This value is used if the - its not set via the command line. Can be None. - option_default: If the option value hasn't been set via the command line - nor via an internal value, then this default value is used. Can be - None. - - Returns: - The value of the command-line option, according to the override rules - described above. - ''' - cmd_line_value = Script.GetOption(option_name) - if not cmd_line_value and not option_value: - cmd_line_value = option_default - return cmd_line_value or option_value - - nacl_utils.AddCommandLineOptions() - env = Script.Environment() - - # We must have a nacl_platform, either as argument to this function or from - # the command line. However, if we're cleaning we can relax this requirement. - # (And our build bots will be much happier that way.) - nacl_platform_from_option = Script.GetOption('nacl_platform') - if not nacl_platform_from_option and not nacl_platform: - if Script.GetOption('clean'): - nacl_platform_from_option='.' - else: - raise ValueError('NaCl platform not specified') - - # Setup the base dir for tools, etc. Favor the nacl platform specified on - # the command line if there's a conflict. - nacl_platform_to_use = nacl_platform_from_option or nacl_platform - - toolchain_variant = GetCommandLineOption( - 'variant', toolchain_variant, nacl_utils.DEFAULT_TOOLCHAIN_VARIANT) - toolchain_arch = GetCommandLineOption( - 'architecture', toolchain_arch, nacl_utils.DEFAULT_TOOLCHAIN_ARCH) - - base_dir = os.getenv('NACL_SDK_ROOT', '') - base_dir = os.path.join(base_dir, nacl_platform_to_use) - toolchain = nacl_utils.ToolchainPath(base_dir=base_dir, - arch=toolchain_arch, - variant=toolchain_variant) - if (toolchain is None): - raise ValueError('Cannot find a NaCl toolchain') - - tool_bin_path = os.path.join(toolchain, 'bin') - tool_runtime_path = os.path.join(toolchain, 'runtime') - staging_dir = os.path.abspath(os.getenv( - 'NACL_INSTALL_ROOT', os.path.join(os.getenv('NACL_SDK_ROOT', '.'), - 'staging'))) - if install_subdir: - staging_dir = os.path.join(staging_dir, install_subdir) - lib_prefix = lib_prefix or [] - if type(lib_prefix) is not list: - # Break path down into list of directory components - lib_prefix = filter(lambda x:x, lib_prefix.split('/')) - - # Invoke the various *nix tools that the NativeClient SDK resembles. This - # is done so that SCons doesn't try to invoke cl.exe on Windows in the - # Object builder. - env.Tool('g++') - env.Tool('gcc') - env.Tool('gnulink') - env.Tool('ar') - env.Tool('as') - - env.Tool('nacl_tools') - # TODO(dspringer): Figure out how to make this dynamic and then compute it - # based on the desired target arch. - env.Replace(tools=['nacl_tools'], - # Replace the normal unix tools with the NaCl ones. Note the - # use of the NACL_ARCHITECTURE prefix for the tools. This - # Environment variable is set in nacl_tools.py; it has no - # default value. - CC=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}gcc'), - CXX=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}g++'), - AR=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}ar'), - AS=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}as'), - GDB=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}gdb'), - # NOTE: use g++ for linking so we can handle C AND C++. - LINK=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}g++'), - LD=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}ld'), - STRIP=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}strip'), - NACL_SEL_LDR32=os.path.join(tool_bin_path, 'sel_ldr_x86_32'), - NACL_IRT_CORE32=os.path.join(tool_runtime_path, - 'irt_core_x86_32.nexe'), - NACL_SEL_LDR64=os.path.join(tool_bin_path, 'sel_ldr_x86_64'), - NACL_IRT_CORE64=os.path.join(tool_runtime_path, - 'irt_core_x86_64.nexe'), - RANLIB=os.path.join(tool_bin_path, '${NACL_ARCHITECTURE}ranlib'), - ASFLAGS=['${EXTRA_ASFLAGS}', - ], - # c specific - EXTRA_CFLAGS=[], - CFLAGS=['${EXTRA_CFLAGS}', - '-std=gnu99', - ], - # c++ specific - EXTRA_CXXFLAGS=[], - CXXFLAGS=['${EXTRA_CXXFLAGS}', - '-std=gnu++98', - '-Wno-long-long', - ], - # Both C and C++ - CCFLAGS=['${EXTRA_CCFLAGS}', - '-Wall', - '-Wswitch-enum', - '-pthread', - ], - CPPDEFINES=[# _GNU_SOURCE ensures that strtof() gets declared. - ('_GNU_SOURCE', 1), - # This ensures that PRId64 etc. get defined. - ('__STDC_FORMAT_MACROS', '1'), - # strdup, and other common stuff - ('_BSD_SOURCE', '1'), - ('_POSIX_C_SOURCE', '199506'), - ('_XOPEN_SOURCE', '600'), - ], - CPPPATH=[], - LINKFLAGS=['${EXTRA_LINKFLAGS}', - ], - # The NaCl environment makes '.nexe' executables. If this is - # not explicitly set, then SCons on Windows doesn't understand - # how to construct a Program builder properly. - PROGSUFFIX='.nexe', - # Target NaCl platform info. - TARGET_NACL_PLATFORM=nacl_platform_to_use, - NACL_TOOLCHAIN_VARIANT=toolchain_variant, - NACL_TOOLCHAIN_ROOT=toolchain, - NACL_INSTALL_ROOT=staging_dir, - NACL_LIB_PREFIX=lib_prefix, - ) - # This supresses the "MS_DOS style path" warnings on Windows. It's benign on - # all other platforms. - env['ENV']['CYGWIN'] = 'nodosfilewarning' - - # Append the common NaCl libs. - if use_ppapi: - common_nacl_libs = ['ppapi'] - if use_c_plus_plus_libs: - common_nacl_libs.extend(['ppapi_cpp']) - env.Append(LIBS=common_nacl_libs) - - gen_nmf_builder = env.Builder(suffix='.nmf', - action=nacl_utils.GenerateNmf) - env.Append(BUILDERS={'GenerateNmf': gen_nmf_builder}) - - return env diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils.py deleted file mode 100644 index d82cad4..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils.py +++ /dev/null @@ -1,495 +0,0 @@ -# -*- python -*- -# -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -'''Small utility library of python functions used by the various helper -scripts. -''' -# Needed for Python 2.5 -- Unnecessary (but harmless) for 2.6 -from __future__ import with_statement - -import optparse -import os -import sys - -from SCons import Script -from site_tools import create_nmf - -#------------------------------------------------------------------------------ -# Parameters - -# The newlib toolchain variant. .nexes built with this variant require a -# different manifest file format than those built with glibc. -NEWLIB_TOOLCHAIN_VARIANT = 'newlib' - -# The default toolchain architecture. -DEFAULT_TOOLCHAIN_ARCH = 'x86' - -# The default toolchain variant. -DEFAULT_TOOLCHAIN_VARIANT = NEWLIB_TOOLCHAIN_VARIANT - -# Map the string stored in |sys.platform| into a toolchain host specifier. -# @private -__PLATFORM_TO_HOST_MAP = { - 'win32': 'windows', - 'cygwin': 'windows', - 'linux2': 'linux', - 'darwin': 'mac' -} - -# Map a platform host to a map of possible architectures and toolchains. -# The platform host can be derived from sys.platform using |PLATFORM_HOST_MAP_}| -# (see above). (Note: if this map changes, you must also update the copy in -# set_nacl_env.py.) -# TODO(gwink): This map is duplicated in set_nacl_env.py. Find a good way to -# share it instead. -# @private -__HOST_TO_TOOLCHAIN_MAP = { - 'windows': { - 'x86': { - 'glibc': 'win_x86', - 'newlib': 'win_x86_newlib', - }, - }, - 'linux': { - 'x86': { - 'glibc': 'linux_x86', - 'newlib': 'linux_x86_newlib', - }, - 'pnacl': { - 'newlib-32': 'pnacl_linux_i686_newlib', - 'newlib-64': 'pnacl_linux_x86_64_newlib', - 'glibc-64': 'pnacl_linux_x86_64_glibc', - }, - 'arm': { - 'newlib': 'pnacl_linux_x86_64_newlib', - 'glibc': 'pnacl_linux_x86_64_glibc', - }, - }, - 'mac': { - 'x86': { - 'glibc': 'mac_x86', - 'newlib': 'mac_x86_newlib', - }, - 'pnacl': { - 'newlib': 'pnacl_darwin_i386_newlib', - }, - }, -} - -# Various architecture spec objects suitable for use with -# nacl_env_ext.SetArchFlags() -ARCH_SPECS = { - 'x86-32': { - 'arch': 'x86', - 'subarch': '32' - }, - 'x86-64': { - 'arch': 'x86', - 'subarch': '64' - }, - 'arm': { - 'arch': 'ARM', - 'subarch': '' - } -} - -# Default values for 'arch' and 'subarch'. -DEFAULT_ARCH = 'x86' -DEFAULT_SUBARCH = '32' - -#------------------------------------------------------------------------------ -# Functions - -def AddCommandLineOptions(): - '''Register the cmd-line options. - - Registers --nacl-platform, --architecture and --variant. This function can be - called multiple times. Only the first call registers the option. - - Args: - None - - Returns: - None - ''' - - try: - Script.AddOption( - '--nacl-platform', - dest='nacl_platform', - nargs=1, - type='string', - action='store', - help='target pepper version') - Script.Help(' --nacl-platform ' - 'Specify the pepper version to build for ' - '(e.g. --nacl-platform="pepper_14").\n') - - Script.AddOption( - '--architecture', - dest='architecture', - nargs=1, - type='string', - action='store', - help='NaCl target architecture') - Script.Help(' --architecture ' - 'Specify the NaCl target architecture to build (e.g. ' - '--architecture="glibc"). Possible values are "x86", "pnacl" ' - '"arm". Not all target architectures are available on all ' - 'host platforms. Defaults to "x86"\n') - - Script.AddOption( - '--variant', - dest='variant', - nargs=1, - type='string', - action='store', - help='NaCl toolchain variant') - Script.Help(' --variant ' - 'Specify the NaCl toolchain variant to use when ' - 'building (e.g. --variant="glibc"). Possible values are ' - '"glibc", "newlib"; when --architecture=pnacl is specified, ' - 'values must include bit-width, e.g. "glibc-64". Defaults to ' - '"newlib"\n') - - except optparse.OptionConflictError: - pass - - -def PrintNaclPlatformBanner(module_name, nacl_platform, variant): - '''Print a banner that shows what nacl platform is used to build a module. - - Args: - module_name: The name of the module. Printed as-is. - nacl_platform: The name - a.k.a. folder name - of the nacl platform. - Printed as-is. - variant: The toolchain variant, one of 'newlib', 'glibc', 'pnacl', etc. - Returns: - None - ''' - - # Don't print the banner if we're just cleaning files. - if not Script.GetOption('clean'): - print '---------------------------------------------------------------' - print ('+ Project "%s" is using NaCl platform "%s", toolchain "%s"' % - (module_name, nacl_platform, variant)) - print '---------------------------------------------------------------' - print '' - sys.stdout.flush() - - -def ToolchainPath(base_dir=None, - arch=DEFAULT_TOOLCHAIN_ARCH, - variant=DEFAULT_TOOLCHAIN_VARIANT): - '''Build a toolchain path based on the platform type. - - |base_dir| is the root directory which includes the platform-specific - toolchain. This could be something like "/usr/local/mydir/nacl_sdk/src". If - |base_dir| is None, then the environment variable NACL_SDK_ROOT is used (if - it's set). This method assumes that the platform-specific toolchain is found - under <base_dir>/toolchain/<platform_spec>. - - Args: - base_dir: The pathname of the root directory that contains the toolchain. - The toolchain is expected to be in a dir called 'toolchain' - within |base_dir|. - variant: The toolchain variant, can be one of 'newlib', 'glibc', etc. - Defaults to 'newlib'. - Returns: - The concatenated platform-specific path to the toolchain. This will look - like base_dir/toolchain/mac_x86 - ''' - - if base_dir is None: - base_dir = os.getenv('NACL_SDK_ROOT', '') - if sys.platform in __PLATFORM_TO_HOST_MAP: - host_platform = __PLATFORM_TO_HOST_MAP[sys.platform] - toolchain_map = __HOST_TO_TOOLCHAIN_MAP[host_platform] - if arch in toolchain_map: - isa_toolchain = toolchain_map[arch] - if variant in isa_toolchain: - return os.path.normpath(os.path.join( - base_dir, 'toolchain', isa_toolchain[variant])) - else: - raise ValueError('ERROR: Variant "%s" not in toolchain "%s/%s".' % - (variant, host_platform, arch)) - else: - raise ValueError('ERROR: Architecture "%s" not supported on host "%s".' % - (arch, host_platform)) - - else: - raise ValueError('ERROR: Unsupported host platform "%s".' % sys.platform) - - -def GetJSONFromNexeSpec(nexe_spec): - '''Generate a JSON string that represents the architecture-to-nexe mapping - in |nexe_spec|. - - The nexe spec is a simple dictionary, whose keys are architecture names and - values are the nexe files that should be loaded for the corresponding - architecture. For example: - {'x86-32': 'hello_world_x86_32.nexe', - 'x86-64': 'hello_world_x86_64.nexe', - 'arm': 'hello_world_ARM.nexe'} - - Args: - nexe_spec: The dictionary that maps architectures to .nexe files. - Returns: - A JSON string representing |nexe_spec|. - ''' - nmf_json = '{\n' - nmf_json += ' "program": {\n' - - # Add an entry in the JSON for each specified architecture. Note that this - # loop emits a trailing ',' for every line but the last one. - if nexe_spec and len(nexe_spec): - line_count = len(nexe_spec) - for arch_key in nexe_spec: - line_count -= 1 - eol_char = ',' if line_count > 0 else '' - nmf_json += ' "%s": {"url": "%s"}%s\n' % (arch_key, - nexe_spec[arch_key], - eol_char) - - nmf_json += ' }\n' - nmf_json += '}\n' - return nmf_json - - -def GenerateNmf(target, source, env): - '''This function is used to create a custom Builder that produces .nmf files. - - The .nmf files are given in the list of targets. This expects the .nexe - mapping to be given as the value of the 'nexes' keyword in |env|. To add - this function as a Builder, use this SCons code: - gen_nmf_builder = nacl_env.Builder(suffix='.nmf', - action=nacl_utils.GenerateNmf) - nacl_env.Append(BUILDERS={'GenerateNmf': gen_nmf_builder}) - To invoke the Builder, do this, for example: - # See examples/hello_world/build.scons for more details. - hello_world_opt_nexes = [nacl_env.NaClProgram(....), ....] - nacl_env.GenerateNmf(target='hello_world.nmf', - source=hello_world_opt_nexes, - nexes={'x86-32': 'hello_world_x86_32.nexe', - 'x86-64': 'hello_world_x86_64.nexe', - 'arm': 'hello_world_ARM.nexe'}) - - A Builder that invokes this function is added to the NaCl Environment by - the NaClEnvironment() function in make_nacl_env.py - - Args: - target: The list of targets to build. This is expected to be a list of - File Nodes that point to the required .nmf files. - source: The list of sources that the targets depend on. This is typically - a list of File Nodes that represent .nexes - env: The SCons construction Environment that provides the build context. - Returns: - None on success. Raises a ValueError() if there are missing parameters, - such as the 'nexes' keyword in |env|. - ''' - - if target == None or source == None: - raise ValueError('No value given for target or source.') - - nexes = env.get('nexes', []) - if len(nexes) == 0: - raise ValueError('No value for "nexes" keyword.') - - for target_file in target: - # If any of the following functions raises an exception, just let the - # exception bubble up to the calling context. This will produce the - # correct SCons error. - target_path = target_file.get_abspath() - if env['NACL_TOOLCHAIN_VARIANT'] == NEWLIB_TOOLCHAIN_VARIANT: - nmf_json = GetJSONFromNexeSpec(nexes) - else: - nmf = create_nmf.NmfUtils( - objdump=os.path.join(env['NACL_TOOLCHAIN_ROOT'], 'bin', - 'x86_64-nacl-objdump'), - main_files=[str(file) for file in source], - lib_path=[os.path.join(env['NACL_TOOLCHAIN_ROOT'], 'x86_64-nacl', dir) - for dir in ['lib', 'lib32']], - lib_prefix=env['NACL_LIB_PREFIX']) - nmf_json = nmf.GetJson() - if env.get('NACL_INSTALL_ROOT', None): - nmf.StageDependencies(env['NACL_INSTALL_ROOT']) - with open(target_path, 'w') as nmf_file: - nmf_file.write(nmf_json) - - # Return None to indicate success. - return None - - -def GetArchFromSpec(arch_spec): - '''Pick out the values for 'arch' and 'subarch' from |arch_spec|, providing - default values in case nothing is specified. - - Args: - arch_spec: An object that can have keys 'arch' and 'subarch'. - Returns: - A tuple (arch, subarch) that contains either the values of the - corresponding keys in |arch_spec| or a default value. - ''' - if arch_spec == None: - return (DEFAULT_ARCH, DEFAULT_SUBARCH) - arch = arch_spec.get('arch', DEFAULT_ARCH) - subarch = arch_spec.get('subarch', DEFAULT_SUBARCH) - return (arch, subarch) - - -def GetArchName(arch_spec): - ''' Return a name of the form arch_subarch for the given arch spec. - - Args: - arch_spec: An object containing 'arch' and 'subarch' keys that describe - the instruction set architecture of the output program. See - |ARCH_SPECS| in nacl_utils.py for valid examples. - - Returns: - A string with the arch name. - ''' - return '%s_%s' % GetArchFromSpec(arch_spec) - - -def MakeNaClCommonEnvironment(nacl_env, - arch_spec=ARCH_SPECS['x86-32'], - is_debug=False): - '''Make a clone of nacl_env that is suitable for building programs or - libraries for a specific build variant. - - Make a cloned NaCl Environment and setup variables for options like optimized - versus debug CCFLAGS. - - Args: - nacl_env: A SCons construction environment. This is typically the return - value of NaClEnvironment() (see above). - arch_spec: An object containing 'arch' and 'subarch' keys that describe - the instruction set architecture of the output program. See - |ARCH_SPECS| in nacl_utils.py for valid examples. - is_debug: Indicates whether this program should be built for debugging or - optimized. - - Returns: - A SCons Environment setup with options for the specified variant of a NaCl - module or library. - ''' - arch_name = GetArchName(arch_spec) - env = nacl_env.Clone() - env.AppendOptCCFlags(is_debug) - env.AppendArchFlags(arch_spec) - - # Wrap linker command with TEMPFILE so that if lines are longer than - # MAXLINELENGTH, the tools will be run with @tmpfile. This isn't needed - # for any of the sdk examples, but if people cargo cult them for other - # purposes, they can end up hitting command line limits on Windows where - # MAXLINELENGTH can be as low as 2048. - env['LINKCOM'] = '${TEMPFILE("' + env['LINKCOM'] + '")}' - env['SHLINKCOM'] = '${TEMPFILE ' + env['SHLINKCOM'] + '")}' - - return env - - -def MakeNaClModuleEnvironment(nacl_env, - sources, - module_name='nacl', - arch_spec=ARCH_SPECS['x86-32'], - is_debug=False, - build_dir_prefix=''): - '''Make a NaClProgram Node for a specific build variant. - - Make a NaClProgram Node in a cloned Environment. Set the environment - in the cloned Environment variables for things like optimized versus debug - CCFLAGS, and also adds a Program builder that makes a NaCl module. The name - of the module is derived from |module_name|, |arch_spec| and |is_debug|; for - example: - MakeNaClModuleEnvironment(nacl_env, sources, module_name='hello_world', - arch_spec=nacl_utils.ARCH_SPECS['x86-64'], is_debug=True) - will produce a NaCl module named - hello_world_x86_64_dbg.nexe - - Args: - nacl_env: A SCons construction environment. This is typically the return - value of NaClEnvironment() (see above). - sources: A list of source Nodes used to build the NaCl module. - module_name: The name of the module. The name of the output program - incorporates this as its prefix. - arch_spec: An object containing 'arch' and 'subarch' keys that describe - the instruction set architecture of the output program. See - |ARCH_SPECS| in nacl_utils.py for valid examples. - is_debug: Indicates whether this program should be built for debugging or - optimized. - build_dir_prefix: Allows user to prefix the build directory with an - additional string. - - Returns: - A SCons Environment that builds the specified variant of a NaCl module. - ''' - debug_name = 'dbg' if is_debug else 'opt' - arch_name = GetArchName(arch_spec) - env = MakeNaClCommonEnvironment(nacl_env, arch_spec, is_debug) - return env.NaClProgram('%s_%s%s' % (module_name, - arch_name, - '_dbg' if is_debug else ''), - sources, - variant_dir='%s%s_%s' % - (build_dir_prefix, debug_name, arch_name)) - - -def MakeNaClStaticLibEnvironment(nacl_env, - sources, - lib_name='nacl', - arch_spec=ARCH_SPECS['x86-32'], - is_debug=False, - build_dir_prefix='', - lib_dir=''): - '''Make a NaClStaticLib Node for a specific build variant. - - Make a NaClStaticLib Node in a cloned Environment. Set the environment - in the cloned Environment variables for things like optimized versus debug - CCFLAGS, and also adds a Program builder that makes a NaCl static library. - The name of the library is derived from |lib_name|, |arch_spec| and - |is_debug|; for example: - MakeNaClStaticLibEnvironment(nacl_env, sources, lib_name='c_salt', - arch_spec=nacl_utils.ARCH_SPECS['x86-64'], is_debug=True) - will produce a NaCl static library named - libc_salt_x86_64_dbg.a - - Args: - nacl_env: A SCons construction environment. This is typically the return - value of NaClEnvironment() (see above). - sources: A list of source Nodes used to build the NaCl library. - lib_name: The name of the library. - arch_spec: An object containing 'arch' and 'subarch' keys that describe - the instruction set architecture of the output program. See - |ARCH_SPECS| in nacl_utils.py for valid examples. - is_debug: Indicates whether this program should be built for debugging or - optimized. - build_dir_prefix: Allows user to prefix the build directory with an - additional string. - lib_dir: Where to output the final library file. Lib files are placed in - directories within lib_dir, based on the arch type and build type. - E.g. Specifying lib_dir = 'dest' for lib name 'c_salt' on x86-32 debug - creates the library file 'dest/lib-x86-32/dbg/libc_salt.a' - - Returns: - A SCons Environment that builds the specified variant of a NaCl module. - ''' - env = MakeNaClCommonEnvironment(nacl_env, arch_spec, is_debug) - debug_name = 'dbg' if is_debug else 'opt' - arch_name = GetArchName(arch_spec) - target_name = '%s_%s%s' % (lib_name, arch_name, debug_name) - variant_dir = '%s%s_%s' % (build_dir_prefix, debug_name, arch_name) - - arch, subarch = GetArchFromSpec(arch_spec) - lib_subdir = 'lib-' + arch - if subarch: lib_subdir = lib_subdir + '-' + subarch - lib_dir = os.path.join(lib_dir, lib_subdir, debug_name) - - return env.NaClStaticLib(target_name, - sources, - variant_dir, - lib_name, - lib_dir) diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils_test.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils_test.py deleted file mode 100755 index 3cf82b7..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils_test.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for nacl_utils.py.""" - -import fileinput -import mox -import nacl_utils -import os -import sys -import unittest - - -def TestMock(file_path, open_func): - temp_file = open_func(file_path) - temp_file.close() - - -class TestNaClUtils(unittest.TestCase): - """Class for test cases to cover globally declared helper functions.""" - - def setUp(self): - self.script_dir = os.path.abspath(os.path.dirname(__file__)) - self.mock_factory = mox.Mox() - self.InitializeResourceMocks() - - def InitializeResourceMocks(self): - """Can be called multiple times if multiple functions need to be tested.""" - self.fileinput_mock = self.mock_factory.CreateMock(fileinput) - self.os_mock = self.mock_factory.CreateMock(os) - self.sys_mock = self.mock_factory.CreateMock(sys) - - def testToolchainPath(self): - output = nacl_utils.ToolchainPath('nacl_sdk_root') - head, tail = os.path.split(output) - base, toolchain = os.path.split(head) - self.assertEqual('nacl_sdk_root', base) - self.assertEqual('toolchain', toolchain) - self.assertRaises(ValueError, - nacl_utils.ToolchainPath, - 'nacl_sdk_root', - arch='nosucharch') - self.assertRaises(ValueError, - nacl_utils.ToolchainPath, - 'nacl_sdk_root', - variant='nosuchvariant') - - def testGetJSONFromNexeSpec(self): - valid_empty_json = '{\n "program": {\n }\n}\n' - null_json = nacl_utils.GetJSONFromNexeSpec(None) - self.assertEqual(null_json, valid_empty_json) - empty_json = nacl_utils.GetJSONFromNexeSpec({}) - self.assertEqual(empty_json, valid_empty_json) - nexes = {'x86-32': 'nacl_x86_32.nexe', - 'x86-64': 'nacl_x86_64.nexe', - 'arm': 'nacl_ARM.nexe'} - json = nacl_utils.GetJSONFromNexeSpec(nexes) - # Assert that the resulting JSON has all the right parts: the "nexes" - # dict, followed by one entry for each architecture. Also make sure that - # the last entry doesn't have a trailing ',' - json_lines = json.splitlines() - self.assertEqual(len(json_lines), 7) - self.assertEqual(json_lines[0], '{') - self.assertEqual(json_lines[1], ' "program": {') - self.assertTrue(json_lines[2].endswith(',')) - self.assertTrue(json_lines[3].endswith(',')) - self.assertFalse(json_lines[4].endswith(',')) - self.assertEqual(json_lines[5], ' }') - self.assertEqual(json_lines[6], '}') - # Assert that the key-value pair lines have the right form. The order - # of the keys doesn't matter. Note that the key values are enclosed in - # "" (e.g. "x86-32") - this is intentional. - valid_arch_keys = ['"x86-32"', '"x86-64"', '"arm"'] - for line in json_lines[2:4]: - key_value = line.split(':') - self.assertEqual(len(key_value), 3) - self.assertTrue(key_value[0].lstrip().rstrip() in valid_arch_keys) - - def testGenerateNmf(self): - # Assert that failure cases properly fail. - self.assertRaises(ValueError, nacl_utils.GenerateNmf, None, None, None) - self.assertRaises(ValueError, nacl_utils.GenerateNmf, [], [], {}) - - def testGetArchFromSpec(self): - default_arch, default_subarch = nacl_utils.GetArchFromSpec(None) - self.assertEqual(default_arch, nacl_utils.DEFAULT_ARCH) - self.assertEqual(default_subarch, nacl_utils.DEFAULT_SUBARCH) - default_arch, subarch = nacl_utils.GetArchFromSpec({'subarch': '64'}) - self.assertEqual(default_arch, nacl_utils.DEFAULT_ARCH) - self.assertEqual(subarch, '64') - arch, default_subarch = nacl_utils.GetArchFromSpec({'arch': 'x86'}) - self.assertEqual(arch, 'x86') - self.assertEqual(default_subarch, nacl_utils.DEFAULT_SUBARCH) - arch, subarch = nacl_utils.GetArchFromSpec({'arch': 'x86', 'subarch': '64'}) - self.assertEqual(arch, 'x86') - self.assertEqual(subarch, '64') - - -def RunTests(): - return_value = 1 - test_suite = unittest.TestLoader().loadTestsFromTestCase(TestNaClUtils) - test_results = unittest.TextTestRunner(verbosity=2).run(test_suite) - if test_results.wasSuccessful(): - return_value = 0 - return return_value - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/nmf_test.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/nmf_test.py deleted file mode 100755 index cf03ee5..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/nmf_test.py +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for nmf.py.""" - -import exceptions -import json -import optparse -import os -import subprocess -import sys -import tempfile -import unittest - -from build_tools import build_utils -from build_tools.nacl_sdk_scons.site_tools import create_nmf - -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -X86_32 = 'x86-32' -X86_64 = 'x86-64' -ARCHS = [X86_32, X86_64] - - -def CallCreateNmf(args): - '''Calls the create_nmf.py utility and returns stdout as a string - - Args: - args: command-line arguments as a list (not including program name) - - Returns: - string containing stdout - - Raises: - subprocess.CalledProcessError: non-zero return code from sdk_update''' - command = [sys.executable, os.path.join(SCRIPT_DIR, 'site_tools', - 'create_nmf.py')] + args - process = subprocess.Popen(stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - args=command) - output, error_output = process.communicate() - - retcode = process.poll() # Note - calling wait() can cause a deadlock - if retcode != 0: - print "\nCallCreateNmf(%s)" % command - print "stdout=%s\nstderr=%s" % (output, error_output) - sys.stdout.flush() - raise subprocess.CalledProcessError(retcode, command) - return output - - -def GlobalInit(options, temp_files): - '''Global initialization for testing nmf file creation. - - Args: - options: object containing gcc and gpp defines - files: (output) A list that will contain all generated nexes. Each - nexe is a value in a map, keyed by architecture. - - Returns: - A list of filemaps, where each filemap is a dict with key=architecture - and value=filename - ''' - hello_world_c = ( - '#include <stdio.h>\n' - 'int main(void) { printf("Hello World!\\n"); return 0; }\n') - hello_world_cc = ( - '#include <iostream>\n' - 'int main(void) { std::cout << "Hello World!\\n"; return 0; }\n') - - files = [] - def MakeNexe(contents, suffix, compiler): - file_map = {} - for arch in ARCHS: - source_filename = None - with tempfile.NamedTemporaryFile(delete=False, - suffix=suffix) as temp_file: - source_filename = temp_file.name - temp_files.append(source_filename) - temp_file.write(contents) - nexe_filename = os.path.splitext(source_filename)[0] + '.nexe' - file_map[arch] = nexe_filename - temp_files.append(nexe_filename) - subprocess.check_call([compiler, - '-m32' if arch == X86_32 else '-m64', - source_filename, - '-o', nexe_filename]) - files.append(file_map) - - c_file = MakeNexe(hello_world_c, '.c', options.gcc) - cc_file = MakeNexe(hello_world_cc, '.cc', options.gpp) - return files - - -def TestingClosure(toolchain_dir, file_map): - '''Closure to provide variables to the test cases - - Args: - toolchain_dir: path to toolchain that we are testing - file_map: dict of nexe files by architecture. - ''' - - class TestNmf(unittest.TestCase): - ''' Test basic functionality of the sdk_update package ''' - - def setUp(self): - self.objdump = (os.path.join(toolchain_dir, - 'bin', - 'x86_64-nacl-objdump')) - self.library_paths = [os.path.join(toolchain_dir, 'x86_64-nacl', lib) - for lib in ['lib32', 'lib']] - self.lib_options = ['--library-path=%s' % lib - for lib in self.library_paths] - - def testRunCreateNmf(self): - json_text = CallCreateNmf( - self.lib_options + ['--objdump', self.objdump] + file_map.values()) - obj = json.loads(json_text) - # For now, just do a simple sanity check that there is a file - # and program section. - self.assertTrue(obj.get('files')) - self.assertTrue(obj.get('program')) - for arch in ['x86-32', 'x86-64']: - self.assertEqual(obj['program'][arch]['url'], - '%s/runnable-ld.so' % arch) - self.assertEqual(obj['files']['main.nexe'][arch]['url'], - os.path.basename(file_map[arch])) - for filename, rest in obj['files'].items(): - if filename == 'main.nexe': - continue - self.assertEqual('/'.join([arch, filename]), - rest[arch]['url']) - - def testGenerateManifest(self): - nmf = create_nmf.NmfUtils( - objdump=self.objdump, - main_files=file_map.values(), - lib_path=self.library_paths) - nmf_json = nmf.GetManifest() - for arch in ['x86-32', 'x86-64']: - self.assertEqual(nmf_json['program'][arch]['url'], - '%s/runnable-ld.so' % arch) - self.assertEqual(nmf_json['files']['main.nexe'][arch]['url'], - os.path.basename(file_map[arch])) - for filename, rest in nmf_json['files'].items(): - if filename == 'main.nexe': - continue - self.assertEqual('/'.join([arch, filename]), - rest[arch]['url']) - - return TestNmf - - -def GlobalTeardown(temp_files): - '''Remove all the temporary files in temp_files''' - for filename in temp_files: - if os.path.exists(filename): - os.remove(filename) - - -def main(argv): - '''Usage: %prog [options] - - Runs the unit tests on the nmf utility''' - parser = optparse.OptionParser(usage=main.__doc__) - - parser.add_option( - '-t', '--toolchain-dir', dest='toolchain_dir', - help='(required) root directory of toolchain') - - (options, args) = parser.parse_args(argv) - - options.gcc = os.path.join(options.toolchain_dir, 'bin', 'x86_64-nacl-gcc') - options.gpp = os.path.join(options.toolchain_dir, 'bin', 'x86_64-nacl-g++') - options.objdump = os.path.join(options.toolchain_dir, 'bin', - 'x86_64-nacl-objdump') - - success = True - temp_files = [] - try: - nexe_maps = GlobalInit(options, temp_files) - for file_map in nexe_maps: - suite = unittest.TestLoader().loadTestsFromTestCase( - TestingClosure(toolchain_dir=options.toolchain_dir, - file_map=file_map)) - result = unittest.TextTestRunner(verbosity=2).run(suite) - success = result.wasSuccessful() and success - finally: - GlobalTeardown(temp_files) - - return int(not success) # 0 = success, 1 = failure - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/__init__.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/__init__.py deleted file mode 100644 index efdd458..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""build_tools/nacl_sdk_scons/site_tools Package - -This package contains general python scons utilities that are used for -creating the Native Client SDK.""" diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/create_nmf.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/create_nmf.py deleted file mode 100755 index 7561bce..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/create_nmf.py +++ /dev/null @@ -1,328 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -from __future__ import with_statement - -import errno -import optparse -import os -import re -import shutil -import subprocess -import sys -import urllib - -try: - import json -except ImportError: - import simplejson as json - -NeededMatcher = re.compile('^ *NEEDED *([^ ]+)\n$') -FormatMatcher = re.compile('^(.+):\\s*file format (.+)\n$') - -FORMAT_ARCH_MAP = { - # Names returned by Linux's objdump: - 'elf64-x86-64': 'x86-64', - 'elf32-i386': 'x86-32', - # Names returned by x86_64-nacl-objdump: - 'elf64-nacl': 'x86-64', - 'elf32-nacl': 'x86-32', - # TODO(mball): Add support for 'arm-32' and 'portable' architectures - # 'elf32-little': 'arm-32', - } - -# These constants are used within nmf files. -RUNNABLE_LD = 'runnable-ld.so' # Name of the dynamic loader -MAIN_NEXE = 'main.nexe' # Name of entry point for execution -PROGRAM_KEY = 'program' # Key of the program section in an nmf file -URL_KEY = 'url' # Key of the url field for a particular file in an nmf file -FILES_KEY = 'files' # Key of the files section in an nmf file - -# The proper name of the dynamic linker, as kept in the IRT. This is -# excluded from the nmf file by convention. -LD_NACL_MAP = { - 'x86-32': 'ld-nacl-x86-32.so.1', - 'x86-64': 'ld-nacl-x86-64.so.1', -} - -_debug_mode = False # Set to True to enable extra debug prints - - -def DebugPrint(message): - if _debug_mode: - sys.stderr.write('%s\n' % message) - sys.stderr.flush() - - -class Error(Exception): - '''Local Error class for this file.''' - pass - - -class ArchFile(object): - '''Simple structure containing information about - - Attributes: - arch: Architecture of this file (e.g., x86-32) - filename: name of this file - path: Full path to this file on the build system - url: Relative path to file in the staged web directory. - Used for specifying the "url" attribute in the nmf file.''' - def __init__(self, arch, name, path='', url=None): - self.arch = arch - self.name = name - self.path = path - self.url = url or '/'.join([arch, name]) - - def __str__(self): - '''Return the file path when invoked with the str() function''' - return self.path - - -class NmfUtils(object): - '''Helper class for creating and managing nmf files - - Attributes: - manifest: A JSON-structured dict containing the nmf structure - needed: A dict with key=filename and value=ArchFile (see GetNeeded) - ''' - - def __init__(self, main_files=None, objdump='x86_64-nacl-objdump', - lib_path=None, extra_files=None, lib_prefix=None): - ''' Constructor - - Args: - main_files: List of main entry program files. These will be named - files->main.nexe for dynamic nexes, and program for static nexes - objdump: path to x86_64-nacl-objdump tool (or Linux equivalent) - lib_path: List of paths to library directories - extra_files: List of extra files to include in the nmf - lib_prefix: A list of path components to prepend to the library paths, - both for staging the libraries and for inclusion into the nmf file. - Examples: ['..'], ['lib_dir'] ''' - self.objdump = objdump - self.main_files = main_files or [] - self.extra_files = extra_files or [] - self.lib_path = lib_path or [] - self.manifest = None - self.needed = None - self.lib_prefix = lib_prefix or [] - - def GleanFromObjdump(self, files): - '''Get architecture and dependency information for given files - - Args: - files: A dict with key=filename and value=list or set of archs. E.g.: - { '/path/to/my.nexe': ['x86-32', 'x86-64'], - '/path/to/libmy.so': ['x86-32'], - '/path/to/my2.nexe': None } # Indicates all architectures - - Returns: A tuple with the following members: - input_info: A dict with key=filename and value=ArchFile of input files. - Includes the input files as well, with arch filled in if absent. - Example: { '/path/to/my.nexe': ArchFile(my.nexe), - '/path/to/libfoo.so': ArchFile(libfoo.so) } - needed: A set of strings formatted as "arch/name". Example: - set(['x86-32/libc.so', 'x86-64/libgcc.so']) - ''' - DebugPrint("GleanFromObjdump(%s)" % ([self.objdump, '-p'] + files.keys())) - proc = subprocess.Popen([self.objdump, '-p'] + files.keys(), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, bufsize=-1) - input_info = {} - needed = set() - output, err_output = proc.communicate() - for line in output.splitlines(True): - # Objdump should display the architecture first and then the dependencies - # second for each file in the list. - matched = FormatMatcher.match(line) - if matched is not None: - filename = matched.group(1) - arch = FORMAT_ARCH_MAP[matched.group(2)] - if files[filename] is None or arch in files[filename]: - name = os.path.basename(filename) - input_info[filename] = ArchFile( - arch=arch, - name=name, - path=filename, - url='/'.join(self.lib_prefix + [arch, name])) - matched = NeededMatcher.match(line) - if matched is not None: - if files[filename] is None or arch in files[filename]: - needed.add('/'.join([arch, matched.group(1)])) - status = proc.poll() - if status != 0: - raise Error('%s\nStdError=%s\nobjdump failed with error code: %d' % - (output, err_output, status)) - return input_info, needed - - def FindLibsInPath(self, name): - '''Finds the set of libraries matching |name| within lib_path - - Args: - name: name of library to find - - Returns: - A list of system paths that match the given name within the lib_path''' - files = [] - for dir in self.lib_path: - file = os.path.join(dir, name) - if os.path.exists(file): - files.append(file) - if not files: - raise Error('cannot find library %s' % name) - return files - - def GetNeeded(self): - '''Collect the list of dependencies for the main_files - - Returns: - A dict with key=filename and value=ArchFile of input files. - Includes the input files as well, with arch filled in if absent. - Example: { '/path/to/my.nexe': ArchFile(my.nexe), - '/path/to/libfoo.so': ArchFile(libfoo.so) }''' - if not self.needed: - DebugPrint('GetNeeded(%s)' % self.main_files) - examined = set() - all_files, unexamined = self.GleanFromObjdump( - dict([(file, None) for file in self.main_files])) - for name, arch_file in all_files.items(): - arch_file.url = os.path.basename(name) - if unexamined: - unexamined.add('/'.join([arch_file.arch, RUNNABLE_LD])) - while unexamined: - files_to_examine = {} - for arch_name in unexamined: - arch, name = arch_name.split('/') - for path in self.FindLibsInPath(name): - files_to_examine.setdefault(path, set()).add(arch) - new_files, needed = self.GleanFromObjdump(files_to_examine) - all_files.update(new_files) - examined |= unexamined - unexamined = needed - examined - # With the runnable-ld.so scheme we have today, the proper name of - # the dynamic linker should be excluded from the list of files. - ldso = [LD_NACL_MAP[arch] for arch in set(FORMAT_ARCH_MAP.values())] - for name, arch_map in all_files.items(): - if arch_map.name in ldso: - del all_files[name] - self.needed = all_files - return self.needed - - def StageDependencies(self, destination_dir): - '''Copies over the dependencies into a given destination directory - - Each library will be put into a subdirectory that corresponds to the arch. - - Args: - destination_dir: The destination directory for staging the dependencies - ''' - needed = self.GetNeeded() - for source, arch_file in needed.items(): - destination = os.path.join(destination_dir, - urllib.url2pathname(arch_file.url)) - try: - os.makedirs(os.path.dirname(destination)) - except OSError as exception_info: - if exception_info.errno != errno.EEXIST: - raise - if (os.path.normcase(os.path.abspath(source)) != - os.path.normcase(os.path.abspath(destination))): - shutil.copy2(source, destination) - - def _GenerateManifest(self): - programs = {} - files = {} - - def add_files(needed): - for filename, arch_file in needed.items(): - files.setdefault(arch_file.arch, set()).add(arch_file.name) - - needed = self.GetNeeded() - add_files(needed) - - for filename in self.main_files: - arch_file = needed[filename] - programs[arch_file.arch] = arch_file.name - - filemap = {} - for arch in files: - for file in files[arch]: - if file not in programs.values() and file != RUNNABLE_LD: - filemap.setdefault(file, set()).add(arch) - - def arch_name(arch, file): - # nmf files expect unix-style path separators - return {URL_KEY: '/'.join(self.lib_prefix + [arch, file])} - - # TODO(mcgrathr): perhaps notice a program with no deps - # (i.e. statically linked) and generate program=nexe instead? - manifest = {PROGRAM_KEY: {}, FILES_KEY: {MAIN_NEXE: {}}} - for arch in programs: - manifest[PROGRAM_KEY][arch] = arch_name(arch, RUNNABLE_LD) - manifest[FILES_KEY][MAIN_NEXE][arch] = {URL_KEY: programs[arch]} - - for file in filemap: - manifest[FILES_KEY][file] = dict([(arch, arch_name(arch, file)) - for arch in filemap[file]]) - self.manifest = manifest - - def GetManifest(self): - '''Returns a JSON-formatted dict containing the NaCl dependencies''' - if not self.manifest: - self._GenerateManifest() - - return self.manifest - - def GetJson(self): - '''Returns the Manifest as a JSON-formatted string''' - pretty_string = json.dumps(self.GetManifest(), indent=2) - # json.dumps sometimes returns trailing whitespace and does not put - # a newline at the end. This code fixes these problems. - pretty_lines = pretty_string.split('\n') - return '\n'.join([line.rstrip() for line in pretty_lines]) + '\n' - - -def Main(argv): - parser = optparse.OptionParser( - usage='Usage: %prog [options] nexe [extra_libs...]') - parser.add_option('-o', '--output', dest='output', - help='Write manifest file to FILE (default is stdout)', - metavar='FILE') - parser.add_option('-D', '--objdump', dest='objdump', default='objdump', - help='Use TOOL as the "objdump" tool to run', - metavar='TOOL') - parser.add_option('-L', '--library-path', dest='lib_path', - action='append', default=[], - help='Add DIRECTORY to library search path', - metavar='DIRECTORY') - parser.add_option('-s', '--stage-dependencies', dest='stage_dependencies', - help='Destination directory for staging libraries', - metavar='DIRECTORY') - (options, args) = parser.parse_args(argv) - - if len(args) < 1: - parser.print_usage() - sys.exit(1) - - nmf = NmfUtils(objdump=options.objdump, - main_files=args, - lib_path=options.lib_path) - - manifest = nmf.GetManifest() - - if options.output is None: - sys.stdout.write(nmf.GetJson()) - else: - with open(options.output, 'w') as output: - output.write(nmf.GetJson()) - - if options.stage_dependencies: - nmf.StageDependencies(options.stage_dependencies) - - -# Invoke this file directly for simple testing. -if __name__ == '__main__': - sys.exit(Main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py b/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py deleted file mode 100644 index 470cec4..0000000 --- a/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py +++ /dev/null @@ -1,484 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -'''Extend the SCons Environment object with NaCl-specific builders and -modifiers. -''' - -from SCons import Script - -import nacl_utils -import os -import SCons - -def FilterOut(env, **kw): - """Removes values from existing construction variables in an Environment. - - The values to remove should be a list. For example: - - env.FilterOut(CPPDEFINES=['REMOVE_ME', 'ME_TOO']) - - Args: - env: Environment to alter. - kw: (Any other named arguments are values to remove). - """ - - kw = SCons.Environment.copy_non_reserved_keywords(kw) - - for key, val in kw.items(): - if key in env: - # Filter out the specified values without modifying the original list. - # This helps isolate us if a list is accidently shared - # NOTE if env[key] is a UserList, this changes the type into a plain - # list. This is OK because SCons also does this in semi_deepcopy - env[key] = [item for item in env[key] if item not in val] - - # TODO: SCons.Environment.Append() has much more logic to deal with various - # types of values. We should handle all those cases in here too. (If - # variable is a dict, etc.) - -def AppendOptCCFlags(env, is_debug=False): - '''Append a set of CCFLAGS that will build a debug or optimized variant - depending on the value of |is_debug|. - - Uses optional build-specific flags for debug and optimized builds. To set - these in your build.scons files you can do something like this: - nacl_env.Append(DEBUG_CCFLAGS=['-gfull'], - OPT_CCFLAGS=['-ffast-math', - '-mfpmath=sse', - '-msse2']) - - Args: - env: Environment to modify. - is_debug: Whether to set the option flags for debugging or not. Default - value is False. - ''' - - if is_debug: - env.Append(CCFLAGS=['${DEBUG_CCFLAGS}', - '-O0', - '-g', - ]) - else: - env.Append(CCFLAGS=['${OPT_CCFLAGS}', - '-O3', - '-fno-stack-protector', - '-fomit-frame-pointer', - ]) - - -def AppendArchFlags(env, arch_spec): - '''Append a set of architecture-specific flags to the environment. - - |arch_spec| is expected to be a map containing the keys "arch" and "subarch". - Supported keys are: - arch: x86 - subarch: 32 | 64 - - Args: - env: Environment to modify. - arch_spec: A dictionary with keys describing the arch and subarch to build. - Possible values are: 'arch': x86; 'subarch': 32 or 64. - ''' - - arch, subarch = nacl_utils.GetArchFromSpec(arch_spec) - cc_arch_flags = ['-m%s' % subarch] - as_arch_flags = ['--%s' % subarch] - if subarch == '64': - ld_arch_flags = ['-m64'] - env['NACL_ARCHITECTURE'] = 'x86_64-nacl-' - else: - ld_arch_flags = ['-m32'] - env['NACL_ARCHITECTURE'] = 'i686-nacl-' - env.Append(ASFLAGS=as_arch_flags, - CCFLAGS=cc_arch_flags, - LINKFLAGS=ld_arch_flags) - - -def NaClProgram(env, target, sources, variant_dir='obj'): - '''Add a Program to env that builds its objects in the directory specified - by |variant_dir|. - - This is slightly different than VariantDir() in that the sources can live in - the same directory as the calling SConscript file. - - Args: - env: Environment to modify. - target: The target name that depends on the object files. E.g. - "hello_world_x86_32.nexe" - sources: The list of source files that are used to build the objects. - variant_dir: The built object files are put in this directory. Default - value is "obj". - - Returns: - The Program Node. - ''' - - program_objects = [] - for src_file in sources: - obj_file = os.path.splitext(src_file)[0] + env.get('OBJSUFFIX', '.o') - program_objects.append(env.StaticObject( - target=os.path.join(variant_dir, obj_file), source=src_file)) - env.Clean('.', variant_dir) - return env.Program(target, program_objects) - - -def NaClTestProgram(env, - test_sources, - arch_spec, - module_name='nacl_test', - target_name='test'): - '''Modify |env| to include an Alias node for a test named |test_name|. - - This node will build the desired NaCl module with the debug flags turned on. - The Alias node has a build action that runs the test under sel_ldr. |env| is - expected to have variables named 'NACL_SEL_LDR<x>', and 'NACL_IRT_CORE<x>' - where <x> is the various architectures supported (e.g. NACL_SEL_LDR32 and - NACL_SEL_LLDR64) - - Args: - env: Environment to modify. - test_sources: The list of source files that are used to build the objects. - arch_spec: A dictionary with keys describing the arch and subarch to build. - Possible values are: 'arch': x86; 'subarch': 32 or 64. - module_name: The name of the module. The name of the output program - incorporates this as its prefix. - target_name: The name of the final Alias node. This name can be given on - the command line. For example: - nacl_env.NaClTestProgram(nacl_utils.ARCH_SPECS['x86-32'], - 'hello_world_test', - 'test32') - will let you say: ./scons test32 to build and run hello_world_test. - Returns: - A list of Nodes, one for each architecture-specific test. - ''' - - arch, subarch = nacl_utils.GetArchFromSpec(arch_spec) - # Create multi-level dictionary for sel_ldr binary name. - NACL_SEL_LDR = {'x86' : - {'32': '$NACL_SEL_LDR32', - '64': '$NACL_SEL_LDR64' - } - } - NACL_IRT_CORE = {'x86' : - {'32': '$NACL_IRT_CORE32', - '64': '$NACL_IRT_CORE64' - } - } - arch_sel_ldr = NACL_SEL_LDR[arch][subarch] - # if |arch| and |subarch| are not found, a KeyError exception will be - # thrown, which will generate a stack trace for debugging. - test_program = nacl_utils.MakeNaClModuleEnvironment( - env, - test_sources, - module_name, - arch_spec, - is_debug=True, - build_dir_prefix='test_') - test_node = env.Alias(target_name, - source=test_program, - action=arch_sel_ldr + - ' -B %s' % NACL_IRT_CORE[arch][subarch] + - ' $SOURCE') - # Tell SCons that |test_node| never goes out of date, so that you don't see - # '<test_node> is up to date.' - env.AlwaysBuild(test_node) - - -def NaClStaticLib(env, target, sources, variant_dir='obj', - lib_name='', lib_dir=''): - '''Add a StaticLibrary to env that builds its objects in the directory - specified by |variant_dir|. - - This is slightly different than VariantDir() in that the sources can live in - the same directory as the calling SConscript file. - - Args: - env: Environment to modify. - target: The target name that depends on the object files. E.g. - "c_salt_x86_32" yields the target name libc_salt_x86_32.a. - sources: The list of source files that are used to build the objects. - variant_dir: The built object files are put in this directory. Default - value is "obj". - lib_name: The final name for the library. E.g. lib_name='c_salt' yields - the final library name libc_)salt.a. Defaults to the target name. - lib_dir: The final library file is placed in that directory. The directory - is created if it doesn't already exists. Default is '.'. - - Returns: - The StaticLibrary Node. - ''' - - program_objects = [] - for src_file in sources: - obj_file = os.path.splitext(src_file)[0] + env.get('OBJSUFFIX', '.o') - program_objects.append(env.StaticObject( - target=os.path.join(variant_dir, obj_file), source=src_file)) - env.Clean('.', variant_dir) - lib_file = env.StaticLibrary(target, program_objects) - - # If either a lib_name or lib_dir, we must move the library file to its - # final destination. - if lib_dir or lib_name: - # Map lib_name to an actual file name that includes the correct prefix and - # suffix, both extracted from the target library name generated by scons. - if lib_name: - final_lib_name = lib_file[0].name.replace(target, lib_name) - else: - final_lib_name = lib_file[0].name - # Add an action to move the file. - install_node = env.InstallAs(os.path.join(lib_dir, final_lib_name), - lib_file) - # Add lib_name as an alias. This is the target that will build and install - # the libraries. - if lib_name: - env.Alias(lib_name, install_node) - - return lib_file - - -def NaClStrippedInstall(env, dir='', source=None): - '''Strip the target node. - - Args: - env: Environment to modify. - dir: The root install directory. - source: a list of a list of Nodes representing the executables to be - stripped. - - Returns: - A list of Install Nodes that strip each buildable in |source|. - ''' - stripped_install_nodes = [] - if not source: - return stripped_install_nodes - for source_nodes in source: - for strip_node in source_nodes: - # Use the construction Environment used to create the buildable object. - # Each environment has various important properties, such as the target - # architecture and tools prefix. - strip_env = strip_node.get_env() - install_node = strip_env.Install(dir=strip_env['NACL_INSTALL_ROOT'], - source=strip_node) - strip_env.AddPostAction(install_node, "%s $TARGET" % strip_env['STRIP']) - stripped_install_nodes.append(install_node) - - return stripped_install_nodes - - -def NaClModules(env, sources, module_name, is_debug=False): - '''Produce one construction Environment for each supported instruction set - architecture. - - Args: - env: Environment to modify. - sources: The list of source files that are used to build the objects. - module_name: The name of the module. - is_debug: Whether to set the option flags for debugging or not. Default - value is False. - - Returns: - A list of SCons build Nodes, each one with settings specific to an - instruction set architecture. - ''' - return [ - nacl_utils.MakeNaClModuleEnvironment( - env, - sources, - module_name=module_name, - arch_spec=nacl_utils.ARCH_SPECS['x86-32'], - is_debug=is_debug), - nacl_utils.MakeNaClModuleEnvironment( - env, - sources, - module_name=module_name, - arch_spec=nacl_utils.ARCH_SPECS['x86-64'], - is_debug=is_debug), - ] - - -def NaClStaticLibraries(env, sources, lib_name, is_debug=False, lib_dir=''): - '''Produce one static-lib construction Environment for each supported - instruction set architecture. - - Args: - env: Environment to modify. - sources: The list of source files that are used to build the objects. - lib_name: The name of the static lib. - is_debug: Whether to set the option flags for debugging or not. Default - value is False. - lib_dir: Where to output the final library file. Lib files are placed in - directories within lib_dir, based on the arch type and build type. - E.g. Specifying lib_dir = 'dest' for lib name 'c_salt' on x86-32 debug - creates the library file 'dest/lib-x86-32/dbg/libc_salt.a' - - Returns: - A list of SCons build Nodes, each one with settings specific to an - instruction set architecture. - ''' - return [ - nacl_utils.MakeNaClStaticLibEnvironment( - env, - sources, - lib_name=lib_name, - arch_spec=nacl_utils.ARCH_SPECS['x86-32'], - is_debug=is_debug, - lib_dir=lib_dir), - nacl_utils.MakeNaClStaticLibEnvironment( - env, - sources, - lib_name=lib_name, - arch_spec=nacl_utils.ARCH_SPECS['x86-64'], - is_debug=is_debug, - lib_dir=lib_dir), - ] - - -def InstallPrebuilt(env, module_name): - '''Create the 'install_prebuilt' target. - - install_prebuilt is used by the SDK build machinery to provide a prebuilt - version of the example in the SDK installer. This pseudo-builder adds an - Alias node called 'install_prebuilt' that depends on the main .nmf file of - the example. The .nmf file in turn has all the right dependencies to build - the necessary NaCl modules. As a final step, the opt variant directories - are removed. Once this build is done, the SDK builder can include the - example directory in its installer. - - Args: - env: Environment to modify. - module_name: The name of the module. - - Returns: - The Alias node representing the install_prebuilt target. - ''' - - return env.Alias('install_prebuilt', - source=['%s.nmf' % module_name], - action=Script.Delete([env.Dir('opt_x86_32'), - env.Dir('opt_x86_64')])) - - -def AllNaClModules(env, sources, module_name): - '''Add a builder for both the debug and optimized variant of every supported - instruction set architecture. - - Add one builder for each variant of the NaCl module, and also generate the - .nmf that loads the resulting NaCl modules. The .nmf file is named - |module_name|.nmf; similarly all other build products have |module_name| in - their name, e.g. - nacl_env.AllNaClModules(sources, module_name='hello_world') - produces these files, when x86-64 and x86-32 architectures are supported: - hello_world.nmf - hello_world_dbg.nmf - hello_world_x86_32.nexe - hello_world_x86_64.nexe - hello_world_x86_32_dbg.nexe - hello_world_x86_64_dbg.nexe - Object files go in variant directories named 'dbg_*' for debug builds and - 'opt_*' for optimized builds, where the * is a string describing the - architecture, e.g. 'x86_32'. - - Args: - env: Environment to modify. - sources: The list of source files that are used to build the objects. - module_name: The name of the module. - - Returns: - A 2-tuple of SCons Program nodes, the first element is the node that - builds optimized .nexes; the second builds the debug .nexes. - ''' - - opt_nexes = env.NaClModules(sources, module_name, is_debug=False) - env.GenerateNmf(target='%s.nmf' % module_name, - source=opt_nexes, - nexes={'x86-32': '%s_x86_32.nexe' % module_name, - 'x86-64': '%s_x86_64.nexe' % module_name}) - - dbg_nexes = env.NaClModules(sources, module_name, is_debug=True) - env.GenerateNmf(target='%s_dbg.nmf' % module_name, - source=dbg_nexes, - nexes={'x86-32': '%s_x86_32_dbg.nexe' % module_name, - 'x86-64': '%s_x86_64_dbg.nexe' % module_name}) - nacl_utils.PrintNaclPlatformBanner(module_name, - nacl_platform=env['TARGET_NACL_PLATFORM'], - variant=env['NACL_TOOLCHAIN_VARIANT']) - - return opt_nexes, dbg_nexes - - -def AllNaClStaticLibraries(env, sources, lib_name, lib_dir=''): - '''Add a builder for both the debug and optimized variant of every supported - instruction set architecture. - - Add one builder for each variant of the NaCl static library. The library - names have |lib_name| in their name, e.g. - nacl_env.AllNaClModules(sources, lib_name='c_salt') - produces these files, when x86-64 and x86-32 architectures are supported: - libc_salt_x86_32.a - libc_salt_x86_64.a - Object files go in variant directories named 'dbg_*' for debug builds and - 'opt_*' for optimized builds, where the * is a string describing the - architecture, e.g. 'x86_32'. - - Args: - env: Environment to modify. - sources: The list of source files that are used to build the objects. - lib_name: The name of the static library. - lib_dir: Where to output the final library files. Lib files are placed in - directories within lib_dir, based on the arch type and build type. - E.g. Specifying lib_dir = 'dest' for lib name 'c_salt' on x-86-32 debug - creates the library file 'dest/lib-x86-32/dbg/libc_salt.a' - - Returns: - A 2-tuple of SCons StaticLibrary nodes, the first element is the node that - builds optimized libs; the second builds the debug libs. - ''' - - opt_libs = env.NaClStaticLibraries(sources, lib_name, is_debug=False, - lib_dir=lib_dir) - dbg_libs = env.NaClStaticLibraries(sources, lib_name, is_debug=True, - lib_dir=lib_dir) - nacl_utils.PrintNaclPlatformBanner(lib_name, - nacl_platform=env['TARGET_NACL_PLATFORM'], - variant=env['NACL_TOOLCHAIN_VARIANT']) - - return opt_libs, dbg_libs - - -def generate(env): - '''SCons entry point for this tool. - - Args: - env: The SCons Environment to modify. - - NOTE: SCons requires the use of this name, which fails lint. - ''' - nacl_utils.AddCommandLineOptions() - - env.AddMethod(AllNaClModules) - env.AddMethod(AllNaClStaticLibraries) - env.AddMethod(AppendOptCCFlags) - env.AddMethod(AppendArchFlags) - env.AddMethod(FilterOut) - env.AddMethod(InstallPrebuilt) - env.AddMethod(NaClProgram) - env.AddMethod(NaClTestProgram) - env.AddMethod(NaClStaticLib) - env.AddMethod(NaClModules) - env.AddMethod(NaClStaticLibraries) - env.AddMethod(NaClStrippedInstall) - - -def exists(env): - '''The NaCl tool is always valid. This is a required entry point for SCons - Tools. - - Args: - env: The SCons Environment this tool will run in. - - Returns: - Always returns True. - ''' - return True diff --git a/native_client_sdk/src/build_tools/nsis_script.py b/native_client_sdk/src/build_tools/nsis_script.py deleted file mode 100644 index 851672e..0000000 --- a/native_client_sdk/src/build_tools/nsis_script.py +++ /dev/null @@ -1,207 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Class that represents an NSIS installer script.""" - -import os -import subprocess -import tarfile -import tempfile - -from build_tools import path_set - - -class Error(Exception): - pass - - -class NsisScript(path_set.PathSet): - '''Container for a NSIS script file - - Use this class to create and manage an NSIS script. You can construct this - class with an existing script file. You can Compile() the script to produce - and NSIS installer. - ''' - - def __init__(self, script_file='nsis.nsi'): - path_set.PathSet.__init__(self) - self._script_file = script_file - self._install_dir = os.path.join('C:%s' % os.sep, 'nsis_install') - self._relative_install_root = None - - @property - def script_file(self): - '''The output NSIS script file. Read-only.''' - return self._script_file - - @property - def install_dir(self): - '''The default directory where the NSIS installer will unpack its contents. - - This must be a full path, including the dirve letter. E.g.: - C:\native_client_sdk - ''' - return self._install_dir - - @install_dir.setter - def install_dir(self, new_install_dir): - if (os.path.isabs(new_install_dir) and - len(os.path.splitdrive(new_install_dir)[0]) > 0): - self._install_dir = new_install_dir - else: - raise Error('install_dir must be an absolute path') - - def InitFromDirectory(self, - artifact_dir, - dir_filter=None, - file_filter=None): - '''Create the list of installer artifacts. - - Creates three lists: - 1. a list of directories that need to be generated by the installer - 2. a list of files that get installed into those directories - 3. a list of symbolic links that need to be created by the installer - These lists are used later on when generating the section commands that are - compiled into the final installer - - Args: - artifact_dir: The directory containing the files to add to the NSIS - installer script. The NSIS installer will reproduce this directory - structure. - - dir_filter: A filter function for directories. This can be written as a - list comprehension. If dir_filter is not None, then it is called - with |_dirs|, and |_dirs| is replaced with the filter's - output. - - file_filter: A filter function for files. This can be written as a - list comprehension. If file_filter is not None, then it is called - with |_files|, and |_files| is replaced with the filter's - output. - ''' - self._relative_install_root = artifact_dir - self.Reset() - for root, dirs, files in os.walk(artifact_dir): - map(lambda dir: self._dirs.add(os.path.join(root, dir)), dirs) - map(lambda file: self._files.add(os.path.join(root, file)), files) - if dir_filter: - self._dirs = set(dir_filter(self._dirs)) - if file_filter: - self._files = set(file_filter(self._files)) - - def ReadCygwinSymlink(path): - if not os.path.isfile(path): - return None - header = open(path, 'rb').read(12) - if header != '!<symlink>\xff\xfe': - return None - data = open(path, 'rb').read()[12:] - return ''.join([ch for ch in data if ch != '\x00']) - - # Pick out cygwin symlinks. - all_files = self._files - self._files = set() - for f in all_files: - link = ReadCygwinSymlink(f) - if link: - self._symlinks[f] = link - else: - self._files.add(f) - - def CreateInstallNameScript(self, cwd='.'): - '''Write out the installer name script. - - The installer name script is in the special NSIS include file - sdk_install_name.nsh. This file is expected to be in |cwd|. If - sdk_install_name.nsh already exists, it is overwritten. - - Args: - cwd: The directory where sdk_install_name.sdk is placed. - ''' - with open(os.path.join(cwd, 'sdk_install_name.nsh'), 'wb') as script: - script.write('InstallDir %s\n' % self._install_dir) - - def NormalizeInstallPath(self, path): - '''Normalize |path| for installation. - - If |_relative_install_root| is set, then normalize |path| by making it - relative to |_relative_install_root|. - - Args: - path: The path to normalize. - - Returns: the normalized path. If |_relative_install_root| is None, then - the return value is the same as |path|. - ''' - if (self._relative_install_root and - path.startswith(self._relative_install_root)): - return path[len(self._relative_install_root) + 1:] - else: - return path - - def CreateSectionNameScript(self, cwd='.'): - '''Write out the section script. - - The section script is in the special NSIS include file sdk_section.nsh. - This file is expected to be in |cwd|. If sdk_section.nsh already exists, - it is overwritten. - - If |_relative_install_root| is set, then that part of the path is stripped - off of the installed file and directory names. This will cause the files - to be installed as if they were relative to |_relative_install_root| and - not in an absolute location. - - Args: - cwd: The directory where sdk_section.sdk is placed. - ''' - - def SymlinkType(symlink): - '''Return whether the source of symlink is a file or a directory.''' - symlink_basename = os.path.basename(symlink) - for file in self._files: - if os.path.basename(file) == symlink_basename: - return 'SoftF' - return 'SoftD' - - with open(os.path.join(cwd, 'sdk_section.nsh'), 'wb') as script: - script.write('Section "!Native Client SDK" NativeClientSDK\n') - script.write(' SectionIn RO\n') - script.write(' SetOutPath $INSTDIR\n') - for dir in self._dirs: - dir = self.NormalizeInstallPath(dir) - script.write(' CreateDirectory "%s"\n' % os.path.join('$INSTDIR', dir)) - for file in self._files: - file_norm = self.NormalizeInstallPath(file) - script.write(' File "/oname=%s" "%s"\n' % (file_norm, file)) - for src, symlink in self._symlinks.items(): - src_norm = self.NormalizeInstallPath(src) - link_type = SymlinkType(symlink) - script.write(' MkLink::%s "%s" "%s"\n' % ( - link_type, os.path.join('$INSTDIR', src_norm), symlink)) - for src, link in self._links.items(): - src_norm = self.NormalizeInstallPath(src) - link_norm = self.NormalizeInstallPath(link) - script.write(' MkLink::Hard "%s" "%s"\n' % ( - os.path.join('$INSTDIR', src_norm), - os.path.join('$INSTDIR', link_norm))) - script.write('SectionEnd\n') - - def Compile(self): - '''Compile the script. - - Compilation happens in a couple of steps: first, the install directory - script is generated from |_install_dir|, then the section commands script - is generated from |_files|. Finally |_script_file| is compiled, which - produces the NSIS installer specified by the OutFile property in - |_script_file|. - ''' - working_dir = os.path.dirname(self._script_file) - self.CreateInstallNameScript(cwd=working_dir) - self.CreateSectionNameScript(cwd=working_dir) - # Run the NSIS compiler. - subprocess.check_call([os.path.join('NSIS', 'makensis'), - '/V2', - self._script_file], - cwd=working_dir, - shell=True) diff --git a/native_client_sdk/src/build_tools/path_set.py b/native_client_sdk/src/build_tools/path_set.py deleted file mode 100644 index 24e9957..0000000 --- a/native_client_sdk/src/build_tools/path_set.py +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Class that contains paths classified into four types.""" - -import os - - -class Error(Exception): - pass - - -class PathSet(object): - '''Container for paths classified into four types. - - Paths in this container are broken into four separate collections, each - accessible as a property (see the "Attributes" section, below). - - Attributes: - files: A set of plain files, keys are platform-specific normalized path - names. Might be empty. - dirs: A set of directories, keys are platform-specific normalized path - names. Might be empty. - symlinks: A dictionary of symbolic links - these are not followed. Keys - are platform-specific normalized path names. The value of each key is - the source file of the link (also a platform-specific normalized path). - Might be empty. - links: A dictionary of hard links. Keys are platform-specific normalized - path names. The value of each key is the source file of the link (also - a platform-specific normalized path). Might be empty. - ''' - - def __init__(self): - self.Reset() - - def __ior__(self, other): - '''Override |= to merge |other| into this path set.''' - (self._files, self._dirs, - self._symlinks, self._links) = self._MergeWithPathSet(other) - return self - - def __or__(self, other): - '''Override | to produce the merger of |self| and |other|.''' - merged_path_set = PathSet() - (merged_path_set.files, - merged_path_set.dirs, - merged_path_set.symlinks, - merged_path_set.links) = self._MergeWithPathSet(other) - return merged_path_set - - def _MergeWithPathSet(self, path_set): - '''Merge this path set with |path_set|. - - Forms the union of the |_files| and |_dirs| sets, then merges the - |_symlinks| and |_links| dicts. The dictionaries are merged in such that - keys are not duplicated: the values of the keys in |path_set| take - precedence in the returned dictionaries. - - Any keys in either the symlink or links dictionaries that also exist in - either of the files or dicts sets are removed from the latter, meaning that - symlinks or links which overlap file or directory entries take precedence. - - Args: - path_set: The other path set. Must be an object with four properties: - files (a set), dirs (a set), symlinks (a dict), links (a dict). - Returns: - A four-tuple (files, dirs, symlinks, links) which is the result of merging - the two PathSets. - ''' - def DiscardOverlappingLinks(links_dict): - '''Discard all overlapping keys from files and dirs.''' - for link in links_dict: - self._files.discard(link) - self._dirs.discard(link) - - DiscardOverlappingLinks(path_set.symlinks) - DiscardOverlappingLinks(path_set.links) - return (self._files | path_set.files, - self._dirs | path_set.dirs, - dict(self._symlinks.items() + path_set.symlinks.items()), - dict(self._links.items() + path_set.links.items())) - - @property - def files(self): - '''The set of plain files.''' - return self._files - - @files.setter - def files(self, new_file_set): - if isinstance(new_file_set, set): - self._files = new_file_set - else: - raise Error('files property must be a set') - - @property - def dirs(self): - '''The set of directories.''' - return self._dirs - - @dirs.setter - def dirs(self, new_dir_set): - if isinstance(new_dir_set, set): - self._dirs = new_dir_set - else: - raise Error('dirs property must be a set') - - @property - def symlinks(self): - '''The dictionary of symbolic links.''' - return self._symlinks - - @symlinks.setter - def symlinks(self, new_symlinks_dict): - if isinstance(new_symlinks_dict, dict): - self._symlinks = new_symlinks_dict - else: - raise Error('symlinks property must be a dict') - - @property - def links(self): - '''The dictionary of hard links.''' - return self._links - - @links.setter - def links(self, new_links_dict): - if isinstance(new_links_dict, dict): - self._links = new_links_dict - else: - raise Error('links property must be a dict') - - def Reset(self): - '''Reset all attributes to empty containers.''' - self._files = set() - self._dirs = set() - self._symlinks = dict() - self._links = dict() - - def PrependPath(self, path_prefix): - '''Prepend paths in all collections with |path_prefix|. - - All the keys in all the colletions get prepended with |path_prefix|. The - resulting path is an os-specific path. - - Args: - path_prefix: The path to prepend to all collection keys. - ''' - prepend_path = lambda p: os.path.join(path_prefix, p) - def PrependToLinkDict(link_dict): - return dict([prepend_path(p), link] for p, link in link_dict.items()) - - self._files = set(map(prepend_path, self._files)) - self._dirs = set(map(prepend_path, self._dirs)) - self._symlinks = PrependToLinkDict(self._symlinks) - self._links = PrependToLinkDict(self._links) diff --git a/native_client_sdk/src/build_tools/tar_archive.py b/native_client_sdk/src/build_tools/tar_archive.py deleted file mode 100644 index 0032201..0000000 --- a/native_client_sdk/src/build_tools/tar_archive.py +++ /dev/null @@ -1,154 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Class that produces a table of contents form a tar archive.""" - -import os -import tarfile - -from build_tools import path_set - - -class Error(Exception): - pass - - -class TarArchive(path_set.PathSet): - '''Container for a tar archive table of contents. - - The table of contents is an enumeration of each node in the archive, stored - as the attributes of a PathSet (see path_set.py for details). - - The tar archive can be taken directly from a tarball (as long as the format - is supported by the tarfile module), or from a manifest file that was - generated using tar -tv. - - Attributes: - path_filter: A callable that gets applied to all paths in the object's tar - archive before the paths are added to any of the sets or dictionaries. - Setting this callable to None has the same effect as using a - pass-through filter (such as lambda x: x). This property cannot be - deleted. - ''' - - def __init__(self): - path_set.PathSet.__init__(self) - self._path_filter = os.path.normpath - - @property - def path_filter(self): - '''A filter to apply to paths in the tar archive.''' - return self._path_filter - - @path_filter.setter - def path_filter(self, path_filter): - self._path_filter = path_filter or (lambda x: x) - - @path_filter.deleter - def path_filter(self): - raise Error('path_filter cannot be deleted') - - def InitWithTarFile(self, tar_archive_file): - '''Initialize the object using a tar-format archive file. - - Wipes out any old table of contents data and replaces it with the new table - of contents from |tar_archive_file|. If the given tar archive doesn't - exist, or if it is not in a recognizable format, this method does nothing. - - Args: - tar_archive_file: The archive file. This is expected to be a file in a - tar format that the python tarfile module recognizes. - Raises: - OSError if |tar_archive_file| doesn't exist. - ''' - def MakePathSet(condition): - '''Helper function used with a lambda to generate a set of path names.''' - return set([self.path_filter(tarinfo.name) - for tarinfo in tar_archive if condition(tarinfo)]) - - def MakeLinksDict(condition): - '''Helper function used with a lambda to generate the link dicitonaries. - - Note that accessing tarinfo.linkname raises an exception if - the TarInfo member is not a link, which is why there are two separate - helper functions. - ''' - return dict([(self.path_filter(tarinfo.name), - self.path_filter(tarinfo.linkname)) - for tarinfo in tar_archive if condition(tarinfo)]) - - if not os.path.exists(tar_archive_file): - raise OSError('%s does not exist' % tar_archive_file) - tar_archive = None - try: - tar_archive = tarfile.open(tar_archive_file) - self.files = MakePathSet(lambda x: x.isfile()) - self.dirs = MakePathSet(lambda x: x.isdir()) - self.symlinks = MakeLinksDict(lambda x: x.issym()) - self.links = MakeLinksDict(lambda x: x.islnk()) - finally: - if tar_archive: - tar_archive.close() - - def InitWithManifest(self, tar_manifest_file): - '''Parse a tar-style manifest file and return the table of contents. - - Wipes out any old table of contents data and replaces it with the new table - of contents from |tar_manifest_file|. If the given manifest file doesn't - exist this method does nothing. - - Args: - tar_manifest_file: The manifest file. This is expected to be a file that - contains the result of tar -tv on the associated tarball. - Raises: - OSError if |tar_archive_file| doesn't exist. - ''' - # Index values into the manifest entry list. Note that some of these - # indices are negative (counting back from the last element), this is - # because the intermediate fields (such as date) from tar -tv differ from - # platform to platform. The last fields in the link members are always the - # same, however. All symlinks end in ['link_src', '->', 'link']; all hard - # links end in ['link_src', 'link', 'to', 'link']. - PERM_BITS_INDEX = 0 - # The symbolic link name is the third-from-last entry. - SYMLINK_FILENAME_INDEX = -3 - # The hard link name is the fourth-from-last entry. - HLINK_FILENAME_INDEX = -4 - LAST_ITEM_INDEX = -1 - - if not os.path.exists(tar_manifest_file): - raise OSError('%s does not exist' % tar_manifest_file) - self.Reset() - with open(tar_manifest_file) as manifest: - for manifest_item in map(lambda line: line.split(), manifest): - # Parse a single tar -tv entry in a manifest. - # The tar -tv entry is represented as a list of strings. The first - # string represents the permission bits; the first bit indicates the - # kind of entry. Depending on the kind of entry, other fields represent - # the member's path name, link source, etc. An entry list might look - # like this: - # ['hrwxr-xr-x', 'Administrators/Domain', 'Users', '0', '2011-08-09', - # '08:11', 'toolchain/win_x86/bin/i686-nacl-g++.exe', 'link', 'to', - # 'toolchain/win_x86/bin/i686-nacl-addr2line.exe'] - # This example is a hard link from i686-nacl-addr2line.exe to - # i686-nacl-g++.exe. - file_type = manifest_item[PERM_BITS_INDEX][0] - if file_type == 'd': - # A directory: the name is the final element of the entry. - self.dirs.add(self.path_filter(manifest_item[LAST_ITEM_INDEX])) - elif file_type == 'h': - # A hard link: the last element is the source of the hard link, and is - # entered as the key in the |links| dictionary. - link_name = self.path_filter(manifest_item[HLINK_FILENAME_INDEX]) - self.links[link_name] = self.path_filter( - manifest_item[LAST_ITEM_INDEX]) - elif file_type == 'l': - # A symbolic link: the last element is the source of the symbolic - # link. - link_name = self.path_filter(manifest_item[SYMLINK_FILENAME_INDEX]) - self.symlinks[link_name] = self.path_filter( - manifest_item[LAST_ITEM_INDEX]) - else: - # Everything else is considered a plain file. - self.files.add(self.path_filter(manifest_item[LAST_ITEM_INDEX])) diff --git a/native_client_sdk/src/build_tools/tests/__init__.py b/native_client_sdk/src/build_tools/tests/__init__.py deleted file mode 100644 index 31325fa..0000000 --- a/native_client_sdk/src/build_tools/tests/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Package for build_tools/tests""" diff --git a/native_client_sdk/src/build_tools/tests/apply_patch_test.py b/native_client_sdk/src/build_tools/tests/apply_patch_test.py deleted file mode 100755 index 496bf5c..0000000 --- a/native_client_sdk/src/build_tools/tests/apply_patch_test.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for apply_patch.py.""" - -import os -import sys -import unittest -import tempfile - -from build_tools import apply_patch - - -class TestRange(unittest.TestCase): - """ Test class _Range. """ - - def setUp(self): - pass - - def testParseValidRange(self): - """ Test _Range.Parse with a valid range. """ - diff_line = ['@@ -1,10 +5,9 @@'] - range = apply_patch._Range() - range.Parse(diff_line) - self.assertEqual(range.src_start_line, 1) - self.assertEqual(range.src_line_count, 10) - self.assertEqual(range.dest_start_line, 5) - self.assertEqual(range.dest_line_count, 9) - - def testParseValidRangeWithDefaults(self): - """ Test _Range.Parse with a valid range with default counts. """ - diff_line = ['@@ -1 +5 @@'] - range = apply_patch._Range() - range.Parse(diff_line) - self.assertEqual(range.src_start_line, 1) - self.assertEqual(range.src_line_count, 1) - self.assertEqual(range.dest_start_line, 5) - self.assertEqual(range.dest_line_count, 1) - - def testParseInvalidRanges(self): - """ Test _Range.Parse with invalid ranges. """ - diff_line = ['@@ ,10 +5,9 @@'] - range = apply_patch._Range() - self.assertRaises(apply_patch.Error, range.Parse, diff_line) - diff_line = ['@@ -,10 +5,9 @@'] - range = apply_patch._Range() - self.assertRaises(apply_patch.Error, range.Parse, diff_line) - diff_line = ['@@ -1,10 5,9 @@'] - range = apply_patch._Range() - self.assertRaises(apply_patch.Error, range.Parse, diff_line) - diff_line = ['@ -5,10 +5,9 @@'] - range = apply_patch._Range() - self.assertRaises(apply_patch.Error, range.Parse, diff_line) - - -class TestChangeHunk(unittest.TestCase): - """ Test class _ChangeHunk. """ - - def setUp(self): - self._change_hunk = apply_patch._ChangeHunk() - - def testDiffLineType(self): - """ Test function _ChangeHunk._DiffLineType. """ - diff_line_pairs = [ - [' a contextual line', apply_patch.CONTEXTUAL_DIFF_LINE], - ['\n', apply_patch.CONTEXTUAL_DIFF_LINE], - ['\r', apply_patch.CONTEXTUAL_DIFF_LINE], - [ '\n\r', apply_patch.CONTEXTUAL_DIFF_LINE], - ['+one added line', apply_patch.ADDED_DIFF_LINE], - ['-one delete line', apply_patch.DELETED_DIFF_LINE], - ['not valid', apply_patch.NOT_A_DIFF_LINE], - ['---not valid', apply_patch.NOT_A_DIFF_LINE], - ['+++not valid', apply_patch.NOT_A_DIFF_LINE], - ] - for pair in diff_line_pairs: - self.assertEqual(self._change_hunk._DiffLineType(pair[0]), pair[1]) - - def testParseWithValidLines(self): - """ Test function _ChangeHunk.Parse with valid diff lines. """ - diff_lines = [ - '@@ -5,4 +10,4 @@', - ' A contextual line.', - '-A line deleted from source.', - '-Another deleted line.', - '\r', # An empty contextual line. - '+A line added to destination.', - '+Another added line.', - '--- Begin next header.', - ] - num_input_lines = len(diff_lines) - self._change_hunk.Parse(diff_lines) - - self.assertEqual(self._change_hunk.range.src_start_line, 5) - self.assertEqual(self._change_hunk.range.src_line_count, 4) - self.assertEqual(self._change_hunk.range.dest_start_line, 10) - self.assertEqual(self._change_hunk.range.dest_line_count, 4) - self.assertEqual(len(self._change_hunk.lines), num_input_lines - 2) - - def testParseWithInvalidLines(self): - """ Test function _ChangeHunk.Parse with invalid diff lines. """ - diff_lines = [ - '@@ -5,4 +10,4 @@', - ' A contextual line.', - '-Another deleted line.', - '\r', # An empty contextual line. - '+A line added to destination.', - '+Another added line.', - '--- Begin next header.', - ] - num_input_lines = len(diff_lines) - self.assertRaises(apply_patch.Error, self._change_hunk.Parse, diff_lines) - - def testApply(self): - """ Test function _ChangeHunk.Apply. """ - with tempfile.SpooledTemporaryFile() as in_file: - with tempfile.SpooledTemporaryFile() as out_file: - in_file.write('aaaaaaaaaa\n') - in_file.write('bbbbbbbbbb\n') - in_file.seek(0) - - diff_lines = [ - '@@ -1,2 +1,2 @@', - ' aaaaaaaaaa\n', - '-bbbbbbbbbb\n', - '+cccccccccc\n', - '--- Begin next header.\n', - ] - - self._change_hunk.Parse(diff_lines) - self._change_hunk.Apply(0, in_file, out_file) - out_file.seek(0) - self.assertEqual(out_file.readline(), 'aaaaaaaaaa\n'); - self.assertEqual(out_file.readline(), 'cccccccccc\n'); - -class TestPatchHeader(unittest.TestCase): - """ Test class _PatchHeader. """ - - def setUp(self): - self._header = apply_patch._PatchHeader() - - def testParseValidHeader(self): - """ Test function _PatchHeader.Parse with a valid header. """ - diff_lines = [ - '--- dir/file.txt 1969-12-31 17:00:00.000000000 -0700\n', - '+++ dir/file_new.txt 2010-07-08 09:49:37.000000000 -0600\n' - ] - self._header.Parse(diff_lines) - self.assertEqual(self._header.in_file_name, 'dir/file.txt') - self.assertEqual(self._header.out_file_name, 'dir/file_new.txt') - - def testParseInvalidHeader(self): - """ Test function _PatchHeader.Parse with invalid headers. """ - diff_lines = [ - '-- dir/file.txt 1969-12-31 17:00:00.000000000 -0700\n', - '+++ dir/file_new.txt 2010-07-08 09:49:37.000000000 -0600\n' - ] - self.assertRaises(apply_patch.Error, self._header.Parse, diff_lines) - diff_lines = [ - '---\n', - '+++ dir/file_new.txt 2010-07-08 09:49:37.000000000 -0600\n' - ] - self.assertRaises(apply_patch.Error, self._header.Parse, diff_lines) - diff_lines = [ - '-- dir/file.txt 1969-12-31 17:00:00.000000000 -0700\n', - '+++\n' - ] - self.assertRaises(apply_patch.Error, self._header.Parse, diff_lines) - diff_lines = [ - '@@ dir/file.txt 1969-12-31 17:00:00.000000000 -0700\n', - '+++ dir/file_new.txt 2010-07-08 09:49:37.000000000 -0600\n' - ] - self.assertRaises(apply_patch.Error, self._header.Parse, diff_lines) - diff_lines = [ - '--- dir/file.txt 1969-12-31 17:00:00.000000000 -0700\n', - '@@ dir/file_new.txt 2010-07-08 09:49:37.000000000 -0600\n' - ] - self.assertRaises(apply_patch.Error, self._header.Parse, diff_lines) - -class TestPatch(unittest.TestCase): - """ Test class _Patch. """ - - TEST_DIR = 'apply_patch_test_archive' - TEST_FILE = 'original_file.txt' - TEST_DATA = [ - 'aaaaaaaaaa\n', - 'bbbbbbbbbb\n', - 'cccccccccc\n', - 'dddddddddd\n', - 'eeeeeeeeee\n', - 'ffffffffff\n', - ] - - def setUp(self): - self._patch = apply_patch._Patch() - - def testParseAndApply(self): - """ Test function _Patch.Parse. """ - diff_lines = [ - '--- ' + TestPatch.TEST_DIR + '/' + TestPatch.TEST_FILE + '\n', - '+++ ' + TestPatch.TEST_DIR + '/new' + TestPatch.TEST_FILE + '\n', - '@@ -1,0 +1,1 @@\n', - '+zzzzzzzzzz\n', - '@@ -3,2 +3,2 @@\n', - ' cccccccccc\n', - '-dddddddddd\n', - '+----------\n', - ] - self._patch.Parse(diff_lines) - - # Create the original data file. - script_dir = os.path.dirname(__file__) - test_dir = os.path.join(script_dir, TestPatch.TEST_DIR) - file_path = os.path.join(test_dir, TestPatch.TEST_FILE) - if not os.path.exists(test_dir): - os.mkdir(test_dir) - with open(file_path, 'w+b') as file: - file.truncate(0) - file.writelines(TestPatch.TEST_DATA) - - # Apply the patch and verify patched file - patched_data = [ - 'zzzzzzzzzz\n', - 'aaaaaaaaaa\n', - 'bbbbbbbbbb\n', - 'cccccccccc\n', - '----------\n', - 'eeeeeeeeee\n', - 'ffffffffff\n', - ] - self._patch.Apply(script_dir) - with open(file_path) as file: - self.assertEqual(file.readline(), patched_data.pop(0)) - - -def RunTests(): - outcome = True - for test_class in [TestRange, TestChangeHunk, TestPatchHeader, TestPatch]: - suite = unittest.TestLoader().loadTestsFromTestCase(test_class) - result = unittest.TextTestRunner(verbosity=2).run(suite) - outcome = outcome and result.wasSuccessful() - - return int(not outcome) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/build_utils_test.py b/native_client_sdk/src/build_tools/tests/build_utils_test.py deleted file mode 100755 index 3894960..0000000 --- a/native_client_sdk/src/build_tools/tests/build_utils_test.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for build_utils.py.""" - -__author__ = 'mball@google.com (Matt Ball)' - -import platform -import os -import subprocess -import sys -import tarfile -import unittest - -from build_tools import build_utils -import mox - - -class TestBuildUtils(unittest.TestCase): - """This class tests basic functionality of the build_utils package""" - def setUp(self): - self.mock_factory = mox.Mox() - - def testArchitecture(self): - """Testing the Architecture function""" - bit_widths = build_utils.SupportedNexeBitWidths() - # Make sure word-width of either 32 or 64. - self.assertTrue(32 in bit_widths or 64 in bit_widths) - if sys.platform in ['linux', 'linux2']: - self.assertTrue(32 in bit_widths) - if '64' in platform.machine(): - self.assertTrue(64 in bit_widths) - elif sys.platform == 'darwin': - # Mac should have both 32- and 64-bit support. - self.assertTrue(32 in bit_widths) - self.assertTrue(64 in bit_widths) - else: - # Windows supports either 32- or 64-bit, but not both. - self.assertEqual(1, len(bit_widths)) - - def testBotAnnotatorPrint(self): - """Testing the Print function of the BotAnnotator class""" - stdout_mock = self.mock_factory.CreateMock(sys.stdout) - stdout_mock.write("My Bot Message\n") - stdout_mock.flush() - stdout_mock.write("@@@BUILD_STEP MyBuildStep@@@\n") - stdout_mock.flush() - self.mock_factory.ReplayAll() - bot = build_utils.BotAnnotator(stdout_mock) - bot.Print("My Bot Message") - bot.BuildStep("MyBuildStep") - self.mock_factory.VerifyAll() - - def testBotAnnotatorRun(self): - """Testing the 'Run' command of the BotAnnotator class""" - out_string = 'hello' - print_command = ['python', '-c', - "import sys; sys.stdout.write('%s')" % out_string] - error_command = ['python', '-c', "import sys; sys.exit(1)"] - stdout_mock = self.mock_factory.CreateMock(sys.stdout) - stdout_mock.write('Running %s\n' % print_command) - stdout_mock.flush() - stdout_mock.write('%s\n' % out_string) - stdout_mock.flush() - stdout_mock.write('Running %s\n' % error_command) - stdout_mock.flush() - stdout_mock.write('\n') - stdout_mock.flush() - self.mock_factory.ReplayAll() - bot = build_utils.BotAnnotator(stdout_mock) - run_output = bot.Run(print_command) - self.assertEqual(run_output, "%s" % out_string) - self.assertRaises(subprocess.CalledProcessError, bot.Run, error_command) - self.mock_factory.VerifyAll() - - def testJoinPathToNaClRepo(self): - """Testing the 'JoinPathToNaClRepo' utility function.""" - # Test an empty arg list. - test_dir = os.path.join('third_party', 'native_client') - self.assertEqual(test_dir, build_utils.JoinPathToNaClRepo()) - # Test an empty arg list with just the root_dir key set. - test_dir = os.path.join('test_root', test_dir) - self.assertEqual(test_dir, - build_utils.JoinPathToNaClRepo(root_dir='test_root')) - # Test non-empty arg lists and with and without root_dir. - test_dir = os.path.join('third_party', 'native_client', 'testing', 'file') - self.assertEqual(test_dir, - build_utils.JoinPathToNaClRepo('testing', 'file')) - test_dir = os.path.join('test_root', test_dir) - self.assertEqual(test_dir, - build_utils.JoinPathToNaClRepo('testing', 'file', root_dir='test_root')) - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestBuildUtils) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/fake_gsutil.bat b/native_client_sdk/src/build_tools/tests/fake_gsutil.bat deleted file mode 100755 index 86cc640..0000000 --- a/native_client_sdk/src/build_tools/tests/fake_gsutil.bat +++ /dev/null @@ -1,3 +0,0 @@ -@echo off
-rem Simple Wrapper function to allow running fake_gsutil on Windows
-python "%~dp0fake_gsutil.py" %*
diff --git a/native_client_sdk/src/build_tools/tests/fake_gsutil.py b/native_client_sdk/src/build_tools/tests/fake_gsutil.py deleted file mode 100755 index 781e0d9..0000000 --- a/native_client_sdk/src/build_tools/tests/fake_gsutil.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -'''Fake implementation of gsutils, which is the utility used to upload files -to commondatastorage''' - -import optparse -import sys - - -def HandleLS(args): - if len(args) == 0: - print 'gs://nativeclient-upload/' - return 0 - print ('InvalidUriError: Attempt to get key for "%s" failed. ' - 'This probably indicates the URI is invalid.' % args[0]) - return 1 - - -def UnknownCommand(args): - return 0 - - -def HandleCP(args): - return 0 - - -def main(args): - if len(args) == 0: - return 0 - COMMANDS = { - 'ls': HandleLS, - 'cp': HandleCP, - } - return COMMANDS.get(args[0], UnknownCommand)(args[1:]) - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/native_client_sdk/src/build_tools/tests/install_nsis_test.py b/native_client_sdk/src/build_tools/tests/install_nsis_test.py deleted file mode 100755 index 9debe92..0000000 --- a/native_client_sdk/src/build_tools/tests/install_nsis_test.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for install_nsis.py.""" - -import os -import shutil -import subprocess -import sys -import unittest - -from build_tools import install_nsis - - -class TestInstallNsis(unittest.TestCase): - """This class tests basic functionality of the install_nsis package""" - def setUp(self): - self.nsis_installer_ = os.path.join(os.path.abspath('build_tools'), - install_nsis.NSIS_INSTALLER) - self.target_dir_ = os.path.join(os.path.dirname(self.nsis_installer_), - 'nsis_test', - 'NSIS') - def tearDown(self): - shutil.rmtree(os.path.dirname(self.target_dir_), ignore_errors=True) - - def testNsisInstallerExists(self): - """Ensure that the correct version of NSIS is present.""" - self.assertTrue(os.path.exists(self.nsis_installer_)) - - def testBogusNsisInstaller(self): - """Make sure the installer handles invalid directory names.""" - self.assertRaises(IOError, install_nsis.InstallNsis, 'bogus', 'not_a_dir') - - def testNsisInstaller(self): - """Make sure the installer produces an NSIS directory.""" - install_nsis.InstallNsis(self.nsis_installer_, self.target_dir_) - self.assertTrue(os.path.exists(os.path.join(self.target_dir_, - 'makensis.exe'))) - - def testAccessControlExtensions(self): - """Make sure that the AccessControl extensions can be installed.""" - script_dir = os.path.dirname(self.nsis_installer_) - install_nsis.InstallAccessControlExtensions( - script_dir, - os.path.join(script_dir, install_nsis.ACCESS_CONTROL_ZIP), - self.target_dir_) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControl.dll'))) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControlW.dll'))) - - def testMkLinkExtensions(self): - """Make sure the MkLink extensions are installed.""" - script_dir = os.path.dirname(self.nsis_installer_) - install_nsis.InstallMkLinkExtensions( - os.path.join(script_dir, install_nsis.MKLINK_DLL), - self.target_dir_) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'MkLink.dll'))) - - def testForceTargetInstall(self): - """Test that a force install to a target directory works.""" - try: - # Mock the NSIS install directories so that Install() thinks NSIS is - # already installed. - os.makedirs(os.path.join(self.target_dir_, 'Plugins'), mode=0777) - except OSError: - pass - self.assertFalse(os.path.exists(os.path.join(self.target_dir_, - 'makensis.exe'))) - self.assertFalse(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControl.dll'))) - self.assertFalse(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControlW.dll'))) - self.assertFalse(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'MkLink.dll'))) - - install_nsis.Install(os.path.dirname(self.nsis_installer_), - target_dir=self.target_dir_, - force=True) - - self.assertTrue(os.path.exists(os.path.join(self.target_dir_, - 'makensis.exe'))) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControl.dll'))) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'AccessControlW.dll'))) - self.assertTrue(os.path.exists( - os.path.join(self.target_dir_, 'Plugins', 'MkLink.dll'))) - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestInstallNsis) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/installer_contents_test.py b/native_client_sdk/src/build_tools/tests/installer_contents_test.py deleted file mode 100755 index 642b99c..0000000 --- a/native_client_sdk/src/build_tools/tests/installer_contents_test.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for installer_contents.py.""" - -import os -import sys -import unittest - -from build_tools import installer_contents - - -class TestInstallerContents(unittest.TestCase): - """This class tests basic functionality of the installer_contents package""" - def setUp(self): - self.mock_path_list = ['file', - 'file/in/a/path', - 'dir/spec/', - '', - '/abs/path', - ] - - - def testConvertToOSPaths(self): - output = installer_contents.ConvertToOSPaths(self.mock_path_list) - self.assertEqual(len(output), len(self.mock_path_list)) - self.assertEqual(output[0], 'file') - self.assertEqual(output[1], os.path.join('file', 'in', 'a', 'path')) - self.assertEqual(output[2], os.path.join('dir', 'spec', '')) - self.assertEqual(output[3], '') - self.assertEqual(output[4], os.path.join('abs', 'path')) - - def testGetDirectoriesFromPathList(self): - output = installer_contents.GetDirectoriesFromPathList(self.mock_path_list) - self.assertEqual(1, len(output)) - self.assertEqual(output[0], os.path.join('dir', 'spec', '')) - - def testGetFilesFromPathList(self): - output = installer_contents.GetFilesFromPathList(self.mock_path_list) - self.assertEqual(4, len(output)) - self.assertEqual(output[0], 'file') - self.assertEqual(output[1], os.path.join('file', 'in', 'a', 'path')) - self.assertEqual(output[2], '') - self.assertEqual(output[3], os.path.join('abs', 'path')) - - def DISABLEDtestGetToolchainManifest(self): - self.assertRaises(KeyError, - installer_contents.GetToolchainManifest, - 'notatoolchain') - newlib_manifest_path = installer_contents.GetToolchainManifest('newlib') - self.assertTrue(os.path.exists(newlib_manifest_path)) - glibc_manifest_path = installer_contents.GetToolchainManifest('glibc') - self.assertTrue(os.path.exists(glibc_manifest_path)) - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestInstallerContents) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/installer_test.py b/native_client_sdk/src/build_tools/tests/installer_test.py deleted file mode 100755 index 7cde6fc..0000000 --- a/native_client_sdk/src/build_tools/tests/installer_test.py +++ /dev/null @@ -1,480 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -""" Tests for the SDK Installer - -The general structure is as follows: - - 1. Extract the installer into a given temporary directory - 2. Run tests -- See TestSDK class (e.g., testExamples) - 3. Remove the installer directory -""" - -from __future__ import with_statement - -import cStringIO -import datetime -import httplib -import optparse -import os -import platform -import shutil -import socket -import string -import subprocess -import sys -import time -import unittest -import urllib -import zipfile - -from build_tools import build_utils -from build_tools import html_checker -from build_tools.sdk_tools import sdk_update -from build_tools.sdk_tools import update_manifest - -annotator = build_utils.BotAnnotator() - - -def TestingClosure(_outdir, _jobs): - '''This closure provides the variables needed by the various tests - - Args: - _outdir: The output directory that holds the extracted installer - _jobs: Number of parallel jobs for Make or Scons - - Returns: - A TestCase class that can be used by the unittest loader - ''' - toolchain_base = build_utils.NormalizeToolchain(base_dir=_outdir) - toolchain_bin = os.path.join(toolchain_base, 'bin') - toolchain_runtime = os.path.join(toolchain_base, 'runtime') - gcc64 = os.path.join(toolchain_bin, 'x86_64-nacl-gcc') - sel_ldr64 = os.path.join(toolchain_bin, 'sel_ldr_x86_64') - irt_core64 = os.path.join(toolchain_runtime, 'irt_core_x86_64.nexe') - scons = 'scons.bat' if sys.platform == 'win32' else 'scons' - staging_path = os.path.join(_outdir, 'staging') - - class TestSDK(unittest.TestCase): - '''Contains tests that run within an extracted SDK installer''' - - def GetBotShellEnv(self): - '''Massage |env| so its env variables will work on the bots.''' - env = os.environ.copy() - env['NACL_TARGET_PLATFORM'] = '.' # Use the repo's toolchain. - env['NACL_PROJECT_ROOT'] = _outdir # Put project templates here. - env['NACL_SDK_ROOT'] = _outdir - return env - - def SconsCommand(self, scons_path=''): - '''Helper to cons up a scons command. Sets nacl platform to '.' so that - SCons uses the repo's toolchain. - ''' - return [os.path.join(scons_path, scons), - '-j', _jobs, - '--nacl-platform=.' - ] - - def buildExamplesWithFlags(self, flags=None): - '''A small helper function that runs scons with arch and variant flags. - - Args: - flags: Any extra flags to pass to scons. Must be an array, - can be empty. - ''' - flags = flags or [] - path = os.path.join(_outdir, 'examples') - command = self.SconsCommand(path) + flags - env = self.GetBotShellEnv() - annotator.Run(command, cwd=path, env=env) - - def testBuildExamplesVariant(self): - '''Verify non-default toolchain SDK example build.''' - - # Note that --nacl-platform is set to ".". This is done so that the bots - # will use the repo's toolchain, instead of a platform-specific one. - # There are no platform-specific toolchains in the repo. - self.buildExamplesWithFlags(['--architecture=x86', - '--variant=newlib']) - self.buildExamplesWithFlags(['--architecture=x86', - '--variant=glibc']) - print "Test with bogus architectures, variants." - print "We expect these tests to throw exceptions:" - self.assertRaises(subprocess.CalledProcessError, - self.buildExamplesWithFlags, - flags=['--architecture=nosucharch']) - self.assertRaises(subprocess.CalledProcessError, - self.buildExamplesWithFlags, - flags=['--variant=nosuchvariant']) - - def testStagedHtmlFiles(self): - self.buildExamplesWithFlags(['--architecture=x86', '--variant=glibc']) - html_checker.ValidateAllLinks([os.path.join(staging_path, 'index.html')]) - - def testReadMe(self): - '''Check that the current build version and date are in the README file''' - - filename = 'README.txt' if sys.platform == 'win32' else 'README' - with open(os.path.join(_outdir, filename), 'r') as file: - contents = file.read() - version = 'Version: %s' % build_utils.PLATFORM_VERSION - annotator.Print('Checking that SDK version = %s' % version) - self.assertTrue(contents.count(version) == 1, - 'Version mismatch in %s' % filename) - revision = 'Revision: %s' % str(build_utils.SVNRevision()) - annotator.Print('Checking that SDK revision = %s' % revision) - self.assertTrue(contents.count(revision) == 1, - 'Revision mismatch in %s' % filename) - - # Check that the README contains either the current date or yesterday's - # date (which happens when building over midnight) - self.assertEqual( - 1, - contents.count(str(datetime.date.today())) + - contents.count(str(datetime.date.today() - - datetime.timedelta(days=1))), - "Cannot find today's or yesterday's date in README") - - def testRunHelloWorldUnittest(self): - '''Verify that we can build and run the hello_world unit test.''' - bit_widths = build_utils.SupportedNexeBitWidths() - test_targets = ['test%d' % bits for bits in bit_widths] - - if len(test_targets) == 0: - annotator.Print('No test targets found') - return - print 'running targets: %s' % str(test_targets) - path = os.path.join(_outdir, 'examples', 'hello_world') - command = self.SconsCommand(os.path.join(path, '..')) + test_targets - env = self.GetBotShellEnv() - annotator.Run(command, cwd=path, env=env) - - def testHttpd(self): - '''Test the simple HTTP server. - - Run the simple server and make sure it quits when processing an URL that - has the ?quit=1 parameter set. This test runs the server on the default - port (5103) and on a specified port. - ''' - - DEFAULT_SERVER_PORT = 5103 - - def runAndQuitHttpServer(port=DEFAULT_SERVER_PORT, - alternate_cwd=None, - extra_args=[], - should_fail=False): - '''A small helper function to launch the simple HTTP server. - - This function launches the simple HTTP server, then waits for its - banner output to appear. If the banner doesn't appear within 10 - seconds, the test fails. The banner is checked validate that it - displays the right port number. - - Once the server is verified as running, this function sends it a GET - request with the ?quit=1 URL parmeter. It then waits to see if the - server process exits with a return code of 0. If the server process - doesn't exit within 20 seconds, the test fails. - - Args: - port: The port to use, defaults to 5103. - ''' - path = staging_path - command = [sys.executable, os.path.join(path, 'httpd.py')] - # Add the port only if it's not the default. - if port != DEFAULT_SERVER_PORT: - command += [str(port)] - command += extra_args - # Can't use annotator.Run() because the HTTP server doesn't stop, which - # causes Run() to hang. - annotator.Print('Starting server: %s' % command) - annotator.Print('extra_args=%s' % str(extra_args)) - current_working_dir = path if alternate_cwd is None else alternate_cwd - annotator.Print('cwd=%s' % current_working_dir) - process = subprocess.Popen(command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - cwd=current_working_dir, - env=self.GetBotShellEnv()) - self.assertNotEqual(None, process) - # Wait until the process starts by trying to send it a GET request until - # the server responds, or until the timeout expires. If the timeout - # expires, fail the test. - time_start = time.time() - time_now = time_start - timeout_time = time_start + 20 # 20 sec timeout. - output = '' - conn = None - while time_now < timeout_time: - conn = httplib.HTTPConnection('localhost', port) - try: - # Send the quit request. - conn.request("GET", "/?quit=1") - output = process.stdout.readline() - break - except socket.error: - # If the server is not listening for connections, then - # HTTPConnetion() raises a socket exception, not one of the - # exceptions defined in httplib. In order to resend a request in - # this case, the original connection has to be closed and re-opened. - conn.close() - conn = None - time.sleep(1) # Wait a second to try again. - time_now = time.time() - - # If we expect the test to fail (e.g. bad directory without - # --no_dir_check) then there should be no connection. - if should_fail: - self.assertEqual(None, conn) - return_code = process.poll() - # If the process has not terminated, return_code will be None - # but since the server should have failed to launch, it should - # have terminated by now. - self.assertNotEqual(return_code, None) - return - - self.assertNotEqual(None, conn) - # Validate the first line of the startup banner. An example of the - # full line is: - # INFO:root:Starting local server on port 5103 - self.assertTrue(output.startswith('INFO:root:Starting')) - self.assertEqual(1, output.count(str(port))) - annotator.Print('Server startup banner: %s' % output) - - # Close down the connection and wait for the server to quit. - conn.getresponse() - conn.close() - - # Check to see if the server quit properly. It should quit within - # 0.5 seconds, so if the first poll() indicates that the process is - # still running, wait 1 sec and then poll again. If the process is - # still running after 20 sec, then fail the test. - return_code = process.poll() - poll_count = 0 - while return_code == None and poll_count < 20: - time.sleep(1) - return_code = process.poll() - poll_count += 1 - self.assertEqual(0, return_code) - - runAndQuitHttpServer() - runAndQuitHttpServer(5280) - # Make sure server works outside examles with --no_dir_check. - runAndQuitHttpServer(5281, alternate_cwd=_outdir, - extra_args=['--no_dir_check']) - # Make sure it works in examples with --no_dir_check. - runAndQuitHttpServer(5281, extra_args=['--no_dir_check']) - # Make sure the test fails if --no_dir_check is left out and the CWD - # is not examples. - runAndQuitHttpServer(5281, alternate_cwd=_outdir, should_fail=True) - # Retest port 5281 with the default parameters. - runAndQuitHttpServer(5281) - - def testProjectTemplates(self): - '''Create and build projects from project_templates.''' - - def initAndCompileProject(project_name, flags=[]): - '''A small helper function that runs init_project.py and then runs - a scons build in the resulting directory. - - Args: - project_name: The project's name, set the --name= parameter for - init_project to this value. - flags: Any extra flags to pass to init_project. Must be an array, - can be empty. - ''' - path = os.path.join(_outdir, 'project_templates') - project_path = os.path.join(_outdir, project_name) - scons_command = self.SconsCommand(project_path) - init_project_command = [sys.executable, - 'init_project.py', - '--name=%s' % project_name, - '--nacl-platform=.'] + flags - env = self.GetBotShellEnv() - annotator.Run(init_project_command, cwd=path, env=env) - annotator.Run(scons_command, cwd=project_path, env=env) - - initAndCompileProject('test_c_project', flags=['-c']) - initAndCompileProject('test_cc_project') - # Calling init_project again with the same names should cause an error - # because the project already exists, and we don't overwrite projects. - print "Rerunning init_project again to test overwriting previous project." - print "We expect these tests to throw exceptions:" - self.assertRaises(subprocess.CalledProcessError, - initAndCompileProject, - 'test_c_project', - flags=['-c']) - self.assertRaises(subprocess.CalledProcessError, - initAndCompileProject, - 'test_cc_project') - - # valgrind is deprecated as of pepper_17. - def deprecatedTestValgrind(self): - '''Verify that Valgrind works properly (Linux 64-bit only)''' - - bit_widths = build_utils.SupportedNexeBitWidths() - if (not sys.platform.startswith('linux')) or (64 not in bit_widths): - annotator.Print('Not running on 64-bit Linux -- skip') - return - true_basename = os.path.join(_outdir, 'true') - true_c_filename = '%s.c' % true_basename - true_nexe_filename = '%s.nexe' % true_basename - with open(true_c_filename, 'w') as true_file: - true_file.write('int main(void) { return 0; }\n') - annotator.Run([gcc64, '-o', true_nexe_filename, '-m64', '-O0', - '-Wl,-u,have_nacl_valgrind_interceptors', '-g', - true_c_filename, '-lvalgrind']) - memcheck = os.path.join(_outdir, 'third_party', 'valgrind', 'memcheck.sh') - annotator.Run([memcheck, sel_ldr64, - # The -B flag is needed by sel_ldr to find an Integrated - # Runtime that it can use to run .nexes. - '-B', irt_core64, - '-Q', true_nexe_filename]) - - return TestSDK - - -def ExtractInstaller(installer, outdir, bundle_name, nacl_sdk): - '''Extract the SDK installer into a given directory - - If the outdir already exists, then this function deletes it - - Args: - installer: full path of the SDK installer - outdir: output directory where to extract the installer - bundle_name: name of sdk bundle within outdir - nacl_sdk: filename of nacl_sdk tarball - - Raises: - OSError - if the outdir already exists - CalledProcessError - if the extract operation fails - ''' - - annotator.Print('Extracting installer %s into %s' % (installer, outdir)) - - if os.path.exists(outdir): - RemoveDir(outdir) - - os.mkdir(outdir) - - if sys.platform == 'win32': - zip_file = None - try: - zip_file = zipfile.ZipFile(nacl_sdk) - zip_file.extractall(path=outdir) - finally: - if zip_file: - zip_file.close() - else: - # Unfortunately, the zipfile module does not retain file permissions - # when extracting executable scripts. For now, just use the unzip - # that comes with Linux and Mac. - subprocess.check_call(['unzip', nacl_sdk], cwd=outdir) - - outdir = os.path.join(outdir, 'nacl_sdk') - - manifest_filename = os.path.join(outdir, 'test_manifest.json') - update_manifest_options = [ - '--bundle-revision=1', - '--bundle-version=2', - '--description=installer_test bundle', - '--%s-archive=file://%s' % ( - sdk_update.GetHostOS(), - urllib.pathname2url(os.path.abspath(installer))), - '--bundle-name=%s' % bundle_name, - '--recommended=yes', - '--stability=stable', - '--manifest-version=1', - '--manifest-file=%s' % manifest_filename] - annotator.Print('Running update manifest with %s' % update_manifest_options) - if 0 != update_manifest.main(update_manifest_options): - raise Exception('update_manifest terminated abnormally.') - - naclsdk_options = [ - os.path.join(outdir, - 'naclsdk.bat' if sys.platform == 'win32' else 'naclsdk'), - '--manifest-url=file://%s' % urllib.pathname2url(manifest_filename), - '--sdk-root-dir=%s' % outdir, - '--user-data-dir=%s' % outdir, - 'update'] - annotator.Print('Running naclsdk with %s' % naclsdk_options) - subprocess.check_call(naclsdk_options) - - -def RemoveDir(outdir): - '''Removes the given directory - - On Unix systems, this just runs shutil.rmtree, but on Windows, this doesn't - work when the directory contains junctions (as does our SDK installer). - Therefore, on Windows, it runs rmdir /S /Q as a shell command. This always - does the right thing on Windows. - - Args: - outdir: The directory to delete - - Raises: - CalledProcessError - if the delete operation fails on Windows - OSError - if the delete operation fails on Linux - ''' - - annotator.Print('Removing %s' % outdir) - if sys.platform == 'win32': - subprocess.check_call(['rmdir /S /Q', outdir], shell=True) - else: - shutil.rmtree(outdir) - - -def main(): - '''Main entry for installer tests - - Returns: - 0: Success - 1: Failure - - Also, raises various exceptions for error conditions. - ''' - - BUNDLE_NAME = 'test_sdk_bundle' - parser = optparse.OptionParser( - usage='Usage: %prog [options] sdk_installer') - parser.add_option( - '-o', '--outdir', dest='outdir', default='sdk_temp_dir', - help='temporary output directory for holding the installer') - parser.add_option( - '-j', '--jobs', dest='jobs', default=1, - help='number of parallel jobs to run') - parser.add_option( - '-n', '--nacl-sdk', dest='nacl_sdk', default='nacl_sdk.zip', - help='location of the nacl_sdk tarball') - parser.add_option( - '-s', '--sdk-tools', dest='sdk_tools', default='sdk_tools.tgz', - help='location of the sdk_tools tarball') - - options, args = parser.parse_args() - - if len(args) == 0: - parser.error('Must provide an sdk_installer') - - if len(args) > 1: - parser.error('Must provide only one sdk_installer') - - installer = args[0] - outdir = os.path.abspath(options.outdir) - - annotator.Print("Running with installer = %s, outdir = %s, jobs = %s" % ( - installer, outdir, options.jobs)) - ExtractInstaller(installer, outdir, BUNDLE_NAME, options.nacl_sdk) - - suite = unittest.TestLoader().loadTestsFromTestCase( - TestingClosure(os.path.join(outdir, 'nacl_sdk', BUNDLE_NAME), - options.jobs)) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - RemoveDir(outdir) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/native_client_sdk/src/build_tools/tests/naclsdk_manifest_test.json b/native_client_sdk/src/build_tools/tests/naclsdk_manifest_test.json deleted file mode 100644 index f3dc797..0000000 --- a/native_client_sdk/src/build_tools/tests/naclsdk_manifest_test.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "bundles": [ - { - "description": "Native Client SDK Tools, revision 1", - "stability": "stable", - "recommended": "yes", - "version": 2, - "archives": [ - { - "url": "nacl_sdk_linux_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "linux", - "size": 30018483 - }, - { - "url": "nacl_sdk_mac_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "mac", - "size": 30227408 - }, - { - "url": "nacl_sdk_win_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "win", - "size": 36440315 - } - ], - "revision": 1, - "name": "sdk_tools" - }, - { - "description": "Test Bundle version 1", - "stability": "stable", - "recommended": "yes", - "version": 1, - "archives": [ - { - "url": "nacl_linux_pepper_14_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "linux", - "size": 30018483 - }, - { - "url": "nacl_mac_pepper_14_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "mac", - "size": 30227408 - }, - { - "url": "nacl_win_pepper_14_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "win", - "size": 36440315 - } - ], - "revision": 2, - "name": "test_1" - }, - { - "description": "Test Bundle version 2", - "stability": "stable", - "recommended": "yes", - "version": 1, - "archives": [ - { - "url": "nacl_linux_pepper_15_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "linux", - "size": 30018483 - }, - { - "url": "nacl_mac_pepper_15_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "mac", - "size": 30227408 - }, - { - "url": "nacl_win_pepper_15_1.tgz", - "checksum": { - "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" - }, - "host_os": "win", - "size": 36440315 - } - ], - "revision": 2, - "name": "test_2" - }, - { - "description": "Chrome 1 bundle, revision 0", - "stability": "dev", - "recommended": "no", - "version": 1, - "archives": [ - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_mac.tgz", - "checksum": { - "sha1": "db66a0bba015f481995648ed022fcd78c9da0539" - }, - "host_os": "mac", - "size": 133 - }, - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_linux.tgz", - "checksum": { - "sha1": "7137917e08e8403e8a92354e69d5ff649a022c39" - }, - "host_os": "linux", - "size": 138 - }, - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_win.exe", - "checksum": { - "sha1": "fd5cecf2c5cb990829fe42a14fb8e1efbb35bf8f" - }, - "host_os": "win", - "size": 138 - } - ], - "revision": 0, - "name": "pepper_1" - }, - { - "name": "pepper_phony", - "description": "Chrome -1 bundle, revision -1", - "stability": "dev", - "recommended": "no", - "version": -1, - "archives": [ - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_mac.tgz", - "checksum": { - "sha1": "db66a0bba015f481995648ed022fcd78c9da0539" - }, - "host_os": "mac", - "size": 133 - }, - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_linux.tgz", - "checksum": { - "sha1": "7137917e08e8403e8a92354e69d5ff649a022c39" - }, - "host_os": "linux", - "size": 138 - }, - { - "url": "file:///Users/dspringer/Source/chromium/src/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_win.exe", - "checksum": { - "sha1": "fd5cecf2c5cb990829fe42a14fb8e1efbb35bf8f" - }, - "host_os": "win", - "size": 138 - } - ], - "revision": -1 - } - ], - "manifest_version": 1 -} diff --git a/native_client_sdk/src/build_tools/tests/nsis_script_test.py b/native_client_sdk/src/build_tools/tests/nsis_script_test.py deleted file mode 100755 index 595e6b8..0000000 --- a/native_client_sdk/src/build_tools/tests/nsis_script_test.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for nsis_script.py.""" - -import filecmp -import os -import sys -import tarfile -import tempfile -import unittest - -from build_tools import nsis_script - - -class TestNsisScript(unittest.TestCase): - """This class tests basic functionality of the nsis_script package""" - - def FilterSvn(self, list): - '''A filter used to remove .svn dirs from installer lists.''' - return [elt for elt in list if '.svn' not in elt] - - def testConstructor(self): - """Test default constructor.""" - script = nsis_script.NsisScript('test_script.nsi') - self.assertEqual('test_script.nsi', script.script_file) - self.assertEqual(0, len(script.files)) - self.assertEqual(0, len(script.dirs)) - self.assertEqual(0, len(script.symlinks)) - self.assertEqual(0, len(script.links)) - - def testInstallDir(self): - """Test install directory accessor/mutator.""" - script = nsis_script.NsisScript('test_script.nsi') - test_inst_dir = os.path.join('C:%s' % os.sep, 'test_install_dir') - script.install_dir = test_inst_dir - self.assertEqual(test_inst_dir, script.install_dir) - - def testBadInstallDir(self): - """Test install directory mutator with bad data""" - script = nsis_script.NsisScript('test_script.nsi') - try: - script.install_dir = 'bogus_path' - self.fail('install_dir failed to throw an exception with bogus_path') - except nsis_script.Error: - pass - else: - raise - - def testInitFromDirectory(self): - """Test creation of artifact lists from an archive directory.""" - script = nsis_script.NsisScript('test_script.nsi') - archive_dir = os.path.join('build_tools', 'tests', 'nsis_test_archive') - script.InitFromDirectory(archive_dir, - dir_filter=self.FilterSvn, - file_filter=self.FilterSvn) - file_set = script.files - self.assertEqual(3, len(file_set)) - self.assertTrue(os.path.join(archive_dir, 'test_file.txt') in file_set) - self.assertTrue(os.path.join(archive_dir, 'test_dir', 'test_dir_file1.txt') - in file_set) - self.assertTrue(os.path.join(archive_dir, 'test_dir', 'test_dir_file2.txt') - in file_set) - dir_set = script.dirs - self.assertEqual(1, len(dir_set)) - self.assertTrue(os.path.join(archive_dir, 'test_dir') in dir_set) - - def testCreateInstallNameScript(self): - """Test the install name include script.""" - test_dir = os.path.join('build_tools', 'tests') - script = nsis_script.NsisScript(os.path.join(test_dir, 'test_script.nsi')) - script.CreateInstallNameScript(cwd=test_dir) - install_name_script = open(os.path.join(test_dir, 'sdk_install_name.nsh'), - 'r') - self.assertTrue(script.install_dir in install_name_script.read()) - install_name_script.close() - os.remove(os.path.join(test_dir, 'sdk_install_name.nsh')) - - def testNormalizeInstallPath(self): - """Test NormalizeInstallPath.""" - # If InitFromDirectory() is not called, then install paths are unchanged. - test_dir = os.path.join('build_tools', 'tests') - script = nsis_script.NsisScript(os.path.join(test_dir, 'test_script.nsi')) - test_path = os.path.join('C:', 'test', 'path') - path = script.NormalizeInstallPath(test_path) - self.assertEqual(test_path, path) - # Set a relative install path. - archive_dir = os.path.join(test_dir, 'nsis_test_archive') - script.InitFromDirectory(archive_dir, - dir_filter=self.FilterSvn, - file_filter=self.FilterSvn) - test_path = os.path.join('test', 'relative', 'path') - path = script.NormalizeInstallPath(os.path.join(archive_dir, test_path)) - self.assertEqual(test_path, path) - - def testCreateSectionNameScript(self): - """Test the section name script.""" - test_dir = os.path.join('build_tools', 'tests') - script = nsis_script.NsisScript(os.path.join(test_dir, 'test_script.nsi')) - archive_dir = os.path.join(test_dir, 'nsis_test_archive') - script.InitFromDirectory(archive_dir, - dir_filter=self.FilterSvn, - file_filter=self.FilterSvn) - script.CreateSectionNameScript(cwd=test_dir) - # When comparing the contents of the script with the golden file, note - # that the 'File' lines can be in any order. All the other section commands - # have to be in the correct order. - def GetSectionCommands(section_script): - '''Split all the section commands into File and other commands. - - Returns: - A tuple (commands, file_set), where |commands| is an ordered list of - NSIS section commands, and |file_set| is an unordered set of NSIS File - commands. - ''' - commands = [] - file_set = set() - with open(section_script) as script_file: - commands = script_file.readlines(); # All the commands in order. - file_set = set([file_cmd - for file_cmd in commands if 'File ' in file_cmd]) - # Remove the File commands from the in-order command list. - for file in file_set: - commands.remove(file) - return commands, file_set - - test_commands, test_files = GetSectionCommands( - os.path.join(test_dir, 'test_sdk_section.nsh')) - script_commands, script_files = GetSectionCommands( - os.path.join(test_dir, 'sdk_section.nsh')) - self.assertEqual(test_commands, script_commands) - self.assertEqual(test_files, script_files) # Uses set() equality. - os.remove(os.path.join(test_dir, 'sdk_section.nsh')) - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestNsisScript) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file1.txt b/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file1.txt deleted file mode 100644 index 96fc3a7..0000000 --- a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file1.txt +++ /dev/null @@ -1,3 +0,0 @@ -This is a test file for nsis_script_test.py - -It is file 1 within a directory.
\ No newline at end of file diff --git a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file2.txt b/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file2.txt deleted file mode 100644 index f448ca9..0000000 --- a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_dir/test_dir_file2.txt +++ /dev/null @@ -1,3 +0,0 @@ -This is a test file for nsis_script_test.py - -It is file 2 within a directory.
\ No newline at end of file diff --git a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_file.txt b/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_file.txt deleted file mode 100644 index 83066e0..0000000 --- a/native_client_sdk/src/build_tools/tests/nsis_test_archive/test_file.txt +++ /dev/null @@ -1 +0,0 @@ -This is a test file for nsis_script_test.py
\ No newline at end of file diff --git a/native_client_sdk/src/build_tools/tests/path_set_test.py b/native_client_sdk/src/build_tools/tests/path_set_test.py deleted file mode 100755 index 3c5c96f..0000000 --- a/native_client_sdk/src/build_tools/tests/path_set_test.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for path_set.py.""" - -import os -import sys -import unittest - -from build_tools import path_set - - -class TestPathSet(unittest.TestCase): - """This class tests basic functionality of the installer_contents package""" - - def setUp(self): - self.pathset = path_set.PathSet() - - def testConstructor(self): - """Test default constructor.""" - self.assertEqual(0, len(self.pathset.files)) - self.assertEqual(0, len(self.pathset.dirs)) - self.assertEqual(0, len(self.pathset.symlinks)) - self.assertEqual(0, len(self.pathset.links)) - - def testSetAttributes(self): - self.pathset.files = set(['file1', 'file2']) - self.pathset.dirs = set(['dir1', 'dir2']) - self.pathset.symlinks = {'symlink': 'symlink_target'} - self.pathset.links = {'link': 'link_target'} - self.assertEqual(2, len(self.pathset.files)) - self.assertTrue('file1' in self.pathset.files) - self.assertTrue('file2' in self.pathset.files) - self.assertFalse('dir1' in self.pathset.files) - self.assertEqual(2, len(self.pathset.dirs)) - self.assertTrue('dir1' in self.pathset.dirs) - self.assertTrue('dir2' in self.pathset.dirs) - self.assertFalse('file1' in self.pathset.dirs) - self.assertEqual(1, len(self.pathset.symlinks)) - self.assertTrue('symlink' in self.pathset.symlinks) - self.assertFalse('dir1' in self.pathset.symlinks) - self.assertEqual(1, len(self.pathset.links)) - self.assertTrue('link' in self.pathset.links) - self.assertFalse('file1' in self.pathset.links) - self.pathset.dirs.discard('dir1') - self.assertFalse('dir11' in self.pathset.dirs) - - def testSetBadAttributes(self): - try: - self.pathset.files = ['this', 'is', 'a', 'list'] - self.fail('set files failed to throw an exception with non-set') - except path_set.Error: - pass - else: - raise - - try: - self.pathset.dirs = ['dir', 'list'] - self.fail('set dirs failed to throw an exception with non-set') - except path_set.Error: - pass - else: - raise - - try: - self.pathset.symlinks = 10 - self.fail('set symlinks failed to throw an exception with non-dict') - except path_set.Error: - pass - else: - raise - - try: - self.pathset.links = 'string of links' - self.fail('set links failed to throw an exception with non-dict') - except path_set.Error: - pass - else: - raise - - def testOrOperator(self): - self.pathset.files = set(['file1', 'file2', 'file3']) - self.pathset.dirs = set(['dir1', 'dir2']) - self.pathset.symlinks = {'symlink': 'symlink_target'} - self.pathset.links = {'link': 'link_target'} - pathset2 = path_set.PathSet() - pathset2.files = set(['file1', 'file4']) - pathset2.dirs = set(['dir1', 'dir3']) - pathset2.symlinks = {'symlink2': 'symlink_target2', - 'dir2': 'link_to_dir', - 'file3': 'link_to_file'} - pathset2.links = {'link2': 'link_target2'} - merged_pathset = self.pathset | pathset2 - self.assertFalse('file3' in self.pathset.files) - self.assertFalse('dir3' in self.pathset.dirs) - self.assertTrue('file1' in merged_pathset.files) - self.assertTrue('file2' in merged_pathset.files) - self.assertFalse('file3' in merged_pathset.files) - self.assertTrue('file4' in merged_pathset.files) - self.assertFalse('dir1' in merged_pathset.files) - self.assertTrue('dir1' in merged_pathset.dirs) - self.assertFalse('dir2' in merged_pathset.dirs) - self.assertTrue('dir3' in merged_pathset.dirs) - self.assertFalse('file1' in merged_pathset.dirs) - self.assertTrue('symlink' in merged_pathset.symlinks) - self.assertTrue('symlink2' in merged_pathset.symlinks) - self.assertFalse('dir1' in merged_pathset.symlinks) - self.assertTrue('link' in merged_pathset.links) - self.assertTrue('link2' in merged_pathset.links) - self.assertFalse('file1' in merged_pathset.links) - - def testOrEqualsOperator(self): - self.pathset.files = set(['file1', 'file2', 'file3']) - self.pathset.dirs = set(['dir1', 'dir2']) - self.pathset.symlinks = {'symlink': 'symlink_target'} - self.pathset.links = {'link': 'link_target'} - pathset2 = path_set.PathSet() - pathset2.files = set(['file1', 'file4']) - pathset2.dirs = set(['dir1', 'dir3']) - pathset2.symlinks = {'symlink2': 'symlink_target2', - 'dir2': 'link_to_dir', - 'file3': 'link_to_file'} - pathset2.links = {'link2': 'link_target2'} - self.pathset |= pathset2 - self.assertTrue('file1' in self.pathset.files) - self.assertTrue('file2' in self.pathset.files) - self.assertFalse('file3' in self.pathset.files) - self.assertFalse('dir1' in self.pathset.files) - self.assertTrue('dir1' in self.pathset.dirs) - self.assertFalse('dir2' in self.pathset.dirs) - self.assertTrue('dir3' in self.pathset.dirs) - self.assertFalse('file1' in self.pathset.dirs) - self.assertTrue('symlink' in self.pathset.symlinks) - self.assertTrue('symlink2' in self.pathset.symlinks) - self.assertFalse('dir1' in self.pathset.symlinks) - self.assertTrue('link' in self.pathset.links) - self.assertTrue('link2' in self.pathset.links) - self.assertFalse('file1' in self.pathset.links) - - def testPrependPath(self): - path_prefix = os.path.join('C:%s' % os.sep, 'path', 'prefix') - self.pathset.files = set(['file1', 'file2']) - self.pathset.dirs = set(['dir1', 'dir2']) - self.pathset.symlinks = {'symlink': 'symlink_target'} - self.pathset.links = {'link': 'link_target'} - prepended_files = set([os.path.join(path_prefix, f) - for f in self.pathset.files]) - prepended_dirs = set([os.path.join(path_prefix, d) - for d in self.pathset.dirs]) - prepended_symlinks = {os.path.join(path_prefix, 'symlink'): - 'symlink_target'} - prepended_links = {os.path.join(path_prefix, 'link'): 'link_target'} - self.pathset.PrependPath(path_prefix) - self.assertTrue(isinstance(self.pathset.files, set)) - self.assertTrue(isinstance(self.pathset.dirs, set)) - self.assertTrue(isinstance(self.pathset.symlinks, dict)) - self.assertTrue(isinstance(self.pathset.links, dict)) - self.assertEqual(prepended_files, self.pathset.files) - self.assertEqual(prepended_dirs, self.pathset.dirs) - self.assertEqual(prepended_symlinks, self.pathset.symlinks) - self.assertEqual(prepended_links, self.pathset.links) - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestPathSet) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_linux.tgz b/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_linux.tgz Binary files differdeleted file mode 100644 index f652373..0000000 --- a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_linux.tgz +++ /dev/null diff --git a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_mac.tgz b/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_mac.tgz Binary files differdeleted file mode 100644 index 779f854..0000000 --- a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_mac.tgz +++ /dev/null diff --git a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_win.exe b/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_win.exe Binary files differdeleted file mode 100755 index 5a4f120..0000000 --- a/native_client_sdk/src/build_tools/tests/pepper_1_0/naclsdk_win.exe +++ /dev/null diff --git a/native_client_sdk/src/build_tools/tests/sdk_test_cache/naclsdk_manifest.json b/native_client_sdk/src/build_tools/tests/sdk_test_cache/naclsdk_manifest.json deleted file mode 100644 index 77e1e4e..0000000 --- a/native_client_sdk/src/build_tools/tests/sdk_test_cache/naclsdk_manifest.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "manifest_version": 1, - "bundles": [ - { - "name": "sdk_tools", - "revision": 1, - "version": 2, - "description": "Native Client SDK Tools, revision 1", - "stability": "stable", - "recommended": "yes", - "archives": [ - { - "host_os": "linux", - "size": 30018483, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_sdk_linux_1.tgz" - }, - { - "host_os": "mac", - "size": 30227408, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_sdk_mac_1.tgz" - }, - { - "host_os": "win", - "size": 36440315, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_sdk_win_1.tgz" - } - ] - }, - { - "name": "test_1", - "version": 1, - "revision": 1, - "description": "Test Bundle version 1", - "stability": "stable", - "recommended": "yes", - "archives": [ - { - "host_os": "linux", - "size": 30018483, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_linux_pepper_14_1.tgz" - }, - { - "host_os": "mac", - "size": 30227408, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_mac_pepper_14_1.tgz" - }, - { - "host_os": "win", - "size": 36440315, - "checksum": { "sha1": "638bf0020c6f013ebef420d03fd7bb28593047b4" }, - "url": "nacl_win_pepper_14_1.tgz" - } - ] - }, - { - "name": "empty_bundle", - "version": 0, - "revision": 0, - "description": "Empty Test Bundle, Version 0", - "stability": "dev", - "recommended": "no", - "archives": [] - } - ] -} diff --git a/native_client_sdk/src/build_tools/tests/sdk_update_test.py b/native_client_sdk/src/build_tools/tests/sdk_update_test.py deleted file mode 100755 index b4ed444..0000000 --- a/native_client_sdk/src/build_tools/tests/sdk_update_test.py +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for sdk_update.py.""" - -import exceptions -import mox -import os -import subprocess -import sys -import tempfile -import unittest -import urllib - -from build_tools.sdk_tools import sdk_update - - -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -PARENT_DIR = os.path.dirname(SCRIPT_DIR) - - -class FakeOptions(object): - ''' Just a placeholder for options ''' - pass - - -def CallSDKUpdate(args): - '''Calls the sdk_update.py utility and returns stdout as a string - - Args: - args: command-line arguments as a list (not including program name) - - Returns: - string tuple containing (stdout, stderr) - - Raises: - subprocess.CalledProcessError: non-zero return code from sdk_update''' - command = ['python', os.path.join(PARENT_DIR, 'sdk_tools', - 'sdk_update.py')] + args - process = subprocess.Popen(stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - args=command) - output, error_output = process.communicate() - - retcode = process.poll() # Note - calling wait() can cause a deadlock - if retcode != 0: - raise subprocess.CalledProcessError(retcode, command) - return output, error_output - - -class TestSDKUpdate(unittest.TestCase): - ''' Test basic functionality of the sdk_update package ''' - def setUp(self): - self._options = FakeOptions() - self._options.manifest_url = 'file://%s' % urllib.pathname2url( - os.path.join(SCRIPT_DIR, 'naclsdk_manifest_test.json')) - self._options.user_data_dir = os.path.join(SCRIPT_DIR, 'sdk_test_cache') - - def testBadArg(self): - '''Test that using a bad argument results in an error''' - self.assertRaises(subprocess.CalledProcessError, CallSDKUpdate, ['--bad']) - - def testGetHostOS(self): - '''Test that the GetHostOS function returns a valid value''' - self.assertTrue(sdk_update.GetHostOS() in ['linux', 'mac', 'win']) - - def testHelp(self): - '''Test that basic help works''' - # Running any help command should call sys.exit() - self.assertRaises(exceptions.SystemExit, sdk_update.main, ['-h']) - - def testList(self): - '''Test the List function''' - command = ['--user-data-dir=%s' % - os.path.join(SCRIPT_DIR, 'sdk_test_cache'), - '--manifest-url=file://%s' % - urllib.pathname2url(os.path.join( - SCRIPT_DIR, 'naclsdk_manifest_test.json')), - 'list'] - bundle_list = CallSDKUpdate(command)[0] - # Just do some simple sanity checks on the resulting string - self.assertEqual(bundle_list.count('sdk_tools'), 2) - self.assertEqual(bundle_list.count('test_1'), 2) - self.assertEqual(bundle_list.count('test_2'), 1) - self.assertEqual(bundle_list.count('description:'), 8) - - def testUpdateHelp(self): - '''Test the help for the update command''' - self.assertRaises(exceptions.SystemExit, - sdk_update.main, ['help', 'update']) - - def testUpdateBogusBundle(self): - '''Test running update with a bogus bundle''' - self.assertRaises(sdk_update.Error, - sdk_update.main, - ['update', 'bogusbundle']) - - def testSDKManifestFile(self): - '''Test SDKManifestFile''' - manifest_file = sdk_update.SDKManifestFile( - os.path.join(self._options.user_data_dir, - sdk_update.MANIFEST_FILENAME)) - self.assertNotEqual(None, manifest_file) - bundles = manifest_file.GetBundles() - self.assertEqual(3, len(bundles)) - test_bundle = manifest_file.GetBundleNamed('test_1') - self.assertNotEqual(None, test_bundle) - self.assertTrue('revision' in test_bundle) - self.assertEqual(1, test_bundle['revision']) - - def testNeedsUpdate(self): - '''Test that the test_1 bundle needs updating''' - tools = sdk_update.ManifestTools(self._options) - tools.LoadManifest() - bundles = tools.GetBundles() - self.assertEqual(5, len(bundles)) - local_manifest = sdk_update.SDKManifestFile( - os.path.join(self._options.user_data_dir, - sdk_update.MANIFEST_FILENAME)) - self.assertNotEqual(None, local_manifest) - for bundle in bundles: - bundle_name = bundle['name'] - self.assertTrue('revision' in bundle) - if bundle_name in ['test_1', 'test_2', 'pepper_1', 'pepper_phony']: - self.assertTrue(local_manifest.BundleNeedsUpdate(bundle)) - else: - self.assertFalse(local_manifest.BundleNeedsUpdate(bundle)) - - def testMergeManifests(self): - '''Test merging a Bundle into a manifest file''' - tools = sdk_update.ManifestTools(self._options) - tools.LoadManifest() - bundles = tools.GetBundles() - self.assertEqual(5, len(bundles)) - local_manifest = sdk_update.SDKManifestFile( - os.path.join(self._options.user_data_dir, - sdk_update.MANIFEST_FILENAME)) - self.assertEqual(None, local_manifest.GetBundleNamed('test_2')) - for bundle in bundles: - local_manifest.MergeBundle(bundle) - self.assertNotEqual(None, local_manifest.GetBundleNamed('test_2')) - for bundle in bundles: - self.assertFalse(local_manifest.BundleNeedsUpdate(bundle)) - - def testMergeBundle(self): - '''Test MergeWithBundle''' - tools = sdk_update.ManifestTools(self._options) - tools.LoadManifest() - bundles = tools.GetBundles() - self.assertEqual(5, len(bundles)) - local_manifest = sdk_update.SDKManifestFile( - os.path.join(self._options.user_data_dir, - sdk_update.MANIFEST_FILENAME)) - self.assertNotEqual(None, local_manifest) - # Test the | operator. - for bundle in bundles: - bundle_name = bundle['name'] - if bundle_name in ['pepper_1', 'test_2', 'pepper_phony']: - continue - local_test_bundle = local_manifest.GetBundleNamed(bundle_name) - merged_bundle = local_test_bundle.MergeWithBundle(bundle) - self.assertTrue('revision' in merged_bundle) - if bundle_name == 'test_1': - self.assertEqual(2, merged_bundle['revision']) - else: - self.assertEqual(1, merged_bundle['revision']) - merged_bundle.Validate() - - def testVersion(self): - '''Test that showing the version works''' - self.assertRaises(exceptions.SystemExit, sdk_update.main, ['--version']) - - -def main(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestSDKUpdate) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/native_client_sdk/src/build_tools/tests/set_nacl_env_test.py b/native_client_sdk/src/build_tools/tests/set_nacl_env_test.py deleted file mode 100755 index 2959c72..0000000 --- a/native_client_sdk/src/build_tools/tests/set_nacl_env_test.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for set_nacl_env.py.""" - -import glob -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -from build_tools.sdk_tools import set_nacl_env - - -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -SDK_ROOT_DIR = os.path.dirname(os.path.dirname(SCRIPT_DIR)) -SRC_DIR = os.path.dirname(os.path.dirname(SDK_ROOT_DIR)) -NACL_DIR = os.path.join(SRC_DIR, 'native_client') - - -class FakeOptions(object): - ''' Just a placeholder for options ''' - pass - - -class TestSetNaclEnv(unittest.TestCase): - ''' Test basic functionality of the set_nacl_env package ''' - def setUp(self): - self._options = FakeOptions() - self._options.host = 'mac' - self._options.lib_variant = 'newlib' - self._options.sdk_root = NACL_DIR - self._options.sdk_platform = 'pepper_17' - self._options.build_type = 'debug' - self._options.no_ppapi = False - self._options.merge = False - - self._env = {} - self._env['NACL_SDK_ROOT'] = NACL_DIR - - self._temp_dir = tempfile.mkdtemp(prefix='tmp_set_nacl_env_test') - - def tearDown(self): - shutil.rmtree(self._temp_dir, ignore_errors=True) - - def testBuildEnvX86_32(self): - ''' Test setting up a x86_32 build env ''' - self._options.arch = 'x86-32' - self._options.toolchain_path = set_nacl_env.GetToolchainPath(self._options) - env = set_nacl_env.SetupX86Env(self._options) - # Verify a few essential build options. - self.assertTrue('CFLAGS' in env) - self.assertTrue('CC' in env) - self.assertTrue('-m32' in env['CC']) - self.assertTrue('pepper_17' in env['CC']) - self.assertTrue('CXX' in env) - self.assertTrue('-m32' in env['CXX']) - - def testBuildEnvX86_64(self): - ''' Test setting up a x86_64 build env ''' - self._options.arch = 'x86-64' - self._options.toolchain_path = set_nacl_env.GetToolchainPath(self._options) - env = set_nacl_env.SetupX86Env(self._options) - # Verify a few essential build options. - self.assertTrue('CFLAGS' in env) - self.assertTrue('CC' in env) - self.assertTrue('-m64' in env['CC']) - self.assertTrue('pepper_17' in env['CC']) - self.assertTrue('CXX' in env) - self.assertTrue('-m64' in env['CXX']) - - def testBuildWithMake(self): - ''' Test building hello_world_c with make ''' - def MakeClean(): - ''' Invoke 'make clean' in the current directory and check the outcome. - ''' - cmd = [script, 'make clean --silent'] - self.assertEqual(0, subprocess.call(cmd, env=self._env, shell=False, - cwd=self._temp_dir)) - self.assertFalse(os.path.exists('hello_world_c.nexe')) - - # Can't use make on Windows - if sys.platform == 'win32': - return - - # The test directories are not generally writable. To be able to run make, - # we copy the files to a temp directory instead. - self.assertTrue(self._temp_dir) - src_dir = os.path.join(SCRIPT_DIR, 'set_nacl_env_test_archive') - for file in glob.iglob(os.path.join(src_dir, '*')): - shutil.copy2(file, self._temp_dir) - shutil.copy2(os.path.join(SDK_ROOT_DIR, 'examples', 'hello_world_c', - 'hello_world_c.c'), - self._temp_dir) - - script = os.path.join(SDK_ROOT_DIR, 'build_tools', 'sdk_tools', - 'set_nacl_env.py') - nexe_path = os.path.join(self._temp_dir, 'hello_world_c.nexe') - - # Build and verify the 32-bit version. - options = ['--platform=.', '--arch=x86-32'] - cmd = [script] + options + ['make hello_world_c.nexe'] - self.assertEqual(0, subprocess.call(cmd, env=self._env, shell=False, - cwd=self._temp_dir)) - self.assertTrue(os.path.exists(nexe_path)) - size_32 = os.path.getsize(nexe_path) - MakeClean() - - # Build and verify the 64-bit version. - options = ['--platform=.', '--arch=x86-64'] - cmd = [script] + options + ['make hello_world_c.nexe'] - self.assertEqual(0, subprocess.call(cmd, env=self._env, shell=False, - cwd=self._temp_dir)) - self.assertTrue(os.path.exists(nexe_path)) - size_64 = os.path.getsize(nexe_path) - MakeClean() - - # Verify that 64-bit version of nexe is larger than 32-bit version. - self.assertTrue(size_64 > size_32) - - -def main(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestSetNaclEnv) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/native_client_sdk/src/build_tools/tests/set_nacl_env_test_archive/Makefile b/native_client_sdk/src/build_tools/tests/set_nacl_env_test_archive/Makefile deleted file mode 100644 index b198ccd..0000000 --- a/native_client_sdk/src/build_tools/tests/set_nacl_env_test_archive/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2011 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -EXAMPLE_DIR = . -EXAMPLE = hello_world_c.nexe - -all : $(EXAMPLE) - -clean : - rm -f $(EXAMPLE) hello_world_c.o hello_world_c.nexe - -SRCS_ = $(EXAMPLE_DIR)/hello_world_c.c - -hello_world_c.o : $(SRCS_) - $(CXX) $(CPPFLAGS) -I$(EXAMPLE_DIR) $(CXXFLAGS) -c \ - $(EXAMPLE_DIR)/hello_world_c.c - -$(EXAMPLE) : hello_world_c.o - $(LINK) $(CFLAGS) $(LDFLAGS) $^ -o $@ diff --git a/native_client_sdk/src/build_tools/tests/tar_archive_test.py b/native_client_sdk/src/build_tools/tests/tar_archive_test.py deleted file mode 100755 index b53bb74..0000000 --- a/native_client_sdk/src/build_tools/tests/tar_archive_test.py +++ /dev/null @@ -1,200 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for tar_archive.py.""" - -import os -import sys -import tarfile -import unittest - -from build_tools import tar_archive - - -class TestTarArchive(unittest.TestCase): - """This class tests basic functionality of the tar_archive package""" - - def setUp(self): - self.archive = tar_archive.TarArchive() - - def ValidateTableOfContents(self, archive, path_filter=None): - '''Helper method to validate an archive table of contents. - - The test table of contents file has these entries (from tar tv): - drwxr-xr-x test_links/ - drwxr-xr-x test_links/test_dir/ - lrwxr-xr-x test_links/test_dir_slnk -> test_dir - -rw-r--r-- test_links/test_hlnk_file_dst1.txt - hrw-r--r-- test_links/test_hlnk_file_dst2.txt link to \ - test_links/test_hlnk_file_dst1.txt - hrw-r--r-- test_links/test_hlnk_file_src.txt link to \ - test_links/test_hlnk_file_dst1.txt - lrwxr-xr-x test_links/test_slnk_file_dst.txt -> test_slnk_file_src.txt - -rw-r--r-- test_links/test_slnk_file_src.txt - -rw-r--r-- test_links/test_dir/test_file.txt - hrw-r--r-- test_links/test_dir/test_hlnk_file_dst3.txt \ - test_links/test_hlnk_file_dst1.txt - lrwxr-xr-x test_links/test_dir/test_slnk_file_dst2.txt -> \ - ../test_slnk_file_src.txt - - Args: - archive: The TarArchive object under test. - ''' - if not path_filter: - path_filter = lambda p: os.path.join('test_links', p) - - self.assertEqual(3, len(archive.files)) - self.assertTrue(path_filter('test_slnk_file_src.txt') in archive.files) - self.assertTrue(path_filter(os.path.join('test_dir', 'test_file.txt')) in - archive.files) - for file in archive.files: - self.assertFalse('_dir' in os.path.basename(file)) - self.assertTrue(path_filter(os.path.join('test_dir', 'test_file.txt')) in - archive.files) - - self.assertEqual(2, len(archive.dirs)) - self.assertTrue(path_filter('test_dir') in archive.dirs) - for dir in archive.dirs: - self.assertFalse('slnk' in dir) - self.assertFalse('.txt' in dir) - self.assertFalse(dir in archive.files) - self.assertFalse(dir in archive.symlinks.keys()) - - self.assertEqual(3, len(archive.symlinks)) - self.assertTrue(path_filter('test_dir_slnk') in archive.symlinks) - self.assertTrue(path_filter('test_slnk_file_dst.txt') in archive.symlinks) - for path, target in archive.symlinks.items(): - self.assertFalse(path in archive.files) - self.assertFalse(path in archive.dirs) - # Make sure the target exists in either |archive.files| or - # |archive.dirs|. The target path in the archive is relative to the - #source file's path. - target_path = os.path.normpath(os.path.join( - os.path.dirname(path), target)) - self.assertTrue((target_path in archive.files) or - (target_path in archive.dirs)) - - self.assertEqual(3, len(archive.links)) - # There is no "source" file for hard links like there is for a symbolic - # link, so there it's possible that the hlnk_src file is in the - # |archive.links| set, which is OK as long as one of the hlnk files is - # in the |archive.files| set. Make sure that only hlnk files are in the - # |archive.links| list. - for path, target in archive.links.items(): - self.assertTrue('test_hlnk_file' in path) - self.assertFalse(path in archive.files) - self.assertFalse(path in archive.dirs) - self.assertTrue(target in archive.files) - self.assertFalse(target in archive.dirs) - - def testConstructor(self): - """Test default constructor.""" - self.assertEqual(0, len(self.archive.files)) - self.assertEqual(0, len(self.archive.dirs)) - self.assertEqual(0, len(self.archive.symlinks)) - self.assertEqual(0, len(self.archive.links)) - - def testFromTarball(self): - """Testing the TarArchive when using a tarball""" - # Use a known test archive to validate the TOC entries. - self.archive.InitWithTarFile(os.path.join('build_tools', - 'tests', - 'test_links.tgz')) - self.ValidateTableOfContents(self.archive) - - def testFromTarballBadFile(self): - """Testing the TarArchive when using a bad tarball""" - self.assertRaises(OSError, - self.archive.InitWithTarFile, - 'nosuchfile') - self.assertRaises(tarfile.ReadError, - self.archive.InitWithTarFile, - os.path.join('build_tools', - 'tests', - 'test_links.tgz.manifest')) - - def testFromManifest(self): - """Testing the TarArchive when using a manifest file""" - # Use a known test manifest to validate the TOC entries. - # The test manifest file is the output of tar -tv on the tarball used in - # testGetArchiveTableOfContents(). - self.archive.InitWithManifest(os.path.join('build_tools', - 'tests', - 'test_links.tgz.manifest')) - self.ValidateTableOfContents(self.archive) - - def testFromManifestBadFile(self): - """Testing the TarArchive when using a bad manifest file""" - self.assertRaises(OSError, self.archive.InitWithManifest, 'nosuchfile') - - def testPathFilter(self): - """Testing the TarArchive when applying a path filter""" - def StripTestLinks(tar_path): - # Strip off the leading 'test_links/' path component. - pos = tar_path.find('test_links/') - if pos >= 0: - return os.path.normpath(tar_path[len('test_links/'):]) - else: - return os.path.normpath(tar_path) - - self.archive.path_filter = StripTestLinks - self.archive.InitWithTarFile(os.path.join('build_tools', - 'tests', - 'test_links.tgz')) - self.ValidateTableOfContents(self.archive, path_filter=lambda p: p) - self.archive.InitWithManifest(os.path.join('build_tools', - 'tests', - 'test_links.tgz.manifest')) - self.ValidateTableOfContents(self.archive, path_filter=lambda p: p) - - def testPathFilterNone(self): - """Testing the TarArchive when applying a None path filter""" - # Verify that the paths in the |archive| object have the tar-style '/' - # separator. - def ValidateTarStylePaths(archive): - def AssertTarPath(iterable): - for i in iterable: - self.assertTrue(len(i.split('/')) > 0) - - self.assertEqual(3, len(archive.files)) - AssertTarPath(archive.files) - self.assertEqual(2, len(archive.dirs)) - AssertTarPath(archive.dirs) - self.assertEqual(3, len(archive.symlinks)) - AssertTarPath(archive.symlinks.keys()) - self.assertEqual(3, len(archive.links)) - AssertTarPath(archive.links.keys()) - - self.archive.path_filter = None - self.archive.InitWithTarFile(os.path.join('build_tools', - 'tests', - 'test_links.tgz')) - ValidateTarStylePaths(self.archive) - self.archive.InitWithManifest(os.path.join('build_tools', - 'tests', - 'test_links.tgz.manifest')) - ValidateTarStylePaths(self.archive) - - def testDeletePathFilter(self): - # Note: due to the use of del() here, self.assertRaises() can't be used. - # Also, the with self.assertRaises() idiom is not in python 2.6 so it - # can't be used either. - try: - del(self.archive.path_filter) - except tar_archive.Error: - pass - else: - raise - - -def RunTests(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestTarArchive) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(RunTests()) diff --git a/native_client_sdk/src/build_tools/tests/test_links.tgz b/native_client_sdk/src/build_tools/tests/test_links.tgz Binary files differdeleted file mode 100644 index 898f147..0000000 --- a/native_client_sdk/src/build_tools/tests/test_links.tgz +++ /dev/null diff --git a/native_client_sdk/src/build_tools/tests/test_links.tgz.manifest b/native_client_sdk/src/build_tools/tests/test_links.tgz.manifest deleted file mode 100644 index dff6fbc2..0000000 --- a/native_client_sdk/src/build_tools/tests/test_links.tgz.manifest +++ /dev/null @@ -1,11 +0,0 @@ -drwxr-xr-x 0 user staff 0 Aug 30 14:53 test_links/ -drwxr-xr-x 0 user staff 0 Sep 6 16:30 test_links/test_dir/ -lrwxr-xr-x 0 user staff 0 Aug 30 14:53 test_links/test_dir_slnk -> test_dir --rw-r--r-- 0 user staff 35 Aug 30 14:53 test_links/test_hlnk_file_dst1.txt -hrw-r--r-- 0 user staff 0 Aug 30 14:53 test_links/test_hlnk_file_dst2.txt link to test_links/test_hlnk_file_dst1.txt -hrw-r--r-- 0 user staff 0 Aug 30 14:53 test_links/test_hlnk_file_src.txt link to test_links/test_hlnk_file_dst1.txt -lrwxr-xr-x 0 user staff 0 Aug 30 14:52 test_links/test_slnk_file_dst.txt -> test_slnk_file_src.txt --rw-r--r-- 0 user staff 33 Aug 30 14:51 test_links/test_slnk_file_src.txt --rw-r--r-- 0 user staff 38 Aug 30 14:52 test_links/test_dir/test_file.txt -hrw-r--r-- 0 user staff 0 Aug 30 14:53 test_links/test_dir/test_hlnk_file_dst3.txt link to test_links/test_hlnk_file_dst1.txt -lrwxr-xr-x 0 user staff 0 Sep 6 16:29 test_links/test_dir/test_slnk_file_dst2.txt -> ../test_slnk_file_src.txt diff --git a/native_client_sdk/src/build_tools/tests/test_sdk_section.nsh b/native_client_sdk/src/build_tools/tests/test_sdk_section.nsh deleted file mode 100644 index ac78aa7..0000000 --- a/native_client_sdk/src/build_tools/tests/test_sdk_section.nsh +++ /dev/null @@ -1,8 +0,0 @@ -Section "!Native Client SDK" NativeClientSDK - SectionIn RO - SetOutPath $INSTDIR - CreateDirectory "$INSTDIR\test_dir" - File "/oname=test_file.txt" "build_tools\tests\nsis_test_archive\test_file.txt" - File "/oname=test_dir\test_dir_file1.txt" "build_tools\tests\nsis_test_archive\test_dir\test_dir_file1.txt" - File "/oname=test_dir\test_dir_file2.txt" "build_tools\tests\nsis_test_archive\test_dir\test_dir_file2.txt" -SectionEnd diff --git a/native_client_sdk/src/build_tools/tests/update_manifest_test.py b/native_client_sdk/src/build_tools/tests/update_manifest_test.py deleted file mode 100755 index 5ff26c2..0000000 --- a/native_client_sdk/src/build_tools/tests/update_manifest_test.py +++ /dev/null @@ -1,369 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit tests for update_manifest.py.""" - -__author__ = 'mball@google.com (Matt Ball)' - -import errno -import os -import SimpleHTTPServer -import SocketServer -import sys -import tempfile -import threading -import unittest -import urllib -import urlparse - -from build_tools.sdk_tools import sdk_update -from build_tools.sdk_tools import update_manifest - -TEST_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def RemoveFile(filename): - '''Remove a filename if it exists and do nothing if it doesn't exist''' - try: - os.remove(filename) - except OSError as error: - if error.errno != errno.ENOENT: - raise - - -def GetHTTPHandler(path, length=None): - '''Returns a simple HTTP Request Handler that only servers up a given file - - Args: - path: path and filename of the file to serve up - length: (optional) only serve up the first |length| bytes - - Returns: - A SimpleHTTPRequestHandler class''' - class HTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - def do_GET(self): - with open(path, 'rb') as f: - # This code is largely lifted from SimpleHTTPRequestHandler.send_head - self.send_response(200) - self.send_header("Content-type", self.guess_type(path)) - fs = os.fstat(f.fileno()) - self.send_header("Content-Length", str(fs[6])) - self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) - self.end_headers() - if length != None: - self.wfile.write(f.read(length)) - else: - self.copyfile(f, self.wfile) - return HTTPHandler - - -class FakeOptions(object): - ''' Just a place holder for options ''' - def __init__(self): - self.archive_id = None - self.bundle_desc_url = None - self.bundle_name = None - self.bundle_version = None - self.bundle_revision = None - self.desc = None - self.gsutil = os.path.join(TEST_DIR, 'fake_gsutil.bat' - if sys.platform == 'win32' else 'fake_gsutil.py') - self.linux_arch_url = None - self.mac_arch_url = None - self.manifest_file = os.path.join(TEST_DIR, 'naclsdk_manifest_test.json') - self.manifest_version = None - self.recommended = None - self.root_url = 'file://%s' % urllib.pathname2url(TEST_DIR) - self.stability = None - self.upload = False - self.win_arch_url = None - - -class TestUpdateManifest(unittest.TestCase): - ''' Test basic functionality of the update_manifest package. - - Note that update_manifest.py now imports sdk_update.py, so this file - tests the update_manifest features within sdk_update.''' - - def setUp(self): - self._json_boilerplate=( - '{\n' - ' "bundles": [],\n' - ' "manifest_version": 1\n' - '}\n') - self._temp_dir = tempfile.gettempdir() - # os.path.join('build_tools', 'tests', 'test_archive') - self._manifest = update_manifest.UpdateSDKManifest() - - def testJSONBoilerplate(self): - ''' Test creating a manifest object''' - self.assertEqual(self._manifest.GetManifestString(), - self._json_boilerplate) - # Test using a manifest file with a version that is too high - self.assertRaises(sdk_update.Error, - self._manifest.LoadManifestString, - '{"manifest_version": 2}') - - def testWriteLoadManifestFile(self): - ''' Test writing to and loading from a manifest file''' - # Remove old test file - file_path = os.path.join(self._temp_dir, 'temp_manifest.json') - if os.path.exists(file_path): - os.remove(file_path) - # Create a basic manifest file - manifest_file = sdk_update.SDKManifestFile(file_path) - manifest_file.WriteFile(); - self.assertTrue(os.path.exists(file_path)) - # Test re-loading the file - manifest_file._manifest._manifest_data['manifest_version'] = 0 - manifest_file._LoadFile() - self.assertEqual(manifest_file._manifest.GetManifestString(), - self._json_boilerplate) - os.remove(file_path) - - def testValidateBundleName(self): - ''' Test validating good and bad bundle names ''' - self.assertTrue( - self._manifest._ValidateBundleName('A_Valid.Bundle-Name(1)')) - self.assertFalse(self._manifest._ValidateBundleName('A bad name')) - self.assertFalse(self._manifest._ValidateBundleName('A bad/name')) - self.assertFalse(self._manifest._ValidateBundleName('A bad;name')) - self.assertFalse(self._manifest._ValidateBundleName('A bad,name')) - - def testUpdateManifestVersion(self): - ''' Test updating the manifest version number ''' - options = FakeOptions() - options.manifest_version = 99 - self.assertEqual(self._manifest._manifest_data['manifest_version'], 1) - self._manifest._UpdateManifestVersion(options) - self.assertEqual(self._manifest._manifest_data['manifest_version'], 99) - - def testVerifyAllOptionsConsumed(self): - ''' Test function _VerifyAllOptionsConsumed ''' - options = FakeOptions() - options.opt1 = None - self.assertTrue(self._manifest._VerifyAllOptionsConsumed(options, None)) - options.opt2 = 'blah' - self.assertRaises(update_manifest.Error, - self._manifest._VerifyAllOptionsConsumed, - options, - 'no bundle name') - - def testBundleUpdate(self): - ''' Test function Bundle.Update ''' - bundle = sdk_update.Bundle('test') - options = FakeOptions() - options.bundle_revision = 1 - options.bundle_version = 2 - options.desc = 'What a hoot' - options.stability = 'dev' - options.recommended = 'yes' - update_manifest.UpdateBundle(bundle, options) - self.assertEqual(bundle['revision'], 1) - - def testUpdateManifestModifyTopLevel(self): - ''' Test function UpdateManifest: modifying top-level info ''' - options = FakeOptions() - options.manifest_version = 0 - options.bundle_name = None - self._manifest.UpdateManifest(options) - self.assertEqual(self._manifest._manifest_data['manifest_version'], 0) - - def testUpdateManifestModifyBundle(self): - ''' Test function UpdateManifest: adding/modifying a bundle ''' - # Add a bundle - options = FakeOptions() - options.manifest_version = 1 - options.bundle_name = 'test' - options.bundle_revision = 2 - options.bundle_version = 3 - options.desc = 'nice bundle' - options.stability = 'canary' - options.recommended = 'yes' - self._manifest.UpdateManifest(options) - bundle = self._manifest.GetBundle('test') - self.assertNotEqual(bundle, None) - # Modify the same bundle - options = FakeOptions() - options.manifest_version = None - options.bundle_name = 'test' - options.desc = 'changed' - self._manifest.UpdateManifest(options) - bundle = self._manifest.GetBundle('test') - self.assertEqual(bundle['description'], 'changed') - - def testUpdateManifestBadBundle1(self): - ''' Test function UpdateManifest: bad bundle data ''' - options = FakeOptions() - options.manifest_version = None - options.bundle_name = 'test' - options.stability = 'excellent' - self.assertRaises(sdk_update.Error, - self._manifest.UpdateManifest, - options) - - def testUpdateManifestBadBundle2(self): - ''' Test function UpdateManifest: incomplete bundle data ''' - options = FakeOptions() - options.manifest_version = None - options.bundle_name = 'another_bundle' - self.assertRaises(sdk_update.Error, - self._manifest.UpdateManifest, - options) - - def testUpdateManifestArchiveComputeSha1AndSize(self): - ''' Test function Archive.Update ''' - temp_file_path = None - try: - with tempfile.NamedTemporaryFile(delete=False) as temp_file: - # Create a temp file with some data - temp_file.write(r'abcdefghijklmnopqrstuvwxyz0123456789') - temp_file_path = temp_file.name - # Windows requires that we close the file before reading from it. - temp_file.close() - - # Create an archive with a url to the file we created above. - url_parts = urlparse.ParseResult('file', '', temp_file_path, '', '', '') - url = urlparse.urlunparse(url_parts) - archive = sdk_update.Archive('mac') - archive.Update(url) - self.assertEqual(archive['checksum']['sha1'], - 'd2985049a677bbc4b4e8dea3b89c4820e5668e3a') - finally: - if temp_file_path and os.path.exists(temp_file_path): - os.remove(temp_file_path) - - def testUpdateManifestArchiveValidate(self): - ''' Test function Archive.Validate ''' - # Test invalid host-os name - archive = sdk_update.Archive('atari') - self.assertRaises(sdk_update.Error, archive.Validate) - # Test missing url - archive['host_os'] = 'mac' - self.assertRaises(sdk_update.Error, archive.Validate) - # Valid archive - archive['url'] = 'http://www.google.com' - archive.Validate() - # Test invalid key name - archive['guess'] = 'who' - self.assertRaises(sdk_update.Error, archive.Validate) - - def testUpdatePartialFile(self): - '''Test updating with a partially downloaded file''' - server = None - server_thread = None - temp_filename = os.path.join(self._temp_dir, - 'testUpdatePartialFile_temp.txt') - try: - # Create a new local server on an arbitrary port that just serves-up - # the first 10 bytes of this file. - server = SocketServer.TCPServer( - ("", 0), GetHTTPHandler(__file__, 10)) - ip, port = server.server_address - server_thread = threading.Thread(target=server.serve_forever) - server_thread.start() - - archive = sdk_update.Archive('mac') - self.assertRaises(sdk_update.Error, - archive.Update, - 'http://localhost:%s' % port) - try: - self.assertRaises(sdk_update.Error, - archive.DownloadToFile, - temp_filename) - finally: - RemoveFile(temp_filename) - finally: - if server_thread and server_thread.isAlive(): - server.shutdown() - server_thread.join() - - def testUpdateManifestMain(self): - ''' test the main function from update_manifest ''' - temp_filename = os.path.join(self._temp_dir, 'testUpdateManifestMain.json') - try: - argv = ['--bundle-version', '0', - '--bundle-revision', '0', - '--description', 'test bundle for update_manifest unit tests', - '--bundle-name', 'test_bundle', - '--stability', 'dev', - '--recommended', 'no', - '--manifest-file', temp_filename] - update_manifest.main(argv) - finally: - RemoveFile(temp_filename) - - def testPush(self): - '''Test whether the push function does the right thing''' - options = FakeOptions() - argv = ['-g', options.gsutil, 'push'] - update_manifest.main(argv) - - def testHandleSDKTools(self): - '''Test the handling of the sdk_tools bundle''' - options = FakeOptions() - options.bundle_name = 'sdk_tools' - options.upload = True - options.bundle_version = 0 - self.assertRaises( - update_manifest.Error, - update_manifest.UpdateSDKManifestFile(options).HandleBundles) - options.bundle_version = None - options.bundle_revision = 0 - self.assertRaises( - update_manifest.Error, - update_manifest.UpdateSDKManifestFile(options).HandleBundles) - options.bundle_revision = None - update_manifest.UpdateSDKManifestFile(options).HandleBundles() - - def testHandlePepper(self): - '''Test the handling of pepper bundles''' - options = FakeOptions() - options.bundle_name = 'pepper' - options.bundle_version = None - self.assertRaises( - update_manifest.Error, - update_manifest.UpdateSDKManifestFile(options).HandleBundles) - options.bundle_name = 'pepper' - options.bundle_version = 1 - options.bundle_revision = None - self.assertRaises( - update_manifest.Error, - update_manifest.UpdateSDKManifestFile(options).HandleBundles) - options.bundle_name = 'pepper' - options.bundle_revision = 0 - manifest_object = update_manifest.UpdateSDKManifestFile(options) - manifest_object.HandleBundles() - manifest_object.UpdateWithOptions() - - options = FakeOptions() - options.bundle_name = 'pepper_1' - options.bundle_revision = 0 - manifest_object = update_manifest.UpdateSDKManifestFile(options) - manifest_object.HandleBundles() - manifest_object.UpdateWithOptions() - - # Verify that the bundle can be found via the --archive-id option. - options = FakeOptions() - options.archive_id = 'pepper_1_0' - options.bundle_name = 'pepper_phony' - options.bundle_version = -1 - options.bundle_revision = -1 - options.stability = 'dev' - options.recommended = 'no' - manifest_object = update_manifest.UpdateSDKManifestFile(options) - manifest_object.HandleBundles() - manifest_object.UpdateWithOptions() - - -def main(): - suite = unittest.TestLoader().loadTestsFromTestCase(TestUpdateManifest) - result = unittest.TextTestRunner(verbosity=2).run(suite) - - return int(not result.wasSuccessful()) - - -if __name__ == '__main__': - sys.exit(main()) |