<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";

class WorkerTest : public UILayoutTest {
 protected:
  virtual ~WorkerTest() { }

  void RunTest(const std::wstring& test_case) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  void RunIncognitoTest(const std::wstring& test_case) {
    scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
    // Open an Incognito window.
    int window_count;
    ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
    scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
    scoped_refptr<TabProxy> tab(incognito->GetTab(0));
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(2, window_count);

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);

    // Close the incognito window
    ASSERT_TRUE(incognito->RunCommand(IDC_CLOSE_WINDOW));
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(1, window_count);

    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  bool WaitForProcessCountToBe(int tabs, int workers) {
    // The 1 is for the browser process.
    int number_of_processes = 1 + workers +
        (UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
    // On Linux, we also have a zygote process and a sandbox host process.
    number_of_processes += 2;
#endif

    int cur_process_count;
    for (int i = 0; i < 10; ++i) {
      cur_process_count = GetBrowserProcessCount();
      if (cur_process_count == number_of_processes)
        return true;

      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }

    EXPECT_EQ(number_of_processes, cur_process_count);
    return false;
  }
};

#if defined(OS_LINUX)
// Fails running under valgrind, http://crbug.com/28445
#define SingleWorker DISABLED_SingleWorker
#endif

TEST_F(WorkerTest, SingleWorker) {
  RunTest(L"single_worker.html");
}

TEST_F(WorkerTest, MultipleWorkers) {
  RunTest(L"multi_worker.html");
}

// Incognito windows should not share workers with non-incognito windows
TEST_F(WorkerTest, IncognitoSharedWorkers) {
  // Load a non-incognito tab and have it create a shared worker
  RunTest(L"incognito_worker.html");
  // Incognito worker should not share with non-incognito
  RunIncognitoTest(L"incognito_worker.html");
}

#if defined(OS_LINUX) || defined (OS_MACOSX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif

TEST_F(WorkerTest, WorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "stress-js-execution.html",
    "use-machine-stack.html",
    "worker-call.html",
    "worker-cloneport.html",
    "worker-close.html",
    "worker-constructor.html",
    "worker-context-gc.html",
    "worker-context-multi-port.html",
    "worker-event-listener.html",
    "worker-gc.html",
    // worker-lifecycle.html relies on layoutTestController.workerThreadCount
    // which is not currently implemented.
    // "worker-lifecycle.html",
    "worker-location.html",
    "worker-messageport.html",
    // Disabled after r27089 (WebKit merge), http://crbug.com/22947
    // "worker-messageport-gc.html",
    "worker-multi-port.html",
    "worker-navigator.html",
    "worker-replace-global-constructor.html",
    "worker-replace-self.html",
    "worker-script-error.html",
    "worker-terminate.html",
    "worker-timeout.html"
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
// http://crbug.com/28445 - flakiness on mac
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// These tests are flaky on linux/views builds.
// See http://crbug.com/28808.
#define MessagePorts FLAKY_MessagePorts
#define SharedWorkerFastLayoutTests FLAKY_SharedWorkerFastLayoutTests
#endif

TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-constructor.html",
    "shared-worker-context-gc.html",
    "shared-worker-event-listener.html",
    "shared-worker-exception.html",
    "shared-worker-gc.html",
    // Lifecycle tests rely on layoutTestController.workerThreadCount which is
    // not currently implemented.
    //"shared-worker-frame-lifecycle.html",
    //"shared-worker-lifecycle.html",
    "shared-worker-load-error.html",
    "shared-worker-location.html",
    "shared-worker-name.html",
    "shared-worker-navigator.html",
    "shared-worker-replace-global-constructor.html",
    "shared-worker-replace-self.html",
    "shared-worker-script-error.html",
    "shared-worker-shared.html",
    "shared-worker-simple.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) {
    RunLayoutTest(kLayoutTestFiles[i], false);
    // Shared workers will error out if we ever have more than one tab open.
    int window_count = 0;
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(1, window_count);
    EXPECT_EQ(1, GetTabCount());
  }
}

TEST_F(WorkerTest, WorkerHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-importScripts.html",
    "shared-worker-redirect.html",
    // flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "worker-importScripts.html",
#endif
    "worker-redirect.html",
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

#if defined(OS_LINUX)
// Fails running under valgrind http://crbug.com/28445
#define WorkerXhrHttpLayoutTests DISABLED_WorkerXhrHttpLayoutTests
#endif

TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "abort-exception-assert.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "close.html",
#endif
    // These tests (and the shared-worker versions below) are disabled due to
    // limitations in lighttpd (doesn't handle all of the HTTP methods).
    //"methods-async.html",
    //"methods.html",

    "shared-worker-close.html",
    // Disabled due to limitations in lighttpd (does not handle methods other
    // than GET/PUT/POST).
    //"shared-worker-methods-async.html",
    //"shared-worker-methods.html",
    "shared-worker-xhr-file-not-found.html",

    "xmlhttprequest-file-not-found.html"
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, MessagePorts) {
  static const char* kLayoutTestFiles[] = {
    "message-channel-gc.html",
    "message-channel-gc-2.html",
    "message-channel-gc-3.html",
    "message-channel-gc-4.html",
    "message-port.html",
    "message-port-clone.html",
    "message-port-constructor-for-deleted-document.html",
    "message-port-deleted-document.html",
    "message-port-deleted-frame.html",
    "message-port-inactive-document.html",
    "message-port-multi.html",
    "message-port-no-wrapper.html",
    // Only works with run-webkit-tests --leaks.
    //"message-channel-listener-circular-ownership.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("events");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // MessagePort tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));

  ASSERT_TRUE(WaitForProcessCountToBe(1, max_workers_per_tab));
}
#endif

#if defined(OS_LINUX)
// Fails (crashes) on Linux Tests: http://crbug.com/28445
#define LimitTotal DISABLED_LimitTotal
#endif

TEST_F(WorkerTest, LimitTotal) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  int total_workers = WorkerService::kMaxWorkersWhenSeparate;

  int tab_count = (total_workers / max_workers_per_tab) + 1;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  for (int i = 1; i < tab_count; ++i)
    window->AppendTab(url);

  // Check that we didn't create more than the max number of workers.
  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));

  // Now close a page and check that the queued workers were started.
  tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));

  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Mark a test as flaky that failed for 1/2 of yesterday on one bot.  Doing fine on others.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";

class WorkerTest : public UILayoutTest {
 protected:
  virtual ~WorkerTest() { }

  void RunTest(const std::wstring& test_case) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  void RunIncognitoTest(const std::wstring& test_case) {
    scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
    // Open an Incognito window.
    int window_count;
    ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
    scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
    scoped_refptr<TabProxy> tab(incognito->GetTab(0));
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(2, window_count);

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);

    // Close the incognito window
    ASSERT_TRUE(incognito->RunCommand(IDC_CLOSE_WINDOW));
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(1, window_count);

    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  bool WaitForProcessCountToBe(int tabs, int workers) {
    // The 1 is for the browser process.
    int number_of_processes = 1 + workers +
        (UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
    // On Linux, we also have a zygote process and a sandbox host process.
    number_of_processes += 2;
#endif

    int cur_process_count;
    for (int i = 0; i < 10; ++i) {
      cur_process_count = GetBrowserProcessCount();
      if (cur_process_count == number_of_processes)
        return true;

      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }

    EXPECT_EQ(number_of_processes, cur_process_count);
    return false;
  }
};

#if defined(OS_LINUX)
// Fails running under valgrind, http://crbug.com/28445
#define SingleWorker DISABLED_SingleWorker
#endif

TEST_F(WorkerTest, SingleWorker) {
  RunTest(L"single_worker.html");
}

TEST_F(WorkerTest, MultipleWorkers) {
  RunTest(L"multi_worker.html");
}

// Incognito windows should not share workers with non-incognito windows
TEST_F(WorkerTest, IncognitoSharedWorkers) {
  // Load a non-incognito tab and have it create a shared worker
  RunTest(L"incognito_worker.html");
  // Incognito worker should not share with non-incognito
  RunIncognitoTest(L"incognito_worker.html");
}

#if defined(OS_LINUX) || defined (OS_MACOSX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif

TEST_F(WorkerTest, WorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "stress-js-execution.html",
    "use-machine-stack.html",
    "worker-call.html",
    "worker-cloneport.html",
    "worker-close.html",
    "worker-constructor.html",
    "worker-context-gc.html",
    "worker-context-multi-port.html",
    "worker-event-listener.html",
    "worker-gc.html",
    // worker-lifecycle.html relies on layoutTestController.workerThreadCount
    // which is not currently implemented.
    // "worker-lifecycle.html",
    "worker-location.html",
    "worker-messageport.html",
    // Disabled after r27089 (WebKit merge), http://crbug.com/22947
    // "worker-messageport-gc.html",
    "worker-multi-port.html",
    "worker-navigator.html",
    "worker-replace-global-constructor.html",
    "worker-replace-self.html",
    "worker-script-error.html",
    "worker-terminate.html",
    "worker-timeout.html"
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
// http://crbug.com/28445 - flakiness on mac
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// These tests are flaky on linux/views builds.
// See http://crbug.com/28808.
#define MessagePorts FLAKY_MessagePorts
#define SharedWorkerFastLayoutTests FLAKY_SharedWorkerFastLayoutTests
#endif

TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-constructor.html",
    "shared-worker-context-gc.html",
    "shared-worker-event-listener.html",
    "shared-worker-exception.html",
    "shared-worker-gc.html",
    // Lifecycle tests rely on layoutTestController.workerThreadCount which is
    // not currently implemented.
    //"shared-worker-frame-lifecycle.html",
    //"shared-worker-lifecycle.html",
    "shared-worker-load-error.html",
    "shared-worker-location.html",
    "shared-worker-name.html",
    "shared-worker-navigator.html",
    "shared-worker-replace-global-constructor.html",
    "shared-worker-replace-self.html",
    "shared-worker-script-error.html",
    "shared-worker-shared.html",
    "shared-worker-simple.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) {
    RunLayoutTest(kLayoutTestFiles[i], false);
    // Shared workers will error out if we ever have more than one tab open.
    int window_count = 0;
    ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    ASSERT_EQ(1, window_count);
    EXPECT_EQ(1, GetTabCount());
  }
}

TEST_F(WorkerTest, WorkerHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-importScripts.html",
    "shared-worker-redirect.html",
    // flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "worker-importScripts.html",
#endif
    "worker-redirect.html",
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

#if defined(OS_LINUX)
// Fails running under valgrind http://crbug.com/28445
#define WorkerXhrHttpLayoutTests DISABLED_WorkerXhrHttpLayoutTests
#endif

TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "abort-exception-assert.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "close.html",
#endif
    // These tests (and the shared-worker versions below) are disabled due to
    // limitations in lighttpd (doesn't handle all of the HTTP methods).
    //"methods-async.html",
    //"methods.html",

    "shared-worker-close.html",
    // Disabled due to limitations in lighttpd (does not handle methods other
    // than GET/PUT/POST).
    //"shared-worker-methods-async.html",
    //"shared-worker-methods.html",
    "shared-worker-xhr-file-not-found.html",

    "xmlhttprequest-file-not-found.html"
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, MessagePorts) {
  static const char* kLayoutTestFiles[] = {
    "message-channel-gc.html",
    "message-channel-gc-2.html",
    "message-channel-gc-3.html",
    "message-channel-gc-4.html",
    "message-port.html",
    "message-port-clone.html",
    "message-port-constructor-for-deleted-document.html",
    "message-port-deleted-document.html",
    "message-port-deleted-frame.html",
    "message-port-inactive-document.html",
    "message-port-multi.html",
    "message-port-no-wrapper.html",
    // Only works with run-webkit-tests --leaks.
    //"message-channel-listener-circular-ownership.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("events");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // MessagePort tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));

  ASSERT_TRUE(WaitForProcessCountToBe(1, max_workers_per_tab));
}
#endif

#if defined(OS_LINUX)
// Fails (crashes) on Linux Tests: http://crbug.com/28445
#define LimitTotal DISABLED_LimitTotal
#elif defined(OS_MACOSX)
// Doesn't crash, but on Mac it sometimes fails for a few runs in a row,
// http://crbug.com/28445
#define LimitTotal FLAKY_LimitTotal
#endif

TEST_F(WorkerTest, LimitTotal) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  int total_workers = WorkerService::kMaxWorkersWhenSeparate;

  int tab_count = (total_workers / max_workers_per_tab) + 1;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  for (int i = 1; i < tab_count; ++i)
    window->AppendTab(url);

  // Check that we didn't create more than the max number of workers.
  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));

  // Now close a page and check that the queued workers were started.
  tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));

  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome_frame/http_negotiate.h"

#include <atlbase.h>
#include <atlcom.h>
#include <htiframe.h>

#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"

#include "chrome_frame/bho.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/urlmon_url_request.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"

#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"

const wchar_t kChromeMimeType[] = L"application/chromepage";
const char kUACompatibleHttpHeader[] = "x-ua-compatible";

// From the latest urlmon.h. Symbol name prepended with LOCAL_ to
// avoid conflict (and therefore build errors) for those building with
// a newer Windows SDK.
// TODO(robertshield): Remove this once we update our SDK version.
static const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54;

static const int kHttpNegotiateBeginningTransactionIndex = 3;
static const int kHttpNegotiateOnResponseTransactionIndex = 4;

BEGIN_VTABLE_PATCHES(IHttpNegotiate)
  VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex,
                     HttpNegotiatePatch::BeginningTransaction)
  VTABLE_PATCH_ENTRY(kHttpNegotiateOnResponseTransactionIndex,
                     HttpNegotiatePatch::OnResponse)
END_VTABLE_PATCHES()

static const int kBindStatusCallbackStartBindingIndex = 3;

BEGIN_VTABLE_PATCHES(IBindStatusCallback)
  VTABLE_PATCH_ENTRY(kBindStatusCallbackStartBindingIndex,
                     HttpNegotiatePatch::StartBinding)
END_VTABLE_PATCHES()

static const int kInternetProtocolSinkReportProgressIndex = 4;

BEGIN_VTABLE_PATCHES(IInternetProtocolSink)
  VTABLE_PATCH_ENTRY(kInternetProtocolSinkReportProgressIndex,
                     HttpNegotiatePatch::ReportProgress)
END_VTABLE_PATCHES()

namespace {

class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>,
                                 public IBindStatusCallback {
 public:
  BEGIN_COM_MAP(SimpleBindStatusCallback)
    COM_INTERFACE_ENTRY(IBindStatusCallback)
  END_COM_MAP()

  // IBindStatusCallback implementation
  STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) {
    return E_NOTIMPL;
  }

  STDMETHOD(GetPriority)(LONG* priority) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnLowResource)(DWORD reserved) {
    return E_NOTIMPL;
  }

  STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress,
                        ULONG status_code, LPCWSTR status_text) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) {
    return E_NOTIMPL;
  }

  STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
    return E_NOTIMPL;
  }

  STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc,
    STGMEDIUM* storage) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) {
    return E_NOTIMPL;
  }
};

// Attempts to get to the associated browser service for an active request.
HRESULT GetBrowserServiceFromProtocolSink(IInternetProtocolSink* sink,
                                          IBrowserService** browser_service) {
  DCHECK(browser_service);
  // When fetching a page for the first time (not cached), we can query the
  // sink directly for IID_IShellBrowser to get the browser service.
  HRESULT hr = DoQueryService(IID_IShellBrowser, sink, browser_service);
  if (FAILED(hr)) {
    // When the request is being served up from the cache, we have to take
    // a different route via IID_ITargetFrame2.
    ScopedComPtr<IWebBrowser2> browser2;
    hr = DoQueryService(IID_ITargetFrame2, sink, browser2.Receive());
    if (browser2) {
      hr = DoQueryService(IID_IShellBrowser, browser2, browser_service);
    }
  }

  return hr;
}

}  // end namespace

HttpNegotiatePatch::HttpNegotiatePatch() {
}

HttpNegotiatePatch::~HttpNegotiatePatch() {
}

// static
bool HttpNegotiatePatch::Initialize() {
  if (IS_PATCHED(IHttpNegotiate)) {
    DLOG(WARNING) << __FUNCTION__ << " called more than once.";
    return true;
  }
  // Use our SimpleBindStatusCallback class as we need a temporary object that
  // implements IBindStatusCallback.
  CComObjectStackEx<SimpleBindStatusCallback> request;
  ScopedComPtr<IBindCtx> bind_ctx;
  HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive());
  DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx";
  if (bind_ctx) {
    ScopedComPtr<IUnknown> bscb_holder;
    bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive());
    if (bscb_holder) {
      hr = PatchHttpNegotiate(bscb_holder);
    } else {
      NOTREACHED() << "Failed to get _BSCB_Holder_";
      hr = E_UNEXPECTED;
    }
    bind_ctx.Release();
  }

  return SUCCEEDED(hr);
}

// static
void HttpNegotiatePatch::Uninitialize() {
  vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo);
}

// static
HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) {
  DCHECK(to_patch);
  DCHECK_IS_NOT_PATCHED(IHttpNegotiate);

  ScopedComPtr<IHttpNegotiate> http;
  HRESULT hr = http.QueryFrom(to_patch);
  if (FAILED(hr)) {
    hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive());
  }

  if (http) {
    hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo);
    DLOG_IF(ERROR, FAILED(hr))
        << StringPrintf("HttpNegotiate patch failed 0x%08X", hr);
  } else {
    DLOG(WARNING)
        << StringPrintf("IHttpNegotiate not supported 0x%08X", hr);
  }

  ScopedComPtr<IBindStatusCallback> bscb;
  hr = bscb.QueryFrom(to_patch);

  if (bscb) {
    hr = vtable_patch::PatchInterfaceMethods(bscb,
                                             IBindStatusCallback_PatchInfo);
    DLOG_IF(ERROR, FAILED(hr))
        << StringPrintf("BindStatusCallback patch failed 0x%08X", hr);
  } else {
    DLOG(WARNING) << StringPrintf("IBindStatusCallback not supported 0x%08X",
                                  hr);
  }
  return hr;
}

// static
HRESULT HttpNegotiatePatch::BeginningTransaction(
    IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me,
    LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) {
  DLOG(INFO) << __FUNCTION__ << " " << url << " headers:\n" << headers;

  HRESULT hr = original(me, url, headers, reserved, additional_headers);

  if (FAILED(hr)) {
    DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error";
    return hr;
  }

  ScopedComPtr<IWebBrowser2> browser2;
  DoQueryService(IID_ITargetFrame2, me, browser2.Receive());
  if (browser2) {
    Bho* bho = Bho::GetCurrentThreadBhoInstance();
    if (bho) {
      bho->OnBeginningTransaction(browser2, url, headers, *additional_headers);
    }
  }

  static const char kLowerCaseUserAgent[] = "user-agent";

  using net::HttpUtil;

  std::string ascii_headers;
  if (*additional_headers) {
    ascii_headers = WideToASCII(*additional_headers);
    DLOG(INFO) << __FUNCTION__ << " additional headers: " << ascii_headers;
  }

  HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
                                             ascii_headers.end(), "\r\n");
  std::string user_agent_value;
  if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) {
    user_agent_value = headers_iterator.values();
  } else if (headers != NULL) {
    // See if there's a user-agent header specified in the original headers.
    std::string original_headers(WideToASCII(headers));
    HttpUtil::HeadersIterator original_it(original_headers.begin(),
                                          original_headers.end(), "\r\n");
    if (original_it.AdvanceTo(kLowerCaseUserAgent))
      user_agent_value = original_it.values();
  }

  // Use the default one if none was provided.
  if (user_agent_value.empty())
    user_agent_value = http_utils::GetDefaultUserAgent();

  // Now add chromeframe to it.
  user_agent_value = http_utils::AddChromeFrameToUserAgentValue(
      user_agent_value);

  // Build new headers, skip the existing user agent value from
  // existing headers.
  std::string new_headers;
  headers_iterator.Reset();
  while (headers_iterator.GetNext()) {
    std::string name(headers_iterator.name());
    if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
      new_headers += name + ": " + headers_iterator.values() + "\r\n";
    }
  }

  new_headers += "User-Agent: " + user_agent_value;
  new_headers += "\r\n\r\n";

  if (*additional_headers)
    ::CoTaskMemFree(*additional_headers);
  *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemAlloc(
      (new_headers.length() + 1) * sizeof(wchar_t)));
  lstrcpyW(*additional_headers, ASCIIToWide(new_headers).c_str());

  return hr;
}

// static
HRESULT HttpNegotiatePatch::OnResponse(IHttpNegotiate_OnResponse_Fn original,
    IHttpNegotiate* me, DWORD response_code, LPCWSTR response_header,
    LPCWSTR request_header, LPWSTR* additional_request_headers) {
  DLOG(INFO) << __FUNCTION__ << " headers: " << std::endl << response_header;

  HRESULT hr = original(me, response_code, response_header, request_header,
                        additional_request_headers);
  return hr;
}

// static
HRESULT HttpNegotiatePatch::StartBinding(
    IBindStatusCallback_StartBinding_Fn original,
    IBindStatusCallback* me, DWORD reserved, IBinding* binding) {
  ScopedComPtr<IBinding> local_binding(binding);
  ScopedComPtr<IInternetProtocolSink> protocol_sink;

  HRESULT hr = protocol_sink.QueryFrom(local_binding);
  if (FAILED(hr) || !protocol_sink) {
    DLOG(WARNING) << "Failed to get IInternetProtocolSink from IBinding: "
                  << hr;
  } else {
    if (!IS_PATCHED(IInternetProtocolSink)) {
      hr = vtable_patch::PatchInterfaceMethods(protocol_sink,
                                               IInternetProtocolSink_PatchInfo);
    }

    DLOG_IF(WARNING, FAILED(hr))
        << "Failed to patch IInternetProtocolSink from IBinding: " << hr;
  }

  hr = original(me, reserved, binding);
  return hr;
}

// static
HRESULT HttpNegotiatePatch::ReportProgress(
    IInternetProtocolSink_ReportProgress_Fn original, IInternetProtocolSink* me,
    ULONG status_code, LPCWSTR status_text) {
  if (status_code == BINDSTATUS_MIMETYPEAVAILABLE ||
      status_code == BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE ||
      status_code == LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE) {
    bool render_in_chrome_frame = false;
    bool is_top_level_request = !IsSubFrameRequest(me);

    // NOTE: After switching over to using the onhttpequiv notification from
    // mshtml we can expect to see sub frames being created even before the
    // owning document has completed loading.  In particular frames whose
    // source is about:blank.

    if (is_top_level_request) {
      ScopedComPtr<IBrowserService> browser;
      GetBrowserServiceFromProtocolSink(me, browser.Receive());
      if (browser) {
        render_in_chrome_frame = CheckForCFNavigation(browser, true);
      }

      if (!render_in_chrome_frame) {
        // Check to see if we need to alter the mime type that gets reported
        // by inspecting the raw header information:
        ScopedComPtr<IWinInetHttpInfo> win_inet_http_info;
        HRESULT hr = win_inet_http_info.QueryFrom(me);

        // Try slightly harder if we couldn't QI directly.
        if (!win_inet_http_info || FAILED(hr)) {
          hr = DoQueryService(IID_IWinInetHttpInfo, me,
                              win_inet_http_info.Receive());
        }

        // Note that it has been observed that getting an IWinInetHttpInfo will
        // fail if we are loading a page like about:blank that isn't loaded via
        // wininet.
        if (win_inet_http_info) {
          // We have headers: check to see if the server is requesting CF via
          // the X-UA-Compatible: chrome=1 HTTP header.
          std::string headers(GetRawHttpHeaders(win_inet_http_info));
          net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(),
                                            "\r\n");
          while (it.GetNext()) {
            if (LowerCaseEqualsASCII(it.name_begin(), it.name_end(),
                                     kUACompatibleHttpHeader)) {
                std::string ua_value(StringToLowerASCII(it.values()));
                if (ua_value.find("chrome=1") != std::string::npos) {
                  render_in_chrome_frame = true;
                  break;
                }
            }
          }
        }
      }
    }

    if (render_in_chrome_frame) {
      status_text = kChromeMimeType;
    }
  }

  return original(me, status_code, status_text);
}
<commit_msg>Releasing the IBindStatusCallback_PatchInfo patch after we've applied the IInternetProtocolSink_PatchInfo one.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome_frame/http_negotiate.h"

#include <atlbase.h>
#include <atlcom.h>
#include <htiframe.h>

#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"

#include "chrome_frame/bho.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/urlmon_url_request.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"

#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"

const wchar_t kChromeMimeType[] = L"application/chromepage";
const char kUACompatibleHttpHeader[] = "x-ua-compatible";

// From the latest urlmon.h. Symbol name prepended with LOCAL_ to
// avoid conflict (and therefore build errors) for those building with
// a newer Windows SDK.
// TODO(robertshield): Remove this once we update our SDK version.
static const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54;

static const int kHttpNegotiateBeginningTransactionIndex = 3;
static const int kHttpNegotiateOnResponseTransactionIndex = 4;

BEGIN_VTABLE_PATCHES(IHttpNegotiate)
  VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex,
                     HttpNegotiatePatch::BeginningTransaction)
  VTABLE_PATCH_ENTRY(kHttpNegotiateOnResponseTransactionIndex,
                     HttpNegotiatePatch::OnResponse)
END_VTABLE_PATCHES()

static const int kBindStatusCallbackStartBindingIndex = 3;

BEGIN_VTABLE_PATCHES(IBindStatusCallback)
  VTABLE_PATCH_ENTRY(kBindStatusCallbackStartBindingIndex,
                     HttpNegotiatePatch::StartBinding)
END_VTABLE_PATCHES()

static const int kInternetProtocolSinkReportProgressIndex = 4;

BEGIN_VTABLE_PATCHES(IInternetProtocolSink)
  VTABLE_PATCH_ENTRY(kInternetProtocolSinkReportProgressIndex,
                     HttpNegotiatePatch::ReportProgress)
END_VTABLE_PATCHES()

namespace {

class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>,
                                 public IBindStatusCallback {
 public:
  BEGIN_COM_MAP(SimpleBindStatusCallback)
    COM_INTERFACE_ENTRY(IBindStatusCallback)
  END_COM_MAP()

  // IBindStatusCallback implementation
  STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) {
    return E_NOTIMPL;
  }

  STDMETHOD(GetPriority)(LONG* priority) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnLowResource)(DWORD reserved) {
    return E_NOTIMPL;
  }

  STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress,
                        ULONG status_code, LPCWSTR status_text) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) {
    return E_NOTIMPL;
  }

  STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
    return E_NOTIMPL;
  }

  STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc,
    STGMEDIUM* storage) {
    return E_NOTIMPL;
  }
  STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) {
    return E_NOTIMPL;
  }
};

// Attempts to get to the associated browser service for an active request.
HRESULT GetBrowserServiceFromProtocolSink(IInternetProtocolSink* sink,
                                          IBrowserService** browser_service) {
  DCHECK(browser_service);
  // When fetching a page for the first time (not cached), we can query the
  // sink directly for IID_IShellBrowser to get the browser service.
  HRESULT hr = DoQueryService(IID_IShellBrowser, sink, browser_service);
  if (FAILED(hr)) {
    // When the request is being served up from the cache, we have to take
    // a different route via IID_ITargetFrame2.
    ScopedComPtr<IWebBrowser2> browser2;
    hr = DoQueryService(IID_ITargetFrame2, sink, browser2.Receive());
    if (browser2) {
      hr = DoQueryService(IID_IShellBrowser, browser2, browser_service);
    }
  }

  return hr;
}

}  // end namespace

HttpNegotiatePatch::HttpNegotiatePatch() {
}

HttpNegotiatePatch::~HttpNegotiatePatch() {
}

// static
bool HttpNegotiatePatch::Initialize() {
  if (IS_PATCHED(IHttpNegotiate)) {
    DLOG(WARNING) << __FUNCTION__ << " called more than once.";
    return true;
  }
  // Use our SimpleBindStatusCallback class as we need a temporary object that
  // implements IBindStatusCallback.
  CComObjectStackEx<SimpleBindStatusCallback> request;
  ScopedComPtr<IBindCtx> bind_ctx;
  HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive());
  DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx";
  if (bind_ctx) {
    ScopedComPtr<IUnknown> bscb_holder;
    bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive());
    if (bscb_holder) {
      hr = PatchHttpNegotiate(bscb_holder);
    } else {
      NOTREACHED() << "Failed to get _BSCB_Holder_";
      hr = E_UNEXPECTED;
    }
    bind_ctx.Release();
  }

  return SUCCEEDED(hr);
}

// static
void HttpNegotiatePatch::Uninitialize() {
  vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo);
}

// static
HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) {
  DCHECK(to_patch);
  DCHECK_IS_NOT_PATCHED(IHttpNegotiate);

  ScopedComPtr<IHttpNegotiate> http;
  HRESULT hr = http.QueryFrom(to_patch);
  if (FAILED(hr)) {
    hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive());
  }

  if (http) {
    hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo);
    DLOG_IF(ERROR, FAILED(hr))
        << StringPrintf("HttpNegotiate patch failed 0x%08X", hr);
  } else {
    DLOG(WARNING)
        << StringPrintf("IHttpNegotiate not supported 0x%08X", hr);
  }

  ScopedComPtr<IBindStatusCallback> bscb;
  hr = bscb.QueryFrom(to_patch);

  if (bscb) {
    hr = vtable_patch::PatchInterfaceMethods(bscb,
                                             IBindStatusCallback_PatchInfo);
    DLOG_IF(ERROR, FAILED(hr))
        << StringPrintf("BindStatusCallback patch failed 0x%08X", hr);
  } else {
    DLOG(WARNING) << StringPrintf("IBindStatusCallback not supported 0x%08X",
                                  hr);
  }
  return hr;
}

// static
HRESULT HttpNegotiatePatch::BeginningTransaction(
    IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me,
    LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) {
  DLOG(INFO) << __FUNCTION__ << " " << url << " headers:\n" << headers;

  HRESULT hr = original(me, url, headers, reserved, additional_headers);

  if (FAILED(hr)) {
    DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error";
    return hr;
  }

  ScopedComPtr<IWebBrowser2> browser2;
  DoQueryService(IID_ITargetFrame2, me, browser2.Receive());
  if (browser2) {
    Bho* bho = Bho::GetCurrentThreadBhoInstance();
    if (bho) {
      bho->OnBeginningTransaction(browser2, url, headers, *additional_headers);
    }
  }

  static const char kLowerCaseUserAgent[] = "user-agent";

  using net::HttpUtil;

  std::string ascii_headers;
  if (*additional_headers) {
    ascii_headers = WideToASCII(*additional_headers);
    DLOG(INFO) << __FUNCTION__ << " additional headers: " << ascii_headers;
  }

  HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
                                             ascii_headers.end(), "\r\n");
  std::string user_agent_value;
  if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) {
    user_agent_value = headers_iterator.values();
  } else if (headers != NULL) {
    // See if there's a user-agent header specified in the original headers.
    std::string original_headers(WideToASCII(headers));
    HttpUtil::HeadersIterator original_it(original_headers.begin(),
                                          original_headers.end(), "\r\n");
    if (original_it.AdvanceTo(kLowerCaseUserAgent))
      user_agent_value = original_it.values();
  }

  // Use the default one if none was provided.
  if (user_agent_value.empty())
    user_agent_value = http_utils::GetDefaultUserAgent();

  // Now add chromeframe to it.
  user_agent_value = http_utils::AddChromeFrameToUserAgentValue(
      user_agent_value);

  // Build new headers, skip the existing user agent value from
  // existing headers.
  std::string new_headers;
  headers_iterator.Reset();
  while (headers_iterator.GetNext()) {
    std::string name(headers_iterator.name());
    if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
      new_headers += name + ": " + headers_iterator.values() + "\r\n";
    }
  }

  new_headers += "User-Agent: " + user_agent_value;
  new_headers += "\r\n\r\n";

  if (*additional_headers)
    ::CoTaskMemFree(*additional_headers);
  *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemAlloc(
      (new_headers.length() + 1) * sizeof(wchar_t)));
  lstrcpyW(*additional_headers, ASCIIToWide(new_headers).c_str());

  return hr;
}

// static
HRESULT HttpNegotiatePatch::OnResponse(IHttpNegotiate_OnResponse_Fn original,
    IHttpNegotiate* me, DWORD response_code, LPCWSTR response_header,
    LPCWSTR request_header, LPWSTR* additional_request_headers) {
  DLOG(INFO) << __FUNCTION__ << " headers: " << std::endl << response_header;

  HRESULT hr = original(me, response_code, response_header, request_header,
                        additional_request_headers);
  return hr;
}

// static
HRESULT HttpNegotiatePatch::StartBinding(
    IBindStatusCallback_StartBinding_Fn original,
    IBindStatusCallback* me, DWORD reserved, IBinding* binding) {
  ScopedComPtr<IBinding> local_binding(binding);
  ScopedComPtr<IInternetProtocolSink> protocol_sink;

  HRESULT hr = protocol_sink.QueryFrom(local_binding);
  if (FAILED(hr) || !protocol_sink) {
    DLOG(WARNING) << "Failed to get IInternetProtocolSink from IBinding: "
                  << hr;
  } else {
    if (!IS_PATCHED(IInternetProtocolSink)) {
      hr = vtable_patch::PatchInterfaceMethods(protocol_sink,
                                               IInternetProtocolSink_PatchInfo);
      DCHECK(SUCCEEDED(hr));
      // Now that we've gotten to the protocol sink,
      // we don't need this patch anymore.
      HRESULT hr_unpatch = vtable_patch::UnpatchInterfaceMethods(
          IBindStatusCallback_PatchInfo);
      DCHECK(SUCCEEDED(hr_unpatch));
    }

    DLOG_IF(WARNING, FAILED(hr))
        << "Failed to patch IInternetProtocolSink from IBinding: " << hr;
  }

  hr = original(me, reserved, binding);
  return hr;
}

// static
HRESULT HttpNegotiatePatch::ReportProgress(
    IInternetProtocolSink_ReportProgress_Fn original, IInternetProtocolSink* me,
    ULONG status_code, LPCWSTR status_text) {
  if (status_code == BINDSTATUS_MIMETYPEAVAILABLE ||
      status_code == BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE ||
      status_code == LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE) {
    bool render_in_chrome_frame = false;
    bool is_top_level_request = !IsSubFrameRequest(me);

    // NOTE: After switching over to using the onhttpequiv notification from
    // mshtml we can expect to see sub frames being created even before the
    // owning document has completed loading.  In particular frames whose
    // source is about:blank.

    if (is_top_level_request) {
      ScopedComPtr<IBrowserService> browser;
      GetBrowserServiceFromProtocolSink(me, browser.Receive());
      if (browser) {
        render_in_chrome_frame = CheckForCFNavigation(browser, true);
      }

      if (!render_in_chrome_frame) {
        // Check to see if we need to alter the mime type that gets reported
        // by inspecting the raw header information:
        ScopedComPtr<IWinInetHttpInfo> win_inet_http_info;
        HRESULT hr = win_inet_http_info.QueryFrom(me);

        // Try slightly harder if we couldn't QI directly.
        if (!win_inet_http_info || FAILED(hr)) {
          hr = DoQueryService(IID_IWinInetHttpInfo, me,
                              win_inet_http_info.Receive());
        }

        // Note that it has been observed that getting an IWinInetHttpInfo will
        // fail if we are loading a page like about:blank that isn't loaded via
        // wininet.
        if (win_inet_http_info) {
          // We have headers: check to see if the server is requesting CF via
          // the X-UA-Compatible: chrome=1 HTTP header.
          std::string headers(GetRawHttpHeaders(win_inet_http_info));
          net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(),
                                            "\r\n");
          while (it.GetNext()) {
            if (LowerCaseEqualsASCII(it.name_begin(), it.name_end(),
                                     kUACompatibleHttpHeader)) {
                std::string ua_value(StringToLowerASCII(it.values()));
                if (ua_value.find("chrome=1") != std::string::npos) {
                  render_in_chrome_frame = true;
                  break;
                }
            }
          }
        }
      }
    }

    if (render_in_chrome_frame) {
      status_text = kChromeMimeType;
    }
  }

  return original(me, status_code, status_text);
}
<|endoftext|>


<commit_before>//===-- ClangdFuzzer.cpp - Fuzz clangd ------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs clangd on a single input.
/// This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "ClangdLSPServer.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include <sstream>
#include <stdio.h>

extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
  clang::clangd::JSONOutput Out(llvm::nulls(), llvm::nulls(),
                                clang::clangd::Logger::Error, nullptr);
  clang::clangd::CodeCompleteOptions CCOpts;
  CCOpts.EnableSnippets = false;
  clang::clangd::ClangdServer::Options Opts;

  // Initialize and run ClangdLSPServer.
  clang::clangd::ClangdLSPServer LSPServer(Out, CCOpts, llvm::None, Opts);
  // fmemopen isn't portable, but I think we only run the fuzzer on Linux.
  LSPServer.run(fmemopen(data, size, "r"));
  return 0;
}
<commit_msg>[clangd] Guard fuzzer against empty inputs.<commit_after>//===-- ClangdFuzzer.cpp - Fuzz clangd ------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs clangd on a single input.
/// This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "ClangdLSPServer.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include <sstream>
#include <stdio.h>

extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
  if (size == 0)
    return 0;

  clang::clangd::JSONOutput Out(llvm::nulls(), llvm::nulls(),
                                clang::clangd::Logger::Error, nullptr);
  clang::clangd::CodeCompleteOptions CCOpts;
  CCOpts.EnableSnippets = false;
  clang::clangd::ClangdServer::Options Opts;

  // Initialize and run ClangdLSPServer.
  clang::clangd::ClangdLSPServer LSPServer(Out, CCOpts, llvm::None, Opts);
  // fmemopen isn't portable, but I think we only run the fuzzer on Linux.
  LSPServer.run(fmemopen(data, size, "r"));
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/net/http/CookieJar.h"

#include "db/util/StringTokenizer.h"

using namespace std;
using namespace db::net::http;
using namespace db::rt;
using namespace db::util;

CookieJar::CookieJar()
{
   mCookies->setType(Map);
}

CookieJar::~CookieJar()
{
}

void CookieJar::readCookies(HttpHeader* header, CookieOrigin origin)
{
   // parse cookies if appropriate cookie field exists
   const char* field = (origin == Server ? "Set-Cookie" : "Cookie");
   int count = header->getFieldCount(field);
   if(count > 0)
   {
      // Set-Cookie: cookie1_name=cookie1_value; max-age=0; path=/
      // Set-Cookie: c2=v2; expires=Thu, 21-Aug-2008 23:47:25 GMT; path=/
      // Cookie: cookie1_name=cookie1_value; cookie2_name=cookie2_value

      // parse cookies by semi-colons (cannot parse by commas because
      // the "expires" value may contain a comma and no one follows the
      // standard)
      string cookies;
      Cookie cookie(NULL);
      TimeZone gmt = TimeZone::getTimeZone("GMT");
      Date d;
      Date now;
      bool name;
      StringTokenizer pairs;
      for(int i = 0; i < count; i++)
      {
         name = true;
         header->getField(field, cookies, i);
         pairs.tokenize(cookies.c_str(), ';');
         while(pairs.hasNextToken())
         {
            // get next token (name=value)
            const char* token = pairs.nextToken();

            // get name part of token
            size_t nameLength = strcspn(token, "=");
            char tmpName[nameLength + 1];
            strncpy(tmpName, token, nameLength);
            tmpName[nameLength] = 0;

            // trim whitespace from name
            char* namePtr = (tmpName + nameLength);
            for(; namePtr != tmpName && *namePtr == ' '; namePtr--)
            {
               *namePtr = 0;
            }
            for(namePtr = tmpName; *namePtr != 0 && *namePtr == ' ';
                namePtr++);

            // get value part of token (ensure value length is at least 0 in
            // case bad parsing because of no equals sign after name)
            size_t valueLength = strlen(token);
            valueLength = (nameLength == valueLength ?
               0 : valueLength - nameLength - 1);
            char tmpValue[valueLength + 1];
            if(valueLength > 0)
            {
               strncpy(tmpValue, token + nameLength + 1, valueLength);
            }
            tmpValue[valueLength] = 0;

            if(origin == Client)
            {
               // set cookie
               setCookie(namePtr, tmpValue, 0, false, false);
            }
            else
            {
               if(name)
               {
                  // first token *must* be cookie name = cookie value
                  cookie = Cookie();
                  cookie["name"] = namePtr;
                  cookie["value"] = tmpValue;
                  name = false;
               }
               else
               {
                  if(strcmp(namePtr, "expires") == 0)
                  {
                     // parse expiration time
                     if(d.parse(tmpValue, HttpHeader::sDateFormat, &gmt))
                     {
                        int age = d.second() - now.second();
                        cookie["maxAge"] = (age <= 0 ? 0 : age);
                     }
                     else
                     {
                        // bad date format, use maxAge of 0
                        cookie["maxAge"] = 0;
                     }
                  }
                  else if(strcasecmp(namePtr, "secure") == 0)
                  {
                     // cookie is secure
                     cookie["secure"] = true;
                  }
                  else if(strcasecmp(namePtr, "HttpOnly") == 0)
                  {
                     // cookie is http-only (non-javascript)
                     cookie["httpOnly"] = true;
                  }
                  else
                  {
                     // not first token or expires, set other cookie parameter
                     cookie[namePtr] = tmpValue;
                  }
               }

               // add cookie if last token
               if(!pairs.hasNextToken())
               {
                  // cookie not secure if no secure value found
                  if(!cookie->hasMember("secure"))
                  {
                     cookie["secure"] = false;
                  }

                  // cookie is not http-only if no HttpOnly value found
                  if(!cookie->hasMember("httpOnly"))
                  {
                     cookie["httpOnly"] = false;
                  }

                  mCookies[cookie["name"]->getString()] = cookie;
                  cookie.setNull();
               }
            }
         }
      }
   }
}

bool CookieJar::writeCookies(
   HttpHeader* header, CookieOrigin origin, bool overwrite)
{
   bool rval = true;

   // get header field name
   const char* field = (origin == Server ? "Set-Cookie" : "Cookie");

   // if overwriting, remove existing field
   if(overwrite)
   {
      header->removeField(field);
   }

   // if cookies exist, convert all cookies to string
   if(mCookies->length() > 0)
   {
      TimeZone gmt = TimeZone::getTimeZone("GMT");
      Date d;
      int age;
      string str;
      CookieIterator i = mCookies.getIterator();
      while(i->hasNext())
      {
         Cookie& cookie = i->next();

         // only write out cookie if not expired or if origin is Server
         age = cookie["maxAge"]->getInt32();
         if(origin == Server || age != 0)
         {
            if(origin == Client)
            {
               // append semi-colon and space if not first cookie
               if(str.length() > 0)
               {
                  str.append("; ");
               }
            }

            // output cookie name and value
            str.append(cookie["name"]->getString());
            str.push_back('=');
            str.append(cookie["value"]->getString());

            // only send out other cookie data if writing out Set-Cookie
            if(origin == Server)
            {
               // output comment if appropriate
               if(cookie->hasMember("comment"))
               {
                  str.append("; comment=");
                  str.append(cookie["comment"]->getString());
               }

               // output "expires" value if appropriate
               if(age > 0)
               {
                  str.append("; expires=");
                  d.addSeconds(age);
                  str.append(d.toString(HttpHeader::sDateFormat, &gmt));
                  d.addSeconds(-age);
               }
               else if(age == 0)
               {
                  // expire cookie
                  str.append("; max-age=0");
               }

               // output path
               str.append("; path=");
               str.append(cookie["path"]->getString());

               // output secure if appropriate
               if(cookie["secure"]->getBoolean())
               {
                  str.append("; secure");
               }

               // output http only if appropriate
               if(cookie["httpOnly"]->getBoolean())
               {
                  str.append("; HttpOnly");
               }

               // output domain if appropriate
               if(cookie->hasMember("domain"))
               {
                  str.append("; domain=");
                  str.append(cookie["domain"]->getString());
               }

               // output version if appropriate
               if(cookie->hasMember("version"))
               {
                  str.append("; version=");
                  str.append(cookie["version"]->getString());
               }

               // add header field and clear string
               header->addField(field, str.c_str());
               str.erase();
            }
         }
      }

      if(origin == Client)
      {
         // add single header field
         header->addField(field, str.c_str());
      }
   }

   return rval;
}

void CookieJar::setCookie(Cookie& cookie)
{
   mCookies[cookie["name"]->getString()] = cookie;
}

void CookieJar::setCookie(
   const char* name, const char* value, int maxAge, bool secure, bool httpOnly,
   const char* path, const char* domain, int version)
{
   Cookie cookie;
   cookie["name"] = name;
   cookie["value"] = value;
   cookie["maxAge"] = maxAge;
   cookie["path"] = path;
   cookie["secure"] = secure;
   cookie["httpOnly"] = httpOnly;

   if(domain != NULL)
   {
      cookie["domain"] = domain;
   }

   if(version != 0)
   {
      cookie["version"] = version;
   }

   setCookie(cookie);
}

Cookie CookieJar::getCookie(const char* name)
{
   Cookie rval(NULL);

   if(mCookies->hasMember(name))
   {
      rval = mCookies[name];
   }

   return rval;
}

void CookieJar::deleteCookie(const char* name, bool secure)
{
   Cookie cookie = getCookie(name);
   if(cookie.isNull())
   {
      setCookie(name, "", 0, secure, false);
   }
   else
   {
      cookie["value"] = "";
      cookie["maxAge"] = 0;
      cookie["httpOnly"] = true;
   }
}

bool CookieJar::removeCookie(const char* name)
{
   bool rval = mCookies->hasMember(name);
   mCookies->removeMember(name);
   return rval;
}

void CookieJar::clearCookies()
{
   mCookies->clear();
}
<commit_msg>Fixed bug in setting max age for cookies.<commit_after>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/net/http/CookieJar.h"

#include "db/util/StringTokenizer.h"

using namespace std;
using namespace db::net::http;
using namespace db::rt;
using namespace db::util;

CookieJar::CookieJar()
{
   mCookies->setType(Map);
}

CookieJar::~CookieJar()
{
}

void CookieJar::readCookies(HttpHeader* header, CookieOrigin origin)
{
   // parse cookies if appropriate cookie field exists
   const char* field = (origin == Server ? "Set-Cookie" : "Cookie");
   int count = header->getFieldCount(field);
   if(count > 0)
   {
      // Set-Cookie: cookie1_name=cookie1_value; max-age=0; path=/
      // Set-Cookie: c2=v2; expires=Thu, 21-Aug-2008 23:47:25 GMT; path=/
      // Cookie: cookie1_name=cookie1_value; cookie2_name=cookie2_value

      // parse cookies by semi-colons (cannot parse by commas because
      // the "expires" value may contain a comma and no one follows the
      // standard)
      string cookies;
      Cookie cookie(NULL);
      TimeZone gmt = TimeZone::getTimeZone("GMT");
      Date d;
      Date now;
      bool name;
      StringTokenizer pairs;
      for(int i = 0; i < count; i++)
      {
         name = true;
         header->getField(field, cookies, i);
         pairs.tokenize(cookies.c_str(), ';');
         while(pairs.hasNextToken())
         {
            // get next token (name=value)
            const char* token = pairs.nextToken();

            // get name part of token
            size_t nameLength = strcspn(token, "=");
            char tmpName[nameLength + 1];
            strncpy(tmpName, token, nameLength);
            tmpName[nameLength] = 0;

            // trim whitespace from name
            char* namePtr = (tmpName + nameLength);
            for(; namePtr != tmpName && *namePtr == ' '; namePtr--)
            {
               *namePtr = 0;
            }
            for(namePtr = tmpName; *namePtr != 0 && *namePtr == ' ';
                namePtr++);

            // get value part of token (ensure value length is at least 0 in
            // case bad parsing because of no equals sign after name)
            size_t valueLength = strlen(token);
            valueLength = (nameLength == valueLength ?
               0 : valueLength - nameLength - 1);
            char tmpValue[valueLength + 1];
            if(valueLength > 0)
            {
               strncpy(tmpValue, token + nameLength + 1, valueLength);
            }
            tmpValue[valueLength] = 0;

            if(origin == Client)
            {
               // set cookie
               setCookie(namePtr, tmpValue, 0, false, false);
            }
            else
            {
               if(name)
               {
                  // first token *must* be cookie name = cookie value
                  cookie = Cookie();
                  cookie["name"] = namePtr;
                  cookie["value"] = tmpValue;
                  name = false;
               }
               else
               {
                  if(strcmp(namePtr, "expires") == 0)
                  {
                     // parse expiration time
                     if(d.parse(tmpValue, HttpHeader::sDateFormat, &gmt))
                     {
                        int64_t age = d.getSeconds() - now.getSeconds();
                        cookie["maxAge"] = (age <= 0 ? 0 : age);
                     }
                     else
                     {
                        // bad date format, use maxAge of 0
                        cookie["maxAge"] = 0;
                     }
                  }
                  else if(strcasecmp(namePtr, "secure") == 0)
                  {
                     // cookie is secure
                     cookie["secure"] = true;
                  }
                  else if(strcasecmp(namePtr, "HttpOnly") == 0)
                  {
                     // cookie is http-only (non-javascript)
                     cookie["httpOnly"] = true;
                  }
                  else
                  {
                     // not first token or expires, set other cookie parameter
                     cookie[namePtr] = tmpValue;
                  }
               }

               // add cookie if last token
               if(!pairs.hasNextToken())
               {
                  // cookie not secure if no secure value found
                  if(!cookie->hasMember("secure"))
                  {
                     cookie["secure"] = false;
                  }

                  // cookie is not http-only if no HttpOnly value found
                  if(!cookie->hasMember("httpOnly"))
                  {
                     cookie["httpOnly"] = false;
                  }

                  mCookies[cookie["name"]->getString()] = cookie;
                  cookie.setNull();
               }
            }
         }
      }
   }
}

bool CookieJar::writeCookies(
   HttpHeader* header, CookieOrigin origin, bool overwrite)
{
   bool rval = true;

   // get header field name
   const char* field = (origin == Server ? "Set-Cookie" : "Cookie");

   // if overwriting, remove existing field
   if(overwrite)
   {
      header->removeField(field);
   }

   // if cookies exist, convert all cookies to string
   if(mCookies->length() > 0)
   {
      TimeZone gmt = TimeZone::getTimeZone("GMT");
      Date d;
      int age;
      string str;
      CookieIterator i = mCookies.getIterator();
      while(i->hasNext())
      {
         Cookie& cookie = i->next();

         // only write out cookie if not expired or if origin is Server
         age = cookie["maxAge"]->getInt32();
         if(origin == Server || age != 0)
         {
            if(origin == Client)
            {
               // append semi-colon and space if not first cookie
               if(str.length() > 0)
               {
                  str.append("; ");
               }
            }

            // output cookie name and value
            str.append(cookie["name"]->getString());
            str.push_back('=');
            str.append(cookie["value"]->getString());

            // only send out other cookie data if writing out Set-Cookie
            if(origin == Server)
            {
               // output comment if appropriate
               if(cookie->hasMember("comment"))
               {
                  str.append("; comment=");
                  str.append(cookie["comment"]->getString());
               }

               // output "expires" value if appropriate
               if(age > 0)
               {
                  str.append("; expires=");
                  d.addSeconds(age);
                  str.append(d.toString(HttpHeader::sDateFormat, &gmt));
                  d.addSeconds(-age);
               }
               else if(age == 0)
               {
                  // expire cookie
                  str.append("; max-age=0");
               }

               // output path
               str.append("; path=");
               str.append(cookie["path"]->getString());

               // output secure if appropriate
               if(cookie["secure"]->getBoolean())
               {
                  str.append("; secure");
               }

               // output http only if appropriate
               if(cookie["httpOnly"]->getBoolean())
               {
                  str.append("; HttpOnly");
               }

               // output domain if appropriate
               if(cookie->hasMember("domain"))
               {
                  str.append("; domain=");
                  str.append(cookie["domain"]->getString());
               }

               // output version if appropriate
               if(cookie->hasMember("version"))
               {
                  str.append("; version=");
                  str.append(cookie["version"]->getString());
               }

               // add header field and clear string
               header->addField(field, str.c_str());
               str.erase();
            }
         }
      }

      if(origin == Client)
      {
         // add single header field
         header->addField(field, str.c_str());
      }
   }

   return rval;
}

void CookieJar::setCookie(Cookie& cookie)
{
   mCookies[cookie["name"]->getString()] = cookie;
}

void CookieJar::setCookie(
   const char* name, const char* value, int maxAge, bool secure, bool httpOnly,
   const char* path, const char* domain, int version)
{
   Cookie cookie;
   cookie["name"] = name;
   cookie["value"] = value;
   cookie["maxAge"] = maxAge;
   cookie["path"] = path;
   cookie["secure"] = secure;
   cookie["httpOnly"] = httpOnly;

   if(domain != NULL)
   {
      cookie["domain"] = domain;
   }

   if(version != 0)
   {
      cookie["version"] = version;
   }

   setCookie(cookie);
}

Cookie CookieJar::getCookie(const char* name)
{
   Cookie rval(NULL);

   if(mCookies->hasMember(name))
   {
      rval = mCookies[name];
   }

   return rval;
}

void CookieJar::deleteCookie(const char* name, bool secure)
{
   Cookie cookie = getCookie(name);
   if(cookie.isNull())
   {
      setCookie(name, "", 0, secure, false);
   }
   else
   {
      cookie["value"] = "";
      cookie["maxAge"] = 0;
      cookie["httpOnly"] = true;
   }
}

bool CookieJar::removeCookie(const char* name)
{
   bool rval = mCookies->hasMember(name);
   mCookies->removeMember(name);
   return rval;
}

void CookieJar::clearCookies()
{
   mCookies->clear();
}
<|endoftext|>


<commit_before>#include "Feeder.h"
#include <fstream>
#include <iostream>
using namespace std;

Feeder::Feeder(ifstream *ifs){
	if (ifs->fail()){
		cerr << "glue: script read error" << endl;
//		return EXIT_FAILURE;
	}
	m_ifs = ifs;
	m_cur_line = 0;
	m_cur_char = 0;

	readAll();
}

Feeder::~Feeder()
{
}

bool Feeder::readLine(void)
{
	string str;
	if(!getline(*m_ifs, str))
		return false;
	m_lines.push_back(str);
	return true;
}

void Feeder::close(void)
{
	if(m_ifs == NULL)
		return;

	m_ifs->close();
	m_ifs = NULL;
}

bool Feeder::command(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == ' ')
			break;
		if(c == '#'){
			break;
		}

		if(! isAlphabet(c) && ! isNum(c)
			&& c != '_' && c != '-' && c != '/')
			return false;
	}
	if(i == m_cur_char)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}

bool Feeder::smallCaps(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	int i = m_cur_char;
	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if( c < 'a' || c > 'z')
			break;
	}

	if(i == m_cur_char)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}

bool Feeder::blank(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	checkEol(p);
	p = &m_lines[m_cur_line];

	if(outOfRange())
		return false;

	int i = m_cur_char;
	if( p->size() < 1 || p->at(i) != ' ')
		return false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if( c != ' ' || c != '\t')
			break;
	}

	if(ans != NULL)
		*ans = string(p->c_str()+m_cur_char,i-m_cur_char);

	m_cur_char = i+1;
	checkEol(p);
	return true;
}

bool Feeder::path(string *ans)
{
	return command(ans);
}

bool Feeder::pipe(string *ans)
{
	if(outOfRange())
		return false;

	bool exist = false;
	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for( ;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '>'){
			if(i >= (int)p->length()-2)
				return false;
			if(p->at(i+1) == '>' && p->at(i+2) == '='){
				exist = true;
				i += 3;
				break;
			}
		}
	}
	if(! exist)
		return false;

	if(ans != NULL)
		*ans = string(p->c_str()+m_cur_char,i-m_cur_char);

	m_cur_char = i;
	checkEol(p);
	return true;
}

/*
bool Feeder::pipeEnd(string *ans)
{
	if(outOfRange())
		return false;

	bool comma = false;
	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for( ;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '.'){
			if(comma){
				return false; //more than one commas
			}else{
				comma = true;
				continue;
			}
		}else if(c != ' ' && c != '\t'){
			break;
		}
	}
	if(! comma)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}
*/

bool Feeder::variable(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	if(p->at(i) == '>' /*|| p->at(i) == '.'*/)
		return false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		//if(c == ',' || c == '.')
		if(c == '>')
			break;
		if(c == ' ')
			break;
		if(c == '#'){
			break;
		}

		if(! isAlphabet(c) && ! isNum(c) && c != '_' && c != '-')
			return false;
	}

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}
// arg should be a string that is quoted by '.
// This function gives escaped characters as
// they are escaped.
bool Feeder::literalString(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;

	if(p->at(i) != '\''){
		return false;
	}

	i++;

	bool escaped = false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '\\'){
			escaped = true;
			continue;
		}

		if(c == '\''){
			if(escaped){
				escaped = false;
				continue;
			}else{
				break;
			}
		}else{
			escaped = false;
		}

	}

	*ans = string(p->c_str()+m_cur_char+1,i-m_cur_char-1);
	m_cur_char = i+1;
	checkEol(p);
	return true;
}

void Feeder::readAll(void)
{
	while(readLine()){};
}

bool Feeder::atNewLine(void)
{
	return m_cur_char == 0;
}

bool Feeder::atEnd(void)
{
	return (m_cur_line == (int)m_lines.size()) && m_cur_char == 0;
}

bool Feeder::outOfRange(void)
{
	return (m_cur_line >= (int)m_lines.size());
}

bool Feeder::comment(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	// a blank line is treated as a comment
	if(p->length() == 0){
		*ans = "";
		m_cur_char = 0;
		m_cur_line++;

		while(m_cur_line < (int)m_lines.size()){
			if(m_lines[m_cur_line].length() != 0)
				break;

			*ans += "\n";
			m_cur_line++;
		}
		return true;
	}

	// #... is a comment
	if(p->at(m_cur_char) != '#')
		return false;

	*ans = string(p->c_str()+m_cur_char,p->length()-m_cur_char);

	m_cur_char = 0;
	m_cur_line++;
	return true;
}

bool Feeder::str(string s)
{
	if(outOfRange())
		return false;

	bool ans = false;

	string *p = &m_lines[m_cur_line];
	if(p->substr(m_cur_char,s.length()) == s){
		ans = true;
		m_cur_char += s.length();
	}

	checkEol(p);
	return ans;
}

bool Feeder::import(string *ans)
{
	return true;
}

// <reserved> variable = ...
bool Feeder::declare(string *ans, string reserved)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	int len = reserved.size();

	if(p->substr(0,len+1) != reserved + " ")
		return false;

	int i = m_cur_char + len + 1;
	for( ; i < (int)p->length() ;i++){
		if( ! isAlphabet(p->at(i)) )
			break;
	}
	int last = i;
	while(p->at(i) == ' ' || p->at(i) == '\t')
		i++;

	if(p->at(i++) != '=')
		return false;

	while(p->at(i) == ' ' || p->at(i) == '\t')
		i++;

	*ans = string(p->c_str()+m_cur_char+len+1,last-m_cur_char-len-1);
	m_cur_char = i;
	checkEol(p);
	return true;
}

void Feeder::checkEol(string *p)
{
	if(m_cur_char < (int)p->length())
		return;

	m_cur_char = 0;
	m_cur_line++;
}

bool Feeder::isAlphabet(char c)
{
	if(c >= 'a' && c <= 'z')
		return true;
	if(c >= 'A' && c <= 'Z')
		return true;

	return false;
}

bool Feeder::isNum(char c)
{
	if(c >= '0' && c <= '9')
		return true;

	return false;
}

void Feeder::debugOut(void)
{
	cerr << m_cur_line << " " << m_cur_char << endl;
}

void Feeder::getPos(int *ln,int *ch)
{
	*ln = m_cur_line;
	*ch = m_cur_char;
}

void Feeder::setPos(int ln,int ch)
{
	m_cur_line = ln;
	m_cur_char = ch;
}

void Feeder::printErrorPart(int from, int from_char, int to, int to_char)
{
	for(int i=from;i<to;i++){
		cerr << "\tline" << i+1 << ": " <<  m_lines[i] << endl;
		if(i == from){
			cerr << "\t";
			for(int j=-7;j<from_char;j++)
				cerr << " ";
			cerr << "^";
		}
	}
	if(to_char != 0)
		cerr << "\tline" << to+1 << ": " <<  m_lines[to] << endl;
}
<commit_msg>Bugfix<commit_after>#include "Feeder.h"
#include <fstream>
#include <iostream>
using namespace std;

Feeder::Feeder(ifstream *ifs){
	if (ifs->fail()){
		cerr << "glue: script read error" << endl;
//		return EXIT_FAILURE;
	}
	m_ifs = ifs;
	m_cur_line = 0;
	m_cur_char = 0;

	readAll();
}

Feeder::~Feeder()
{
}

bool Feeder::readLine(void)
{
	string str;
	if(!getline(*m_ifs, str))
		return false;
	m_lines.push_back(str);
	return true;
}

void Feeder::close(void)
{
	if(m_ifs == NULL)
		return;

	m_ifs->close();
	m_ifs = NULL;
}

bool Feeder::command(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == ' ')
			break;
		if(c == '#'){
			break;
		}

		if(! isAlphabet(c) && ! isNum(c)
			&& c != '_' && c != '-' && c != '/')
			return false;
	}
	if(i == m_cur_char)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}

bool Feeder::smallCaps(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	int i = m_cur_char;
	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if( c < 'a' || c > 'z')
			break;
	}

	if(i == m_cur_char)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}

bool Feeder::blank(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	checkEol(p);
	p = &m_lines[m_cur_line];

	if(outOfRange())
		return false;

	int i = m_cur_char;
	if( p->size() < 1 || p->at(i) != ' ')
		return false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if( c != ' ' || c != '\t')
			break;
	}

	if(ans != NULL)
		*ans = string(p->c_str()+m_cur_char,i-m_cur_char);

	m_cur_char = i+1;
	checkEol(p);
	return true;
}

bool Feeder::path(string *ans)
{
	return command(ans);
}

bool Feeder::pipe(string *ans)
{
	if(outOfRange())
		return false;

	bool exist = false;
	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for( ;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '>'){
			if(i >= (int)p->length()-2)
				return false;
			if(p->at(i+1) == '>' && p->at(i+2) == '='){
				exist = true;
				i += 3;
				break;
			}
		}
	}
	if(! exist)
		return false;

	if(ans != NULL)
		*ans = string(p->c_str()+m_cur_char,i-m_cur_char);

	m_cur_char = i;
	checkEol(p);
	return true;
}

/*
bool Feeder::pipeEnd(string *ans)
{
	if(outOfRange())
		return false;

	bool comma = false;
	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	for( ;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '.'){
			if(comma){
				return false; //more than one commas
			}else{
				comma = true;
				continue;
			}
		}else if(c != ' ' && c != '\t'){
			break;
		}
	}
	if(! comma)
		return false;

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}
*/

bool Feeder::variable(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;
	if(p->at(i) == '>' /*|| p->at(i) == '.'*/)
		return false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		//if(c == ',' || c == '.')
		if(c == '>')
			break;
		if(c == ' ')
			break;
		if(c == '#'){
			break;
		}

		if(! isAlphabet(c) && ! isNum(c) && c != '_' && c != '-')
			return false;
	}

	*ans = string(p->c_str()+m_cur_char,i-m_cur_char);
	m_cur_char = i;
	checkEol(p);
	return true;
}
// arg should be a string that is quoted by '.
// This function gives escaped characters as
// they are escaped.
bool Feeder::literalString(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];
	int i = m_cur_char;

	if(p->at(i) != '\''){
		return false;
	}

	i++;

	bool escaped = false;

	for(;i < (int)p->length();i++){
		char c = p->at(i);
		if(c == '\\'){
			escaped = true;
			continue;
		}

		if(c == '\''){
			if(escaped){
				escaped = false;
				continue;
			}else{
				break;
			}
		}else{
			escaped = false;
		}

	}

	*ans = string(p->c_str()+m_cur_char+1,i-m_cur_char-1);
	m_cur_char = i+1;
	checkEol(p);
	return true;
}

void Feeder::readAll(void)
{
	while(readLine()){};
}

bool Feeder::atNewLine(void)
{
	return m_cur_char == 0;
}

bool Feeder::atEnd(void)
{
	return (m_cur_line == (int)m_lines.size()) && m_cur_char == 0;
}

bool Feeder::outOfRange(void)
{
	return (m_cur_line >= (int)m_lines.size());
}

bool Feeder::comment(string *ans)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	// a blank line is treated as a comment
	if(p->length() == 0){
		*ans = "";
		m_cur_char = 0;
		m_cur_line++;

		while(m_cur_line < (int)m_lines.size()){
			if(m_lines[m_cur_line].length() != 0)
				break;

			*ans += "\n";
			m_cur_line++;
		}
		return true;
	}

	// #... is a comment
	if(p->at(m_cur_char) != '#')
		return false;

	*ans = string(p->c_str()+m_cur_char,p->length()-m_cur_char);

	m_cur_char = 0;
	m_cur_line++;
	return true;
}

bool Feeder::str(string s)
{
	if(outOfRange())
		return false;

	bool ans = false;

	string *p = &m_lines[m_cur_line];
	if(p->substr(m_cur_char,s.length()) == s){
		ans = true;
		m_cur_char += s.length();
	}

	checkEol(p);
	return ans;
}

bool Feeder::import(string *ans)
{
	return true;
}

// <reserved> variable = ...
bool Feeder::declare(string *ans, string reserved)
{
	if(outOfRange())
		return false;

	string *p = &m_lines[m_cur_line];

	int len = reserved.size();

	if(p->substr(0,len+1) != reserved + " ")
		return false;

	int i = m_cur_char + len + 1;
	for( ; i < (int)p->length() ;i++){
		if( ! isAlphabet(p->at(i)) )
			break;
	}
	int last = i;
	while(p->at(i) == ' ' || p->at(i) == '\t')
		i++;

	if(p->at(i++) != '=')
		return false;

	while(p->at(i) == ' ' || p->at(i) == '\t')
		i++;

	*ans = string(p->c_str()+m_cur_char+len+1,last-m_cur_char-len-1);
	m_cur_char = i;
	checkEol(p);
	return true;
}

void Feeder::checkEol(string *p)
{
	if(m_cur_char < (int)p->length())
		return;

	m_cur_char = 0;
	m_cur_line++;
}

bool Feeder::isAlphabet(char c)
{
	if(c >= 'a' && c <= 'z')
		return true;
	if(c >= 'A' && c <= 'Z')
		return true;

	return false;
}

bool Feeder::isNum(char c)
{
	if(c >= '0' && c <= '9')
		return true;

	return false;
}

void Feeder::debugOut(void)
{
	cerr << m_cur_line << " " << m_cur_char << endl;
}

void Feeder::getPos(int *ln,int *ch)
{
	*ln = m_cur_line;
	*ch = m_cur_char;
}

void Feeder::setPos(int ln,int ch)
{
	m_cur_line = ln;
	m_cur_char = ch;
}

void Feeder::printErrorPart(int from, int from_char, int to, int to_char)
{
	for(int i=from;i<to;i++){
		string left = "\tline" + to_string(i+1) + ": ";
		cerr << left <<  m_lines[i] << endl;
		if(i == from){
			cerr << "\t";
			for(int j=1-left.size();j<from_char;j++)
				cerr << " ";
			cerr << "^";
		}
	}
	if(to_char != 0)
		cerr << "\tline" << to+1 << ": " <<  m_lines[to] << endl;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/environment.h"
#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "net/test/python_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(PythonUtils, Append) {
  const FilePath::CharType kAppendDir1[] =
      FILE_PATH_LITERAL("test/path_append1");
  const FilePath::CharType kAppendDir2[] =
      FILE_PATH_LITERAL("test/path_append2");

  scoped_ptr<base::Environment> env(base::Environment::Create());

  std::string python_path;
  FilePath append_path1(kAppendDir1);
  FilePath append_path2(kAppendDir2);

  // Get a clean start
  env->UnSetVar(kPythonPathEnv);

  // Append the path
  AppendToPythonPath(append_path1);
  env->GetVar(kPythonPathEnv, &python_path);
  ASSERT_EQ(python_path, "test/path_append1");

  // Append the safe path again, nothing changes
  AppendToPythonPath(append_path2);
  env->GetVar(kPythonPathEnv, &python_path);
#if defined(OS_WIN)
  ASSERT_EQ(std::string("test/path_append1;test/path_append2"), python_path);
#elif defined(OS_POSIX)
  ASSERT_EQ(std::string("test/path_append1:test/path_append2"), python_path);
#endif
}

TEST(PythonUtils, PythonRunTime) {
  FilePath dir;
  EXPECT_TRUE(GetPythonRunTime(&dir));
#if defined(OS_WIN)
  EXPECT_NE(std::wstring::npos,
            dir.value().find(L"\\third_party\\python_24\\python.exe"));
#elif defined(OS_POSIX)
  EXPECT_NE(std::string::npos, dir.value().find("python"));
#endif
}

<commit_msg>Use python run time to launch python and make sure it works. TEST=this BUG=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_path.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "net/test/python_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(PythonUtils, Append) {
  const FilePath::CharType kAppendDir1[] =
      FILE_PATH_LITERAL("test/path_append1");
  const FilePath::CharType kAppendDir2[] =
      FILE_PATH_LITERAL("test/path_append2");

  scoped_ptr<base::Environment> env(base::Environment::Create());

  std::string python_path;
  FilePath append_path1(kAppendDir1);
  FilePath append_path2(kAppendDir2);

  // Get a clean start
  env->UnSetVar(kPythonPathEnv);

  // Append the path
  AppendToPythonPath(append_path1);
  env->GetVar(kPythonPathEnv, &python_path);
  ASSERT_EQ(python_path, "test/path_append1");

  // Append the safe path again, nothing changes
  AppendToPythonPath(append_path2);
  env->GetVar(kPythonPathEnv, &python_path);
#if defined(OS_WIN)
  ASSERT_EQ(std::string("test/path_append1;test/path_append2"), python_path);
#elif defined(OS_POSIX)
  ASSERT_EQ(std::string("test/path_append1:test/path_append2"), python_path);
#endif
}

TEST(PythonUtils, PythonRunTime) {
  FilePath dir;
  EXPECT_TRUE(GetPythonRunTime(&dir));

  // Run a python command to print a string and make sure the output is what
  // we want.
  CommandLine cmd_line(dir);
  cmd_line.AppendArg("-c");
  std::string input("PythonUtilsTest");
  std::string python_cmd = StringPrintf("print '%s';", input.c_str());
  cmd_line.AppendArg(python_cmd);
  std::string output;
  EXPECT_TRUE(base::GetAppOutput(cmd_line, &output));
  TrimWhitespace(output, TRIM_TRAILING, &output);
  EXPECT_EQ(input, output);
}
<|endoftext|>


<commit_before>#include <Flash.h>

bool FlashClass::erasePage(void* adr) {
    NVMADDR = KVA_TO_PA((unsigned int) adr);
    return doNvmOp(nvmopErasePage);
}

bool FlashClass::writeWord(void* adr, uint32_t val) {
    NVMADDR = KVA_TO_PA((unsigned int) adr);
#if defined(__PIC32MZ__)
    NVMDATA0 = val;
#else
    NVMDATA = val;
#endif
    return doNvmOp(nvmopWriteWord);
}

bool FlashClass::writeRow(void* adr, void *val) {
	bool blank = true;
	for (int i = 0; i < ROW_SIZE; i++) {
		if (((char *)val)[i] != 0xFF) {
			blank = false;
		}
	}
	if (blank) {
		return 0;
	}
    NVMADDR = KVA_TO_PA((unsigned int) adr);
    NVMSRCADDR = KVA_TO_PA((uint32_t)val);
    return doNvmOp(nvmopWriteRow);
}

bool FlashClass::clearNvmError() {
	return doNvmOp(nvmopNop);
}

bool FlashClass::isNvmError() {
	return (NVMCON & (_NVMCON_WRERR_MASK | _NVMCON_LVDERR_MASK)) ? true : false;
}

bool __attribute__((nomips16)) FlashClass::doNvmOp(uint32_t nvmop) {
    int         intSt;
    uint32_t    tm;

    // M00TODO: When DMA operations are supported in the core, need
    // to add code here to suspend DMA during the NVM operation.

    intSt = disableInterrupts();
    NVMCON = _NVMCON_WREN_MASK | nvmop;

    tm = _CP0_GET_COUNT();
    while (_CP0_GET_COUNT() - tm < ((F_CPU * 6) / 2000000));

    NVMKEY      = 0xAA996655;
    NVMKEY      = 0x556699AA;
    NVMCONSET   = _NVMCON_WR_MASK;

    while (NVMCON & _NVMCON_WR_MASK) {
		continue;
    }

    NVMCONCLR = _NVMCON_WREN_MASK;

    //M00TODO: Resume a suspended DMA operation

    restoreInterrupts(intSt);
    return(isNvmError());
}

bool FlashClass::loadPage(void *adr) {
    uint32_t *ptr = (uint32_t *)adr;

    ptr = (uint32_t *)((uint32_t)ptr & ~((PAGE_SIZE*4)-1));
    _page_address = (uint32_t)ptr;

    for (int i = 0; i < PAGE_SIZE; i++) {
        _flash_buffer[i] = *ptr;
        ptr++;
    }
    return true;
}

bool FlashClass::savePage() {
    uint32_t *ptr = (uint32_t *)_page_address;
    erasePage(ptr);
    for (int i = 0; i < PAGE_SIZE; i++) {
        writeWord(ptr, _flash_buffer[i]);
        ptr++;
    }
    return true;
}

bool FlashClass::writePageWord(void *adr, uint32_t val) {
    uint32_t a = (uint32_t)adr - _page_address;
    if (a > PAGE_SIZE * 4) {
        return false;
    }
    _flash_buffer[a/4] = val;
    return true;
}

bool FlashClass::verifyPage() {
    uint32_t *ptr = (uint32_t *)_page_address;
    for (int i = 0; i < PAGE_SIZE; i++) {
        if (*ptr != _flash_buffer[i]) {
            return false;
        }
        ptr++;
    }
    return true;
}

bool FlashClass::eraseProgmem() {
    return doNvmOp(nvmopEraseProgmem);
}

FlashClass Flash;
<commit_msg>Fixed range warning<commit_after>#include <Flash.h>

bool FlashClass::erasePage(void* adr) {
    NVMADDR = KVA_TO_PA((unsigned int) adr);
    return doNvmOp(nvmopErasePage);
}

bool FlashClass::writeWord(void* adr, uint32_t val) {
    NVMADDR = KVA_TO_PA((unsigned int) adr);
#if defined(__PIC32MZ__)
    NVMDATA0 = val;
#else
    NVMDATA = val;
#endif
    return doNvmOp(nvmopWriteWord);
}

bool FlashClass::writeRow(void* adr, void *val) {
	bool blank = true;
	for (int i = 0; i < ROW_SIZE; i++) {
		if (((uint8_t *)val)[i] != 0xFF) {
			blank = false;
		}
	}
	if (blank) {
		return 0;
	}
    NVMADDR = KVA_TO_PA((unsigned int) adr);
    NVMSRCADDR = KVA_TO_PA((uint32_t)val);
    return doNvmOp(nvmopWriteRow);
}

bool FlashClass::clearNvmError() {
	return doNvmOp(nvmopNop);
}

bool FlashClass::isNvmError() {
	return (NVMCON & (_NVMCON_WRERR_MASK | _NVMCON_LVDERR_MASK)) ? true : false;
}

bool __attribute__((nomips16)) FlashClass::doNvmOp(uint32_t nvmop) {
    int         intSt;
    uint32_t    tm;

    // M00TODO: When DMA operations are supported in the core, need
    // to add code here to suspend DMA during the NVM operation.

    intSt = disableInterrupts();
    NVMCON = _NVMCON_WREN_MASK | nvmop;

    tm = _CP0_GET_COUNT();
    while (_CP0_GET_COUNT() - tm < ((F_CPU * 6) / 2000000));

    NVMKEY      = 0xAA996655;
    NVMKEY      = 0x556699AA;
    NVMCONSET   = _NVMCON_WR_MASK;

    while (NVMCON & _NVMCON_WR_MASK) {
		continue;
    }

    NVMCONCLR = _NVMCON_WREN_MASK;

    //M00TODO: Resume a suspended DMA operation

    restoreInterrupts(intSt);
    return(isNvmError());
}

bool FlashClass::loadPage(void *adr) {
    uint32_t *ptr = (uint32_t *)adr;

    ptr = (uint32_t *)((uint32_t)ptr & ~((PAGE_SIZE*4)-1));
    _page_address = (uint32_t)ptr;

    for (int i = 0; i < PAGE_SIZE; i++) {
        _flash_buffer[i] = *ptr;
        ptr++;
    }
    return true;
}

bool FlashClass::savePage() {
    uint32_t *ptr = (uint32_t *)_page_address;
    erasePage(ptr);
    for (int i = 0; i < PAGE_SIZE; i++) {
        writeWord(ptr, _flash_buffer[i]);
        ptr++;
    }
    return true;
}

bool FlashClass::writePageWord(void *adr, uint32_t val) {
    uint32_t a = (uint32_t)adr - _page_address;
    if (a > PAGE_SIZE * 4) {
        return false;
    }
    _flash_buffer[a/4] = val;
    return true;
}

bool FlashClass::verifyPage() {
    uint32_t *ptr = (uint32_t *)_page_address;
    for (int i = 0; i < PAGE_SIZE; i++) {
        if (*ptr != _flash_buffer[i]) {
            return false;
        }
        ptr++;
    }
    return true;
}

bool FlashClass::eraseProgmem() {
    return doNvmOp(nvmopEraseProgmem);
}

FlashClass Flash;
<|endoftext|>