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

#include <string>

#include "base/basictypes.h"
#include "base/clipboard.h"
#include "base/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
  class ClipboardTest : public testing::Test {
  };
}

TEST(ClipboardTest, ClearTest) {
  Clipboard clipboard;

  clipboard.Clear();
  EXPECT_EQ(false, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  EXPECT_EQ(false, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
}

TEST(ClipboardTest, TextTest) {
  Clipboard clipboard;

  std::wstring text(L"This is a wstring!#$"), text_result;
  std::string ascii_text;

  clipboard.Clear();
  clipboard.WriteText(text);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  clipboard.ReadText(&text_result);
  EXPECT_EQ(text, text_result);
  clipboard.ReadAsciiText(&ascii_text);
  EXPECT_EQ(WideToUTF8(text), ascii_text);
}

TEST(ClipboardTest, HTMLTest) {
  Clipboard clipboard;

  std::wstring markup(L"Hi!</string>"), markup_result;
  std::string url("http://www.example.com/"), url_result;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);
#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
}

TEST(ClipboardTest, TrickyHTMLTest) {
  Clipboard clipboard;

  std::wstring markup(L"Bye!"), markup_result;
  std::string url, url_result;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);

#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
}

TEST(ClipboardTest, BookmarkTest) {
  Clipboard clipboard;

  std::wstring title(L"The Example Company"), title_result;
  std::string url("http://www.example.com/"), url_result;

  clipboard.Clear();
  clipboard.WriteBookmark(title, url);
  EXPECT_EQ(true,
      clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType()));
  clipboard.ReadBookmark(&title_result, &url_result);
  EXPECT_EQ(title, title_result);
  EXPECT_EQ(url, url_result);
}

TEST(ClipboardTest, MultiFormatTest) {
  Clipboard clipboard;

  std::wstring text(L"Hi!"), text_result;
  std::wstring markup(L"Hi!</string>"), markup_result;
  std::string url("http://www.example.com/"), url_result;
  std::string ascii_text;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  clipboard.WriteText(text);
  EXPECT_EQ(true,
      clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);
#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
  clipboard.ReadText(&text_result);
  EXPECT_EQ(text, text_result);
  clipboard.ReadAsciiText(&ascii_text);
  EXPECT_EQ(WideToUTF8(text), ascii_text);
}

// Files for this test don't actually need to exist on the file system, just
// don't try to use a non-existent file you've retrieved from the clipboard.
TEST(ClipboardTest, FileTest) {
  Clipboard clipboard;
  clipboard.Clear();
#if defined(OS_WIN)
  std::wstring file = L"C:\\Downloads\\My Downloads\\A Special File.txt";
#else
  // OS X will print a warning message if we stick a non-existant file on the
  // clipboard.
  std::wstring file = L"/usr/bin/make";
#endif
  clipboard.WriteFile(file);
  std::wstring out_file;
  clipboard.ReadFile(&out_file);
  EXPECT_EQ(file, out_file);
}

TEST(ClipboardTest, MultipleFilesTest) {
  Clipboard clipboard;
  clipboard.Clear();

#if defined(OS_WIN)
  std::wstring file1 = L"C:\\Downloads\\My Downloads\\File 1.exe";
  std::wstring file2 = L"C:\\Downloads\\My Downloads\\File 2.pdf";
  std::wstring file3 = L"C:\\Downloads\\My Downloads\\File 3.doc";
#elif defined(OS_MACOSX)
  // OS X will print a warning message if we stick a non-existant file on the
  // clipboard.
  std::wstring file1 = L"/usr/bin/make";
  std::wstring file2 = L"/usr/bin/man";
  std::wstring file3 = L"/usr/bin/perl";
#endif
  std::vector<std::wstring> files;
  files.push_back(file1);
  files.push_back(file2);
  files.push_back(file3);
  clipboard.WriteFiles(files);

  std::vector<std::wstring> out_files;
  clipboard.ReadFiles(&out_files);

  EXPECT_EQ(files.size(), out_files.size());
  for (size_t i = 0; i < out_files.size(); ++i)
    EXPECT_EQ(files[i], out_files[i]);
}

#if defined(OS_WIN)  // Windows only tests.
TEST(ClipboardTest, HyperlinkTest) {
  Clipboard clipboard;

  std::wstring title(L"The Example Company"), title_result;
  std::string url("http://www.example.com/"), url_result;
  std::wstring html(L""
                    L"The Example Company"), html_result;

  clipboard.Clear();
  clipboard.WriteHyperlink(title, url);
  EXPECT_EQ(true,
            clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType()));
  EXPECT_EQ(true,
            clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType()));
  clipboard.ReadBookmark(&title_result, &url_result);
  EXPECT_EQ(title, title_result);
  EXPECT_EQ(url, url_result);
  clipboard.ReadHTML(&html_result, &url_result);
  EXPECT_EQ(html, html_result);
  //XXX EXPECT_FALSE(url_result.is_valid());
}

TEST(ClipboardTest, WebSmartPasteTest) {
  Clipboard clipboard;

  clipboard.Clear();
  clipboard.WriteWebSmartPaste();
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetWebKitSmartPasteFormatType()));
}

TEST(ClipboardTest, BitmapTest) {
  unsigned int fake_bitmap[] = {
    0x46155189, 0xF6A55C8D, 0x79845674, 0xFA57BD89,
    0x78FD46AE, 0x87C64F5A, 0x36EDC5AF, 0x4378F568,
    0x91E9F63A, 0xC31EA14F, 0x69AB32DF, 0x643A3FD1,
  };

  Clipboard clipboard;

  clipboard.Clear();
  clipboard.WriteBitmap(fake_bitmap, gfx::Size(3, 4));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
                      Clipboard::GetBitmapFormatType()));
}
#endif
<commit_msg>Make ClipboardTest a PlatformTest to get autorelease pool management, needed on the Mac Review URL: http://codereview.chromium.org/6455<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "base/basictypes.h"
#include "base/clipboard.h"
#include "base/platform_test.h"
#include "base/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"

typedef PlatformTest ClipboardTest;

TEST_F(ClipboardTest, ClearTest) {
  Clipboard clipboard;

  clipboard.Clear();
  EXPECT_EQ(false, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  EXPECT_EQ(false, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
}

TEST_F(ClipboardTest, TextTest) {
  Clipboard clipboard;

  std::wstring text(L"This is a wstring!#$"), text_result;
  std::string ascii_text;

  clipboard.Clear();
  clipboard.WriteText(text);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  clipboard.ReadText(&text_result);
  EXPECT_EQ(text, text_result);
  clipboard.ReadAsciiText(&ascii_text);
  EXPECT_EQ(WideToUTF8(text), ascii_text);
}

TEST_F(ClipboardTest, HTMLTest) {
  Clipboard clipboard;

  std::wstring markup(L"Hi!</string>"), markup_result;
  std::string url("http://www.example.com/"), url_result;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);
#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
}

TEST_F(ClipboardTest, TrickyHTMLTest) {
  Clipboard clipboard;

  std::wstring markup(L"Bye!"), markup_result;
  std::string url, url_result;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetHtmlFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);

#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
}

TEST_F(ClipboardTest, BookmarkTest) {
  Clipboard clipboard;

  std::wstring title(L"The Example Company"), title_result;
  std::string url("http://www.example.com/"), url_result;

  clipboard.Clear();
  clipboard.WriteBookmark(title, url);
  EXPECT_EQ(true,
      clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType()));
  clipboard.ReadBookmark(&title_result, &url_result);
  EXPECT_EQ(title, title_result);
  EXPECT_EQ(url, url_result);
}

TEST_F(ClipboardTest, MultiFormatTest) {
  Clipboard clipboard;

  std::wstring text(L"Hi!"), text_result;
  std::wstring markup(L"Hi!</string>"), markup_result;
  std::string url("http://www.example.com/"), url_result;
  std::string ascii_text;

  clipboard.Clear();
  clipboard.WriteHTML(markup, url);
  clipboard.WriteText(text);
  EXPECT_EQ(true,
      clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType()));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetPlainTextFormatType()));
  clipboard.ReadHTML(&markup_result, &url_result);
  EXPECT_EQ(markup, markup_result);
#if defined(OS_MACOSX)
  // TODO(playmobil): It's not clear that the OS X clipboard needs to support
  // this.
#else
  EXPECT_EQ(url, url_result);
#endif
  clipboard.ReadText(&text_result);
  EXPECT_EQ(text, text_result);
  clipboard.ReadAsciiText(&ascii_text);
  EXPECT_EQ(WideToUTF8(text), ascii_text);
}

// Files for this test don't actually need to exist on the file system, just
// don't try to use a non-existent file you've retrieved from the clipboard.
TEST_F(ClipboardTest, FileTest) {
  Clipboard clipboard;
  clipboard.Clear();
#if defined(OS_WIN)
  std::wstring file = L"C:\\Downloads\\My Downloads\\A Special File.txt";
#else
  // OS X will print a warning message if we stick a non-existant file on the
  // clipboard.
  std::wstring file = L"/usr/bin/make";
#endif
  clipboard.WriteFile(file);
  std::wstring out_file;
  clipboard.ReadFile(&out_file);
  EXPECT_EQ(file, out_file);
}

TEST_F(ClipboardTest, MultipleFilesTest) {
  Clipboard clipboard;
  clipboard.Clear();

#if defined(OS_WIN)
  std::wstring file1 = L"C:\\Downloads\\My Downloads\\File 1.exe";
  std::wstring file2 = L"C:\\Downloads\\My Downloads\\File 2.pdf";
  std::wstring file3 = L"C:\\Downloads\\My Downloads\\File 3.doc";
#elif defined(OS_MACOSX)
  // OS X will print a warning message if we stick a non-existant file on the
  // clipboard.
  std::wstring file1 = L"/usr/bin/make";
  std::wstring file2 = L"/usr/bin/man";
  std::wstring file3 = L"/usr/bin/perl";
#endif
  std::vector<std::wstring> files;
  files.push_back(file1);
  files.push_back(file2);
  files.push_back(file3);
  clipboard.WriteFiles(files);

  std::vector<std::wstring> out_files;
  clipboard.ReadFiles(&out_files);

  EXPECT_EQ(files.size(), out_files.size());
  for (size_t i = 0; i < out_files.size(); ++i)
    EXPECT_EQ(files[i], out_files[i]);
}

#if defined(OS_WIN)  // Windows only tests.
TEST_F(ClipboardTest, HyperlinkTest) {
  Clipboard clipboard;

  std::wstring title(L"The Example Company"), title_result;
  std::string url("http://www.example.com/"), url_result;
  std::wstring html(L""
                    L"The Example Company"), html_result;

  clipboard.Clear();
  clipboard.WriteHyperlink(title, url);
  EXPECT_EQ(true,
            clipboard.IsFormatAvailable(Clipboard::GetUrlWFormatType()));
  EXPECT_EQ(true,
            clipboard.IsFormatAvailable(Clipboard::GetHtmlFormatType()));
  clipboard.ReadBookmark(&title_result, &url_result);
  EXPECT_EQ(title, title_result);
  EXPECT_EQ(url, url_result);
  clipboard.ReadHTML(&html_result, &url_result);
  EXPECT_EQ(html, html_result);
  //XXX EXPECT_FALSE(url_result.is_valid());
}

TEST_F(ClipboardTest, WebSmartPasteTest) {
  Clipboard clipboard;

  clipboard.Clear();
  clipboard.WriteWebSmartPaste();
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
      Clipboard::GetWebKitSmartPasteFormatType()));
}

TEST_F(ClipboardTest, BitmapTest) {
  unsigned int fake_bitmap[] = {
    0x46155189, 0xF6A55C8D, 0x79845674, 0xFA57BD89,
    0x78FD46AE, 0x87C64F5A, 0x36EDC5AF, 0x4378F568,
    0x91E9F63A, 0xC31EA14F, 0x69AB32DF, 0x643A3FD1,
  };

  Clipboard clipboard;

  clipboard.Clear();
  clipboard.WriteBitmap(fake_bitmap, gfx::Size(3, 4));
  EXPECT_EQ(true, clipboard.IsFormatAvailable(
                      Clipboard::GetBitmapFormatType()));
}
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/roudi/memory/roudi_memory_manager.hpp"

#include "mocks/roudi_memory_block_mock.hpp"
#include "mocks/roudi_memory_provider_mock.hpp"

#include "test.hpp"

using namespace ::testing;

using namespace iox::roudi;
/// @todo the RouDiMemoryManager changed quite much from the initial idea, check which tests makes sense
#if 0
class RouDiMemoryManager_Test : public Test
{
  public:
    void SetUp() override
    {
    }

    void TearDown() override
    {
    }

    MemoryBlockMock memoryBlock1;
    MemoryBlockMock memoryBlock2;
    MemoryProviderTestImpl memoryProvider1;
    MemoryProviderTestImpl memoryProvider2;

    RouDiMemoryManager sut;
};

TEST_F(RouDiMemoryManager_Test, CallingCreateAndAnnounceMemoryWithoutMemoryProviderFails)
{
    auto expectError = sut.createAndAnnounceMemory();
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT));
}

TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderSucceeds)
{
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    uint64_t MEMORY_SIZE_2{32};
    uint64_t MEMORY_ALIGNMENT_2{16};
    EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
    EXPECT_CALL(memoryBlock2, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_2));
    EXPECT_CALL(memoryBlock2, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_2));
    EXPECT_CALL(memoryBlock2, memoryAvailableMock(_));

    memoryProvider1.addMemoryBlock(&memoryBlock1);
    memoryProvider2.addMemoryBlock(&memoryBlock2);

    sut.addMemoryProvider(&memoryProvider1);
    sut.addMemoryProvider(&memoryProvider2);

    EXPECT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(false));

    EXPECT_CALL(memoryBlock1, destroyMock());
    EXPECT_CALL(memoryBlock2, destroyMock());
}

TEST_F(RouDiMemoryManager_Test, RouDiMemoryManagerDTorTriggersMemoryProviderDestroy)
{
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));

    memoryProvider1.addMemoryBlock(&memoryBlock1);

    {
        RouDiMemoryManager sutDestroy;
        sutDestroy.addMemoryProvider(&memoryProvider1);
        sutDestroy.createAndAnnounceMemory();
        EXPECT_CALL(memoryBlock1, destroyMock()).Times(1);
    }
    EXPECT_CALL(memoryBlock1, destroyMock()).Times(0);
}

TEST_F(RouDiMemoryManager_Test, AddMemoryProviderExceedsCapacity)
{
    MemoryProviderTestImpl memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER + 1];
    RouDiMemoryManager sutExhausting;

    for (uint32_t i = 0; i < iox::MAX_NUMBER_OF_MEMORY_PROVIDER; ++i)
    {
        EXPECT_THAT(sutExhausting.addMemoryProvider(&memoryProvider[i]).has_error(), Eq(false));
    }

    auto expectError = sutExhausting.addMemoryProvider(&memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER]);
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED));
}
#endif
<commit_msg>iox-#91 Add todo for new RouDiMemoryManager test case<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/roudi/memory/roudi_memory_manager.hpp"

#include "mocks/roudi_memory_block_mock.hpp"
#include "mocks/roudi_memory_provider_mock.hpp"

#include "test.hpp"

using namespace ::testing;

using namespace iox::roudi;
/// @todo the RouDiMemoryManager changed quite much from the initial idea, check which tests makes sense
#if 0
class RouDiMemoryManager_Test : public Test
{
  public:
    void SetUp() override
    {
    }

    void TearDown() override
    {
    }

    MemoryBlockMock memoryBlock1;
    MemoryBlockMock memoryBlock2;
    MemoryProviderTestImpl memoryProvider1;
    MemoryProviderTestImpl memoryProvider2;

    RouDiMemoryManager sut;
};

TEST_F(RouDiMemoryManager_Test, CallingCreateAndAnnounceMemoryWithoutMemoryProviderFails)
{
    auto expectError = sut.createAndAnnounceMemory();
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT));
}

TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderSucceeds)
{
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    uint64_t MEMORY_SIZE_2{32};
    uint64_t MEMORY_ALIGNMENT_2{16};
    EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
    EXPECT_CALL(memoryBlock2, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_2));
    EXPECT_CALL(memoryBlock2, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_2));
    EXPECT_CALL(memoryBlock2, memoryAvailableMock(_));

    memoryProvider1.addMemoryBlock(&memoryBlock1);
    memoryProvider2.addMemoryBlock(&memoryBlock2);

    sut.addMemoryProvider(&memoryProvider1);
    sut.addMemoryProvider(&memoryProvider2);

    EXPECT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(false));

    EXPECT_CALL(memoryBlock1, destroyMock());
    EXPECT_CALL(memoryBlock2, destroyMock());
}

TEST_F(RouDiMemoryManager_Test, RouDiMemoryManagerDTorTriggersMemoryProviderDestroy)
{
    uint64_t MEMORY_SIZE_1{16};
    uint64_t MEMORY_ALIGNMENT_1{8};
    EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
    EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
    EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));

    memoryProvider1.addMemoryBlock(&memoryBlock1);

    {
        RouDiMemoryManager sutDestroy;
        sutDestroy.addMemoryProvider(&memoryProvider1);
        sutDestroy.createAndAnnounceMemory();
        EXPECT_CALL(memoryBlock1, destroyMock()).Times(1);
    }
    EXPECT_CALL(memoryBlock1, destroyMock()).Times(0);
}

TEST_F(RouDiMemoryManager_Test, AddMemoryProviderExceedsCapacity)
{
    MemoryProviderTestImpl memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER + 1];
    RouDiMemoryManager sutExhausting;

    for (uint32_t i = 0; i < iox::MAX_NUMBER_OF_MEMORY_PROVIDER; ++i)
    {
        EXPECT_THAT(sutExhausting.addMemoryProvider(&memoryProvider[i]).has_error(), Eq(false));
    }

    auto expectError = sutExhausting.addMemoryProvider(&memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER]);
    ASSERT_THAT(expectError.has_error(), Eq(true));
    EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED));
}

TEST_F(RouDiMemoryManager_Test, StreamOperatorTranslationIsCorrect)
{
    /// @todo
}
#endif
<|endoftext|>


<commit_before>#include "teensy3/WProgram.h"
#include "teensy3/core_pins.h"
#include "teensy3/usb_serial.h"

#define ROWS 15
#define COLS 112

#define CLK 11
#define DAT 12
#define HIBANK 3
#define LOBANK 4
#define BIT0 0
#define BIT1 1
#define BIT2 2

#define bufferSize 512

int serialbuffer[bufferSize];
int img1[ROWS][COLS];
int img2[ROWS][COLS];

int currentRow;
int serialEnd;

void setRow(int row) {
  if (row < 8 & row < 16) {
    digitalWriteFast(HIBANK, LOW);
    digitalWriteFast(LOBANK, HIGH);
  } else if (row < 16) {
    digitalWriteFast(HIBANK, HIGH);
    digitalWriteFast(LOBANK, LOW);
  } else {
    digitalWriteFast(HIBANK, LOW);
    digitalWriteFast(LOBANK, LOW);
  }
  digitalWriteFast(BIT0, row & 1);
  digitalWriteFast(BIT1, row & 2);
  digitalWriteFast(BIT2, row & 4);
}

void initialize() {
    pinMode(CLK, OUTPUT);
    pinMode(DAT, OUTPUT);
    pinMode(LOBANK, OUTPUT);
    pinMode(HIBANK, OUTPUT);
    pinMode(BIT0, OUTPUT);
    pinMode(BIT1, OUTPUT);
    pinMode(BIT2, OUTPUT);

    currentRow = 0;
    serialEnd = 0;
}

extern "C" int main(void) {
  initialize();
  elapsedMillis refresh = 0;
  int* img = (int*)img1;
  int *nimg = (int*)img2;

  Serial.begin(9600);

  while(1) {
    for(int col = 0; col < COLS; col++) {
      digitalWriteFast(DAT, img[currentRow*ROWS + col] ? HIGH : LOW);
      digitalWriteFast(CLK, HIGH);
      digitalWriteFast(CLK, LOW);
    }
    setRow(currentRow);
    currentRow++;
    currentRow %= 15;
    while (refresh < 10) {
      if (Serial.available()) {
        serialbuffer[serialEnd] = Serial.read();
        serialEnd++;
      }
      if (serialEnd == 2) {
        if ((serialbuffer[0] != 0xCA) | (serialbuffer[1] != 0xFE)) {
          serialEnd = 0;
        }
      }
      if (serialEnd > 2) {
        if (serialbuffer[3] == 0x00) { //Blit frame
          if (img == (int*)img1) {
            img = (int*)img2;
            nimg = (int*)img1;
          } else {
            img = (int*)img1;
            nimg = (int*)img2;
          }
          serialEnd = 0;
          currentRow = 0;
        }
        if ((serialbuffer[3] == 0x01) & (serialEnd == COLS*ROWS+3)) {
          for (int i=0; i<COLS*ROWS; i++) {
            nimg[i] = serialbuffer[i+3];
          }
        }
      }
      if (serialEnd > bufferSize) {
        serialEnd = 0;
      }
    }
    setRow(16);
    refresh -= 10;
  }
}
<commit_msg>Fixed graphics glitch<commit_after>#include "teensy3/WProgram.h"
#include "teensy3/core_pins.h"
#include "teensy3/usb_serial.h"

#define ROWS 15
#define COLS 112

#define SYNC 10
#define CLK 11
#define DAT 12
#define HIBANK 3
#define LOBANK 4
#define BIT0 0
#define BIT1 1
#define BIT2 2

#define bufferSize 2048

int serialbuffer[bufferSize];
int img1[ROWS][COLS];
int img2[ROWS][COLS];

int currentRow;
int serialEnd;

void setRow(int row) {
  digitalWrite(LOBANK, HIGH);
  digitalWrite(HIBANK, HIGH);
  digitalWrite(BIT0, row & 1);
  digitalWrite(BIT1, row & 2);
  digitalWrite(BIT2, row & 4);
  if ((row < 8) & (row < 16) & (row >= 0)) {
    digitalWrite(HIBANK, LOW);
  } else if ((row >= 8) & (row < 16)) {
    digitalWrite(LOBANK, LOW);
  }
}

void initialize() {
    pinMode(CLK, OUTPUT);
    pinMode(DAT, OUTPUT);
    pinMode(LOBANK, OUTPUT);
    pinMode(HIBANK, OUTPUT);
    pinMode(BIT0, OUTPUT);
    pinMode(BIT1, OUTPUT);
    pinMode(BIT2, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(SYNC, OUTPUT);

    currentRow = 0;
    serialEnd = 0;
}

extern "C" int main(void) {
  initialize();
  elapsedMillis refresh = 0;
  elapsedMillis blink = 0;
  int* img = (int*)img1;
  int *nimg = (int*)img2;

  int ledState = 0;

  Serial.begin(9600);

  while(1) {
    setRow(16);
    digitalWrite(SYNC, currentRow);
    for(int col = 0; col < COLS; col++) {
      digitalWrite(DAT, img[currentRow*COLS + col] ? HIGH : LOW);
      digitalWrite(CLK, HIGH);
      digitalWrite(CLK, LOW);
    }
    setRow(ROWS - currentRow - 1);
    currentRow++;
    currentRow %= 16;
    for (int i=0; i<112; i++) {
      if (Serial.available()) {
        serialbuffer[serialEnd] = Serial.read();
        serialEnd++;
      }
      if (serialEnd == 1) {
        if (serialbuffer[0] != 0xCA) {
          serialEnd = 0;
        }
      }
      if (serialEnd == 2) {
        if (serialbuffer[1] != 0xFE) {
          serialEnd = 0;
        }
      }
      if (serialEnd > 2) {
        if (serialbuffer[2] == 0x00) { //Blit frame
          if (img == (int*)img1) {
            img = (int*)img2;
            nimg = (int*)img1;
          } else {
            img = (int*)img1;
            nimg = (int*)img2;
          }
          serialEnd = 0;
        }
        if ((serialbuffer[2] == 0x01) & (serialEnd == COLS*ROWS+3)) {
          for (int i=0; i<COLS*ROWS; i++) {
            nimg[i] = serialbuffer[i+3];
          }
          serialEnd = 0;
        }
      }
      if (serialEnd > bufferSize) {
        serialEnd = 0;
      }
    }
    if (blink > 500) {
      digitalWrite(13, ledState);
      ledState = !ledState;
      blink -= 500;
    }
    refresh = 0;
  }
}
<|endoftext|>


<commit_before>#include "parser.h"

#include "ast.h"
#include "token.h"

#include "exceptions.h"

#include <string>
#include <vector>

namespace sota {

    std::string Parser::Load(const std::string &filename) {
        return "";
    }

    Token Parser::Take(Token token) {
        if (token)
            _tokens.push_back(token);
        return token;
    }

    Token Parser::Emit() {
        Token token = Token(nullptr, Source, Index, 0);
        if (_tokens.size()) {
            token = _tokens.front();
            _tokens.pop_front();
        }
        return token;
    }

    Token Parser::Scan() {

        Symbol *match = nullptr;
        if (Index < Source.length()) {
            auto end = Index;
            std::vector<Symbol *> symbols;
            for (auto symbol : symbols) {
                auto index = symbol->Scan(Source, Index);
                if (index > end || (match != nullptr && symbol->LBP > match->LBP && index == end)) {
                    match = symbol;
                    end = index;
                }
            }
            if (Index == end)
                throw SotaException("Parser::Scan: invalid symbol");
        }
        return Token();
    }

    Token Parser::LookAhead(int distance) {
        auto token = Token();
        while (distance--) {
            if (token = Emit())
                continue;
            token = Scan();
        }
        return token;
    }

    /*public*/

    Parser::Parser(const Types2Symbols &symbols)
        : Symbols(symbols) {}

    Ast * Parser::ParseFile(const std::string &filename) {
        auto source = Load(filename);
        return Parse(source);
    }

    Ast * Parser::Parse(const std::string &source) {
        Source = source;
        return Parse();
    }

    Ast * Parser::Parse(size_t lbp/* = 0 */) {

        Token token = Consume();

        Ast *left = token.Nud(this, &token);

        while (lbp < token.LBP()) {
            Token token = Consume();
            token.Led(this, left, &token);
        }

        return left;
    }

    Token Parser::Consume() {
        auto symbol = new Symbol(SymbolType::Add, "+", nullptr, nullptr, nullptr, 0);
        return Token(symbol, Source, 0, 0);
    }

    Token Parser::Consume(const size_t &expected, const std::string &message) {
        auto token = Consume();
        if (token.Type() != expected)
            throw SotaException(message);
        return token;
    }

    size_t Parser::Line() {
        return 0;
    }

    size_t Parser::Column() {
        return 0;
    }
}
<commit_msg>added reference to Symbols ... -sai<commit_after>#include "parser.h"

#include "ast.h"
#include "token.h"

#include "exceptions.h"

#include <string>
#include <vector>

namespace sota {

    std::string Parser::Load(const std::string &filename) {
        return "";
    }

    Token Parser::Take(Token token) {
        if (token)
            _tokens.push_back(token);
        return token;
    }

    Token Parser::Emit() {
        Token token = Token(nullptr, Source, Index, 0);
        if (_tokens.size()) {
            token = _tokens.front();
            _tokens.pop_front();
        }
        return token;
    }

    Token Parser::Scan() {

        Symbol *match = nullptr;
        if (Index < Source.length()) {
            auto end = Index;
            for (auto kvp : Symbols) {
                auto symbol = kvp.second;
                auto index = symbol->Scan(Source, Index);
                if (index > end || (match != nullptr && symbol->LBP > match->LBP && index == end)) {
                    match = symbol;
                    end = index;
                }
            }
            if (Index == end)
                throw SotaException("Parser::Scan: invalid symbol");
        }
        return Token();
    }

    Token Parser::LookAhead(int distance) {
        auto token = Token();
        while (distance--) {
            if (token = Emit())
                continue;
            token = Scan();
        }
        return token;
    }

    /*public*/

    Parser::Parser(const Types2Symbols &symbols)
        : Symbols(symbols) {}

    Ast * Parser::ParseFile(const std::string &filename) {
        auto source = Load(filename);
        return Parse(source);
    }

    Ast * Parser::Parse(const std::string &source) {
        Source = source;
        return Parse();
    }

    Ast * Parser::Parse(size_t lbp/* = 0 */) {

        Token token = Consume();

        Ast *left = token.Nud(this, &token);

        while (lbp < token.LBP()) {
            Token token = Consume();
            token.Led(this, left, &token);
        }

        return left;
    }

    Token Parser::Consume() {
        auto symbol = new Symbol(SymbolType::Add, "+", nullptr, nullptr, nullptr, 0);
        return Token(symbol, Source, 0, 0);
    }

    Token Parser::Consume(const size_t &expected, const std::string &message) {
        auto token = Consume();
        if (token.Type() != expected)
            throw SotaException(message);
        return token;
    }

    size_t Parser::Line() {
        return 0;
    }

    size_t Parser::Column() {
        return 0;
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 BMW Group
// Author: Lutz Bichler (lutz.bichler@bmw.de)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <iomanip>
#include <sstream>

#include <boost/asio/write.hpp>

#include <vsomeip/defines.hpp>
#include <vsomeip/logger.hpp>

#include "../include/endpoint_host.hpp"
#include "../include/local_client_endpoint_impl.hpp"

namespace vsomeip {

local_client_endpoint_impl::local_client_endpoint_impl(
		std::shared_ptr< endpoint_host > _host, endpoint_type _remote, boost::asio::io_service &_io)
	: local_client_endpoint_base_impl(_host, _remote, _io) {
	is_supporting_magic_cookies_ = false;
}

void local_client_endpoint_impl::start() {
	connect();
}

void local_client_endpoint_impl::connect() {
	socket_.open(remote_.protocol());

	socket_.async_connect(
		remote_,
		std::bind(
			&local_client_endpoint_base_impl::connect_cbk,
			shared_from_this(),
			std::placeholders::_1
		)
	);
}

void local_client_endpoint_impl::receive() {
	packet_buffer_ptr_t its_buffer
		= std::make_shared< packet_buffer_t >();
	socket_.async_receive(
		boost::asio::buffer(*its_buffer),
		std::bind(
			&local_client_endpoint_impl::receive_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			its_buffer,
			std::placeholders::_1,
			std::placeholders::_2
		)
	);
}

void local_client_endpoint_impl::send_queued(message_buffer_ptr_t _buffer) {
#if 0
	std::stringstream msg;
	msg << "lce<" << this << ">::sq: ";
	for (std::size_t i = 0; i < _buffer->size(); i++)
		msg << std::setw(2) << std::setfill('0') << std::hex << (int)(*_buffer)[i] << " ";
	VSOMEIP_DEBUG << msg.str();
#endif

	static byte_t its_start_tag[] = { 0x67, 0x37, 0x6D, 0x07 };
	static byte_t its_end_tag[] = { 0x07, 0x6D, 0x37, 0x67 };

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(
			its_start_tag,
			sizeof(its_start_tag)
		),
		std::bind(
			&local_client_endpoint_impl::send_tag_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			std::placeholders::_1,
			std::placeholders::_2
		)
	);

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(*_buffer),
		std::bind(
			&client_endpoint_impl::send_cbk,
			this->shared_from_this(),
			_buffer,
			std::placeholders::_1,
			std::placeholders::_2
		)
	);

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(
			its_end_tag,
			sizeof(its_end_tag)
		),
		std::bind(
			&local_client_endpoint_impl::send_tag_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			std::placeholders::_1,
			std::placeholders::_2
		)
	);
}

void local_client_endpoint_impl::send_magic_cookie() {
}

void local_client_endpoint_impl::send_tag_cbk(
		boost::system::error_code const &_error, std::size_t _bytes) {
}

void local_client_endpoint_impl::receive_cbk(
		packet_buffer_ptr_t _buffer,
		boost::system::error_code const &_error, std::size_t _bytes) {
	VSOMEIP_ERROR << "Local client endpoints must not receive messages!";
}

} // namespace vsomeip
<commit_msg>Log the reason for receiving a message on a local client endpoint.<commit_after>// Copyright (C) 2014 BMW Group
// Author: Lutz Bichler (lutz.bichler@bmw.de)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <iomanip>
#include <sstream>

#include <boost/asio/write.hpp>

#include <vsomeip/defines.hpp>
#include <vsomeip/logger.hpp>

#include "../include/endpoint_host.hpp"
#include "../include/local_client_endpoint_impl.hpp"

namespace vsomeip {

local_client_endpoint_impl::local_client_endpoint_impl(
		std::shared_ptr< endpoint_host > _host, endpoint_type _remote, boost::asio::io_service &_io)
	: local_client_endpoint_base_impl(_host, _remote, _io) {
	is_supporting_magic_cookies_ = false;
}

void local_client_endpoint_impl::start() {
	connect();
}

void local_client_endpoint_impl::connect() {
	socket_.open(remote_.protocol());

	socket_.async_connect(
		remote_,
		std::bind(
			&local_client_endpoint_base_impl::connect_cbk,
			shared_from_this(),
			std::placeholders::_1
		)
	);
}

void local_client_endpoint_impl::receive() {
	packet_buffer_ptr_t its_buffer
		= std::make_shared< packet_buffer_t >();
	socket_.async_receive(
		boost::asio::buffer(*its_buffer),
		std::bind(
			&local_client_endpoint_impl::receive_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			its_buffer,
			std::placeholders::_1,
			std::placeholders::_2
		)
	);
}

void local_client_endpoint_impl::send_queued(message_buffer_ptr_t _buffer) {
#if 0
	std::stringstream msg;
	msg << "lce<" << this << ">::sq: ";
	for (std::size_t i = 0; i < _buffer->size(); i++)
		msg << std::setw(2) << std::setfill('0') << std::hex << (int)(*_buffer)[i] << " ";
	VSOMEIP_DEBUG << msg.str();
#endif

	static byte_t its_start_tag[] = { 0x67, 0x37, 0x6D, 0x07 };
	static byte_t its_end_tag[] = { 0x07, 0x6D, 0x37, 0x67 };

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(
			its_start_tag,
			sizeof(its_start_tag)
		),
		std::bind(
			&local_client_endpoint_impl::send_tag_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			std::placeholders::_1,
			std::placeholders::_2
		)
	);

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(*_buffer),
		std::bind(
			&client_endpoint_impl::send_cbk,
			this->shared_from_this(),
			_buffer,
			std::placeholders::_1,
			std::placeholders::_2
		)
	);

	boost::asio::async_write(
		socket_,
		boost::asio::buffer(
			its_end_tag,
			sizeof(its_end_tag)
		),
		std::bind(
			&local_client_endpoint_impl::send_tag_cbk,
			std::dynamic_pointer_cast< local_client_endpoint_impl >(shared_from_this()),
			std::placeholders::_1,
			std::placeholders::_2
		)
	);
}

void local_client_endpoint_impl::send_magic_cookie() {
}

void local_client_endpoint_impl::send_tag_cbk(
		boost::system::error_code const &_error, std::size_t _bytes) {
}

void local_client_endpoint_impl::receive_cbk(
		packet_buffer_ptr_t _buffer,
		boost::system::error_code const &_error, std::size_t _bytes) {
	VSOMEIP_ERROR << "Local endpoint received message (" << _error.message() << ")";
}

} // namespace vsomeip
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: disas.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-08-03 09:55:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DISAS_HXX
#define _DISAS_HXX

#include "image.hxx"
#include "opcodes.hxx"
// find a place for this limit ( also used in
class SvStream;
#define MAX_LABELS 0x2000L
class SbiDisas {
    const SbiImage& rImg;
    SbModule* pMod;
    char     cLabels[ MAX_LABELS ];     // Bitvektor fuer Labels
    UINT32   nOff;                  // aktuelle Position
    UINT32   nPC;                   // Position des Opcodes
    SbiOpcode eOp;                  // Opcode
    USHORT   nOp1, nOp2;            // Operanden
    short    nParts;                // 1, 2 oder 3
    short    nLine;                 // aktuelle Zeile
    BOOL     DisasLine( String& );
    BOOL     Fetch();               // naechster Opcode
public:
    SbiDisas( SbModule*, const SbiImage* );
    void Disas( SvStream& );
    void Disas( String& );
                                    // NICHT AUFRUFEN
    void     StrOp( String& );
    void     Str2Op( String& );
    void     ImmOp( String& );
    void     OnOp( String& );
    void     LblOp( String& );
    void     ReturnOp( String& );
    void     ResumeOp( String& );
    void     PromptOp( String& );
    void     CloseOp( String& );
    void     CharOp( String& );
    void     VarOp( String& );
    void     VarDefOp( String& );
    void     OffOp( String& );
    void     TypeOp( String& );
    void     CaseOp( String& );
    void     StmntOp( String& );
    void     StrmOp( String& );
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.78); FILE MERGED 2008/03/28 16:07:25 rt 1.6.78.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: disas.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DISAS_HXX
#define _DISAS_HXX

#include "image.hxx"
#include "opcodes.hxx"
// find a place for this limit ( also used in
class SvStream;
#define MAX_LABELS 0x2000L
class SbiDisas {
    const SbiImage& rImg;
    SbModule* pMod;
    char     cLabels[ MAX_LABELS ];     // Bitvektor fuer Labels
    UINT32   nOff;                  // aktuelle Position
    UINT32   nPC;                   // Position des Opcodes
    SbiOpcode eOp;                  // Opcode
    USHORT   nOp1, nOp2;            // Operanden
    short    nParts;                // 1, 2 oder 3
    short    nLine;                 // aktuelle Zeile
    BOOL     DisasLine( String& );
    BOOL     Fetch();               // naechster Opcode
public:
    SbiDisas( SbModule*, const SbiImage* );
    void Disas( SvStream& );
    void Disas( String& );
                                    // NICHT AUFRUFEN
    void     StrOp( String& );
    void     Str2Op( String& );
    void     ImmOp( String& );
    void     OnOp( String& );
    void     LblOp( String& );
    void     ReturnOp( String& );
    void     ResumeOp( String& );
    void     PromptOp( String& );
    void     CloseOp( String& );
    void     CharOp( String& );
    void     VarOp( String& );
    void     VarDefOp( String& );
    void     OffOp( String& );
    void     TypeOp( String& );
    void     CaseOp( String& );
    void     StmntOp( String& );
    void     StrmOp( String& );
};

#endif
<|endoftext|>


<commit_before>#include "parser.hpp"

namespace Xigua
{
	DataType Parser::parse_to_data_types(std::vector<std::string> string_list, DataTypes list_type)
	{
		DataType current_list;
		current_list.type = list_type;
		unsigned int current_item_index = 0;
		for (; current_item_index < string_list.size(); ++current_item_index)
		{
			if (string_list.at(current_item_index) == "[" || string_list.at(current_item_index) == "{")
			{
				DataTypes sub_list_type = DataTypes::Proc;
				if (string_list.at(current_item_index) == "{")
					sub_list_type = DataTypes::Tuple;

				std::vector<std::string> new_list;
				int internal_lists = 1;
				while (true) {
					current_item_index++;
					if (string_list.at(current_item_index) == "[" || string_list.at(current_item_index) == "{") {
						internal_lists++;
					}
					else if (string_list.at(current_item_index) == "]" || string_list.at(current_item_index) == "}") {
						internal_lists--;
						if (internal_lists == 0) {
							break;
						}
					}
					new_list.push_back(string_list.at(current_item_index));
				}
				current_list.list.push_back(parse_to_data_types(new_list, sub_list_type));
			}
			else if (is_number(string_list.at(current_item_index)))
			{
				DataType data;
				data.type = DataTypes::Number;
				data.number = atof(string_list.at(current_item_index).c_str());
				current_list.list.push_back(data);
			}
			else if (string_list.at(current_item_index)[0] == '"')
			{
				DataType data;
				data.type = DataTypes::String;
				data.string = string_list.at(current_item_index).substr(1, string_list.at(current_item_index).size() - 2);
				current_list.list.push_back(data);
			}
			else if (string_list.at(current_item_index) == "true" || string_list.at(current_item_index) == "false")
			{
				DataType data;
				data.type = DataTypes::Bool;
				if (string_list.at(current_item_index) == "true")
					data.boolean = true;
				else
					data.boolean = false;
				current_list.list.push_back(data);

			}
			else
			{
				DataType data;
				data.type = DataTypes::Symbol;
				data.string = string_list.at(current_item_index);
				current_list.list.push_back(data);
			}
		}
		return current_list;
	}

	Parser::Parser(std::string program_string)
	{
		raw_string = program_string;
	}

	std::vector<std::string> Parser::as_string_list()
	{
		std::vector<std::string> parsed_list;

		bool is_reading_string = false;
		std::stringstream string_buffer;
		bool string_buffer_contains_data = false;
		for (char c : raw_string)
		{
			if (c == '[' || c == ']' || c == '{' || c == '}'){

				if (string_buffer_contains_data) {
					parsed_list.push_back(string_buffer.str());
					string_buffer.str("");
					string_buffer_contains_data = false;
				}

				parsed_list.push_back(std::string(1, c));

			}
			else if (c == ' ' || c == '\n' || c == '\t') {

				if (!is_reading_string) {
					if (string_buffer_contains_data) {
						parsed_list.push_back(string_buffer.str());
						string_buffer.str("");
						string_buffer_contains_data = false;
					}
				}
				else {
					string_buffer << c;
					string_buffer_contains_data = true;
				}

			}
			else if (c == '"') {
				string_buffer << '"';
				if (is_reading_string) {
					is_reading_string = false;
					parsed_list.push_back(string_buffer.str());
					string_buffer.str("");
					string_buffer_contains_data = false;
				}
				else {
					is_reading_string = true;
				}

			}
			else {

				string_buffer << c;
				string_buffer_contains_data = true;

			}
		}

		return parsed_list;
	}

	DataType Parser::as_data_type()
	{
		return parse_to_data_types(as_string_list());
	}

}
<commit_msg>strings can contain brackets now<commit_after>#include "parser.hpp"

namespace Xigua
{
	DataType Parser::parse_to_data_types(std::vector<std::string> string_list, DataTypes list_type)
	{
		DataType current_list;
		current_list.type = list_type;
		unsigned int current_item_index = 0;
		for (; current_item_index < string_list.size(); ++current_item_index)
		{
			if (string_list.at(current_item_index) == "[" || string_list.at(current_item_index) == "{")
			{
				DataTypes sub_list_type = DataTypes::Proc;
				if (string_list.at(current_item_index) == "{")
					sub_list_type = DataTypes::Tuple;

				std::vector<std::string> new_list;
				int internal_lists = 1;
				while (true) {
					current_item_index++;
					if (string_list.at(current_item_index) == "[" || string_list.at(current_item_index) == "{") {
						internal_lists++;
					}
					else if (string_list.at(current_item_index) == "]" || string_list.at(current_item_index) == "}") {
						internal_lists--;
						if (internal_lists == 0) {
							break;
						}
					}
					new_list.push_back(string_list.at(current_item_index));
				}
				current_list.list.push_back(parse_to_data_types(new_list, sub_list_type));
			}
			else if (is_number(string_list.at(current_item_index)))
			{
				DataType data;
				data.type = DataTypes::Number;
				data.number = atof(string_list.at(current_item_index).c_str());
				current_list.list.push_back(data);
			}
			else if (string_list.at(current_item_index)[0] == '"')
			{
				DataType data;
				data.type = DataTypes::String;
				data.string = string_list.at(current_item_index).substr(1, string_list.at(current_item_index).size() - 2);
				current_list.list.push_back(data);
			}
			else if (string_list.at(current_item_index) == "true" || string_list.at(current_item_index) == "false")
			{
				DataType data;
				data.type = DataTypes::Bool;
				if (string_list.at(current_item_index) == "true")
					data.boolean = true;
				else
					data.boolean = false;
				current_list.list.push_back(data);

			}
			else
			{
				DataType data;
				data.type = DataTypes::Symbol;
				data.string = string_list.at(current_item_index);
				current_list.list.push_back(data);
			}
		}
		return current_list;
	}

	Parser::Parser(std::string program_string)
	{
		raw_string = program_string;
	}

	std::vector<std::string> Parser::as_string_list()
	{
		std::vector<std::string> parsed_list;

		bool is_reading_string = false;
		std::stringstream string_buffer;
		bool string_buffer_contains_data = false;
		for (char c : raw_string)
		{
			if (c == '[' || c == ']' || c == '{' || c == '}'){

                if (!is_reading_string) {
				    if (string_buffer_contains_data) {
				    	parsed_list.push_back(string_buffer.str());
				    	string_buffer.str("");
				    	string_buffer_contains_data = false;
				    }
				    parsed_list.push_back(std::string(1, c));
                } else {
                    string_buffer << c;
					string_buffer_contains_data = true;
                }

			}
			else if (c == ' ' || c == '\n' || c == '\t') {

				if (!is_reading_string) {
					if (string_buffer_contains_data) {
						parsed_list.push_back(string_buffer.str());
						string_buffer.str("");
						string_buffer_contains_data = false;
					}
				}
				else {
					string_buffer << c;
					string_buffer_contains_data = true;
				}

			}
			else if (c == '"') {
				string_buffer << '"';
				if (is_reading_string) {
					is_reading_string = false;
					parsed_list.push_back(string_buffer.str());
					string_buffer.str("");
					string_buffer_contains_data = false;
				}
				else {
					is_reading_string = true;
				}

			}
			else {

				string_buffer << c;
				string_buffer_contains_data = true;

			}
		}

		return parsed_list;
	}

	DataType Parser::as_data_type()
	{
		return parse_to_data_types(as_string_list());
	}

}
<|endoftext|>


<commit_before>#pragma once

#include <depthai-shared/datatype/RawCameraControl.hpp>
#include <nlohmann/json.hpp>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraImageOrientation.hpp"

namespace dai {

/**
 * Specify ColorCamera options such as camera ID, ...
 */
struct ColorCameraProperties {
    static constexpr int AUTO = -1;

    /**
     * Select the camera sensor resolution
     */
    enum class SensorResolution : int32_t { THE_1080_P, THE_4_K, THE_12_MP };

    /**
     * For 24 bit color these can be either RGB or BGR
     */
    enum class ColorOrder : int32_t { BGR, RGB };

    /*
     * Initial controls applied to ColorCamera node
     */
    RawCameraControl initialControl;

    /**
     * Which socket will color camera use
     */
    CameraBoardSocket boardSocket = CameraBoardSocket::AUTO;

    /**
     * Camera sensor image orientation / pixel readout
     */
    CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO;

    /**
     * For 24 bit color these can be either RGB or BGR
     */
    ColorOrder colorOrder = ColorOrder::BGR;
    /**
     * Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2)
     */
    bool interleaved = true;
    /**
     * Are values FP16 type (0.0 - 255.0)
     */
    bool fp16 = false;

    /**
     * Preview frame output height
     */
    uint32_t previewHeight = 300;
    /**
     * Preview frame output width
     */
    uint32_t previewWidth = 300;

    /**
     * Preview frame output width
     */
    int32_t videoWidth = AUTO;

    /**
     * Preview frame output height
     */
    int32_t videoHeight = AUTO;

    /**
     * Preview frame output width
     */
    int32_t stillWidth = AUTO;

    /**
     * Preview frame output height
     */
    int32_t stillHeight = AUTO;

    /**
     * Select the camera sensor resolution
     */
    SensorResolution resolution = SensorResolution::THE_1080_P;
    /**
     * Camera sensor FPS
     */
    float fps = 30.0;

    /**
     * Initial sensor crop, -1 signifies center crop
     */
    float sensorCropX = AUTO;
    float sensorCropY = AUTO;

    /**
     * Whether to wait for config at 'inputConfig' io
     */
    bool inputConfigSync = false;

    /**
     * Whether to keep aspect ratio of input (video size) or not
     */
    bool previewKeepAspectRatio = true;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(ColorCameraProperties,
                                   initialControl,
                                   boardSocket,
                                   imageOrientation,
                                   colorOrder,
                                   interleaved,
                                   fp16,
                                   previewHeight,
                                   previewWidth,
                                   videoWidth,
                                   videoHeight,
                                   stillWidth,
                                   stillHeight,
                                   resolution,
                                   fps,
                                   sensorCropX,
                                   sensorCropY,
                                   inputConfigSync,
                                   previewKeepAspectRatio);

}  // namespace dai
<commit_msg>ColorCameraProperties: add ispScale config<commit_after>#pragma once

#include <depthai-shared/datatype/RawCameraControl.hpp>
#include <nlohmann/json.hpp>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraImageOrientation.hpp"

namespace dai {

/**
 * Specify ColorCamera options such as camera ID, ...
 */
struct ColorCameraProperties {
    static constexpr int AUTO = -1;

    struct IspScale {
        uint8_t horizNumerator = 0;
        uint8_t horizDenominator = 0;
        uint8_t vertNumerator = 0;
        uint8_t vertDenominator = 0;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(IspScale, horizNumerator, horizDenominator, vertNumerator, vertDenominator);
    };

    /**
     * Select the camera sensor resolution
     */
    enum class SensorResolution : int32_t { THE_1080_P, THE_4_K, THE_12_MP };

    /**
     * For 24 bit color these can be either RGB or BGR
     */
    enum class ColorOrder : int32_t { BGR, RGB };

    /*
     * Initial controls applied to ColorCamera node
     */
    RawCameraControl initialControl;

    /**
     * Which socket will color camera use
     */
    CameraBoardSocket boardSocket = CameraBoardSocket::AUTO;

    /**
     * Camera sensor image orientation / pixel readout
     */
    CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO;

    /**
     * For 24 bit color these can be either RGB or BGR
     */
    ColorOrder colorOrder = ColorOrder::BGR;
    /**
     * Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2)
     */
    bool interleaved = true;
    /**
     * Are values FP16 type (0.0 - 255.0)
     */
    bool fp16 = false;

    /**
     * Preview frame output height
     */
    uint32_t previewHeight = 300;
    /**
     * Preview frame output width
     */
    uint32_t previewWidth = 300;

    /**
     * Preview frame output width
     */
    int32_t videoWidth = AUTO;

    /**
     * Preview frame output height
     */
    int32_t videoHeight = AUTO;

    /**
     * Preview frame output width
     */
    int32_t stillWidth = AUTO;

    /**
     * Preview frame output height
     */
    int32_t stillHeight = AUTO;

    /**
     * Select the camera sensor resolution
     */
    SensorResolution resolution = SensorResolution::THE_1080_P;
    /**
     * Camera sensor FPS
     */
    float fps = 30.0;

    /**
     * Initial sensor crop, -1 signifies center crop
     */
    float sensorCropX = AUTO;
    float sensorCropY = AUTO;

    /**
     * Whether to wait for config at 'inputConfig' io
     */
    bool inputConfigSync = false;

    /**
     * Whether to keep aspect ratio of input (video size) or not
     */
    bool previewKeepAspectRatio = true;

    /**
     * Configure scaling for `isp` output.
     */
    IspScale ispScale;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(ColorCameraProperties,
                                   initialControl,
                                   boardSocket,
                                   imageOrientation,
                                   colorOrder,
                                   interleaved,
                                   fp16,
                                   previewHeight,
                                   previewWidth,
                                   videoWidth,
                                   videoHeight,
                                   stillWidth,
                                   stillHeight,
                                   resolution,
                                   fps,
                                   sensorCropX,
                                   sensorCropY,
                                   inputConfigSync,
                                   previewKeepAspectRatio,
                                   ispScale);

}  // namespace dai
<|endoftext|>


<commit_before>#include "main.h"
#include "cvar.h"

class TournamentStartListener: public IGameEventListener2 {
    public:
    virtual ~TournamentStartListener() {}
    virtual void FireGameEvent(IGameEvent *event) {
        ConNotifyf("%s", "Tournament event triggered");
        if (g_pCVar->FindVar("mp_tournament")->GetInt() != 1) return;
        if (!g_pEngineClient->IsRecordingDemo()) {
            prec_record(CCommand(0, nullptr));
        }
    }
};
static TournamentStartListener g_TournamentStartListener;

class PlayerSpawnListener: public IGameEventListener2 {
    public:
    virtual ~PlayerSpawnListener() {}
    virtual void FireGameEvent(IGameEvent *event) {
        if (static_cast<PrecMode>(prec_mode.GetInt()) == PrecMode::Always && g_pCVar->FindVar("mp_tournament")->GetInt() != 1) {
            if (!g_pEngineClient->IsRecordingDemo()) {
                prec_record(CCommand(0, nullptr));
            }
        }
    }
};
static PlayerSpawnListener g_PlayerSpawnListener;

bool register_eventlisteners() {
    g_pEventManager->AddListener(&g_TournamentStartListener, "teamplay_restart_round", false);
    g_pEventManager->AddListener(&g_PlayerSpawnListener, "localplayer_respawn", false);
    return true;
}

void unregister_eventlisteners() {
    g_pEventManager->RemoveListener(&g_TournamentStartListener);
    g_pEventManager->RemoveListener(&g_PlayerSpawnListener);
}
<commit_msg>Remove debug notification from tournament event<commit_after>#include "main.h"
#include "cvar.h"

class TournamentStartListener: public IGameEventListener2 {
    public:
    virtual ~TournamentStartListener() {}
    virtual void FireGameEvent(IGameEvent *event) {
        if (g_pCVar->FindVar("mp_tournament")->GetInt() != 1) return;
        if (!g_pEngineClient->IsRecordingDemo()) {
            prec_record(CCommand(0, nullptr));
        }
    }
};
static TournamentStartListener g_TournamentStartListener;

class PlayerSpawnListener: public IGameEventListener2 {
    public:
    virtual ~PlayerSpawnListener() {}
    virtual void FireGameEvent(IGameEvent *event) {
        if (static_cast<PrecMode>(prec_mode.GetInt()) == PrecMode::Always && g_pCVar->FindVar("mp_tournament")->GetInt() != 1) {
            if (!g_pEngineClient->IsRecordingDemo()) {
                prec_record(CCommand(0, nullptr));
            }
        }
    }
};
static PlayerSpawnListener g_PlayerSpawnListener;

bool register_eventlisteners() {
    g_pEventManager->AddListener(&g_TournamentStartListener, "teamplay_restart_round", false);
    g_pEventManager->AddListener(&g_PlayerSpawnListener, "localplayer_respawn", false);
    return true;
}

void unregister_eventlisteners() {
    g_pEventManager->RemoveListener(&g_TournamentStartListener);
    g_pEventManager->RemoveListener(&g_PlayerSpawnListener);
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/InvocationOptions.h"

#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

#ifdef WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif

namespace {
#if defined(LLVM_ON_UNIX)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
    if (!env_var)
      env_var = getenv("DYLD_LIBRARY_PATH");
    if (!env_var)
      env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
    if (env_var != 0) {
      static const char PathSeparator = ':';
      const char* at = env_var;
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          Paths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }

      if (*at != 0)
        if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
          Paths.push_back(at);
    }
#if defined(__APPLE__) || defined(__CYGWIN__)
    Paths.push_back("/usr/local/lib/");
    Paths.push_back("/usr/X11R6/lib/");
    Paths.push_back("/usr/lib/");
    Paths.push_back("/lib/");

    Paths.push_back("/lib/x86_64-linux-gnu/");
    Paths.push_back("/usr/local/lib64/");
    Paths.push_back("/usr/lib64/");
    Paths.push_back("/lib64/");
#else
    static bool initialized = false;
    static std::vector<std::string> SysPaths;
    if (!initialized) {
      // trick to get the system search path
      std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
      FILE *pf = popen(cmd.c_str (), "r");
      std::string result = "";
      std::string sys_path = "";
      char buffer[128];
      while (!feof(pf)) {
        if (fgets(buffer, 128, pf) != NULL)
          result += buffer;
      }
      pclose(pf);
      std::size_t from
        = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
      std::size_t to = result.find("(system search path)");
      if (from != std::string::npos && to != std::string::npos) {
        from += 12;
        sys_path = result.substr(from, to-from);
        sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),
                       sys_path.end());
        sys_path += ':';
      }
      static const char PathSeparator = ':';
      const char* at = sys_path.c_str();
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          SysPaths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }
      initialized = true;
    }

    for (std::vector<std::string>::const_iterator I = SysPaths.begin(),
           E = SysPaths.end(); I != E; ++I)
      Paths.push_back((*I).c_str());
#endif
  }
#elif defined(LLVM_ON_WIN32)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char buff[MAX_PATH];
    // Generic form of C:\Windows\System32
    HRESULT res =  SHGetFolderPathA(NULL,
                                    CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
                                    NULL,
                                    SHGFP_TYPE_CURRENT,
                                    buff);
    if (res != S_OK) {
      assert(0 && "Failed to get system directory");
      return;
    }
    Paths.push_back(buff);

    // Reset buff.
    buff[0] = 0;
    // Generic form of C:\Windows
    res =  SHGetFolderPathA(NULL,
                            CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
                            NULL,
                            SHGFP_TYPE_CURRENT,
                            buff);
    if (res != S_OK) {
      assert(0 && "Failed to get windows directory");
      return;
    }
    Paths.push_back(buff);
  }
#else
# error "Unsupported platform."
#endif

}

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts), m_Callbacks(0) {
    GetSystemLibraryPaths(m_SystemSearchPaths);
    m_SystemSearchPaths.push_back(".");
  }

  DynamicLibraryManager::~DynamicLibraryManager() {}

  static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {
    using namespace llvm::sys::fs;
    file_magic Magic;
    std::error_code Error = identify_magic(LibName, Magic);
    bool onDisk = (Error != std::errc::no_such_file_or_directory);
    if (exists)
      *exists = onDisk;

    return onDisk &&
#ifdef __APPLE__
      (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib_stub
       || Magic == file_magic::macho_universal_binary)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
      (Magic == file_magic::pecoff_executable)
#else
      (Magic == file_magic::elf_shared_object)
#endif
#elif defined(LLVM_ON_WIN32)
      (Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
      ;
  }

  std::string
  DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
    llvm::SmallVector<std::string, 128>
      Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
    Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());

    for (llvm::SmallVectorImpl<std::string>::const_iterator
           IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {
      llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop
      llvm::sys::path::append(ThisPath, libStem);
      bool exists;
      if (isSharedLib(ThisPath.str(), &exists))
        return ThisPath.str();
      if (exists)
        return "";
    }
    return "";
  }

  std::string
  DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
    using namespace llvm::sys;

    std::string foundDyLib = lookupLibInPaths(libStem);

    if (foundDyLib.empty()) {
      // Add DyLib extension:
      llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
      llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
      static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
      static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
      filenameWithExt += DyLibExt;
      foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
      if (foundDyLib.empty()) {
        filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
        filenameWithExt += ".dylib";
        foundDyLib = lookupLibInPaths(filenameWithExt);
      }
#endif
    }

    if (foundDyLib.empty())
      return "";

    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    llvm::SmallString<_MAX_PATH> FullPath("");
    char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);
#else
    llvm::SmallString<PATH_MAX+1> FullPath("");
    char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());
#endif
    if (res == 0) {
      llvm::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): "
        "error getting real (canonical) path of library " << foundDyLib << '\n';
      return foundDyLib;
    }
    FullPath.set_size(strlen(res));
    return FullPath.str();
  }

  std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {
    // Make the path canonical if the file exists.
    struct stat buffer;
    if (stat(path.data(), &buffer) != 0)
      return "";
#if defined(LLVM_ON_WIN32)
    char buf[_MAX_PATH];
    char *res = _fullpath(buf, path.data(), _MAX_PATH);
#else
    char buf[PATH_MAX+1];
    char *res = realpath(path.data(), buf);
#endif
    if (res == 0) {
      assert(0 && "Cannot normalize!?");
      return "";
    }
    return res;
  }

  std::string
  DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
    llvm::SmallString<128> Absolute(libStem);
    llvm::sys::fs::make_absolute(Absolute);
    bool isAbsolute = libStem == Absolute;

    // If it is an absolute path, don't try iterate over the paths.
    if (isAbsolute) {
      if (isSharedLib(libStem))
        return normalizePath(libStem);
      else
        return "";
    }

    std::string foundName = lookupLibMaybeAddExt(libStem);
    if (foundName.empty() && !libStem.startswith("lib")) {
      // try with "lib" prefix:
      foundName = lookupLibMaybeAddExt("lib" + libStem.str());
    }

    if (isSharedLib(foundName))
      return normalizePath(foundName);
    return "";
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& libStem,
                                     bool permanent) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (canonicalLoadedLib.empty())
      return kLoadLibNotFound;

    if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
      return kLoadLibAlreadyLoaded;

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,
                                        DONT_RESOLVE_DLL_REFERENCES);
    errMsg = "LoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),
                                     RTLD_LAZY|RTLD_GLOBAL);
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (!dyLibHandle) {
      llvm::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg
                   << '\n';
      return kLoadLibLoadError;
    }
    else if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);

    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            canonicalLoadedLib));
    if (!insRes.second)
      return kLoadLibAlreadyLoaded;
    m_LoadedLibraries.insert(canonicalLoadedLib);
    return kLoadLibSuccess;
  }

  void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (!isLibraryLoaded(canonicalLoadedLib))
      return;

    DyLibHandle dyLibHandle = 0;
    for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
         I != E; ++I) {
      if (I->second == canonicalLoadedLib)
        dyLibHandle = I->first;
    }

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    FreeLibrary((HMODULE)dyLibHandle);
    errMsg = "UnoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    dlclose(const_cast<void*>(dyLibHandle));
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);

    m_DyLibs.erase(dyLibHandle);
    m_LoadedLibraries.erase(canonicalLoadedLib);
  }

  bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
    std::string canonPath = normalizePath(fullPath);
    if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())
      return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }
} // end namespace cling
<commit_msg>Use LLVM_ON_WIN32 instead of WIN32 CPP macro.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/InvocationOptions.h"

#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

#ifdef LLVM_ON_WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif

namespace {
#if defined(LLVM_ON_UNIX)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
    if (!env_var)
      env_var = getenv("DYLD_LIBRARY_PATH");
    if (!env_var)
      env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
    if (env_var != 0) {
      static const char PathSeparator = ':';
      const char* at = env_var;
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          Paths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }

      if (*at != 0)
        if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
          Paths.push_back(at);
    }
#if defined(__APPLE__) || defined(__CYGWIN__)
    Paths.push_back("/usr/local/lib/");
    Paths.push_back("/usr/X11R6/lib/");
    Paths.push_back("/usr/lib/");
    Paths.push_back("/lib/");

    Paths.push_back("/lib/x86_64-linux-gnu/");
    Paths.push_back("/usr/local/lib64/");
    Paths.push_back("/usr/lib64/");
    Paths.push_back("/lib64/");
#else
    static bool initialized = false;
    static std::vector<std::string> SysPaths;
    if (!initialized) {
      // trick to get the system search path
      std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
      FILE *pf = popen(cmd.c_str (), "r");
      std::string result = "";
      std::string sys_path = "";
      char buffer[128];
      while (!feof(pf)) {
        if (fgets(buffer, 128, pf) != NULL)
          result += buffer;
      }
      pclose(pf);
      std::size_t from
        = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
      std::size_t to = result.find("(system search path)");
      if (from != std::string::npos && to != std::string::npos) {
        from += 12;
        sys_path = result.substr(from, to-from);
        sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),
                       sys_path.end());
        sys_path += ':';
      }
      static const char PathSeparator = ':';
      const char* at = sys_path.c_str();
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          SysPaths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }
      initialized = true;
    }

    for (std::vector<std::string>::const_iterator I = SysPaths.begin(),
           E = SysPaths.end(); I != E; ++I)
      Paths.push_back((*I).c_str());
#endif
  }
#elif defined(LLVM_ON_WIN32)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char buff[MAX_PATH];
    // Generic form of C:\Windows\System32
    HRESULT res =  SHGetFolderPathA(NULL,
                                    CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
                                    NULL,
                                    SHGFP_TYPE_CURRENT,
                                    buff);
    if (res != S_OK) {
      assert(0 && "Failed to get system directory");
      return;
    }
    Paths.push_back(buff);

    // Reset buff.
    buff[0] = 0;
    // Generic form of C:\Windows
    res =  SHGetFolderPathA(NULL,
                            CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
                            NULL,
                            SHGFP_TYPE_CURRENT,
                            buff);
    if (res != S_OK) {
      assert(0 && "Failed to get windows directory");
      return;
    }
    Paths.push_back(buff);
  }
#else
# error "Unsupported platform."
#endif

}

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts), m_Callbacks(0) {
    GetSystemLibraryPaths(m_SystemSearchPaths);
    m_SystemSearchPaths.push_back(".");
  }

  DynamicLibraryManager::~DynamicLibraryManager() {}

  static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {
    using namespace llvm::sys::fs;
    file_magic Magic;
    std::error_code Error = identify_magic(LibName, Magic);
    bool onDisk = (Error != std::errc::no_such_file_or_directory);
    if (exists)
      *exists = onDisk;

    return onDisk &&
#ifdef __APPLE__
      (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib_stub
       || Magic == file_magic::macho_universal_binary)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
      (Magic == file_magic::pecoff_executable)
#else
      (Magic == file_magic::elf_shared_object)
#endif
#elif defined(LLVM_ON_WIN32)
      (Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
      ;
  }

  std::string
  DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
    llvm::SmallVector<std::string, 128>
      Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
    Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());

    for (llvm::SmallVectorImpl<std::string>::const_iterator
           IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {
      llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop
      llvm::sys::path::append(ThisPath, libStem);
      bool exists;
      if (isSharedLib(ThisPath.str(), &exists))
        return ThisPath.str();
      if (exists)
        return "";
    }
    return "";
  }

  std::string
  DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
    using namespace llvm::sys;

    std::string foundDyLib = lookupLibInPaths(libStem);

    if (foundDyLib.empty()) {
      // Add DyLib extension:
      llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
      llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
      static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
      static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
      filenameWithExt += DyLibExt;
      foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
      if (foundDyLib.empty()) {
        filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
        filenameWithExt += ".dylib";
        foundDyLib = lookupLibInPaths(filenameWithExt);
      }
#endif
    }

    if (foundDyLib.empty())
      return "";

    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    llvm::SmallString<_MAX_PATH> FullPath("");
    char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);
#else
    llvm::SmallString<PATH_MAX+1> FullPath("");
    char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());
#endif
    if (res == 0) {
      llvm::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): "
        "error getting real (canonical) path of library " << foundDyLib << '\n';
      return foundDyLib;
    }
    FullPath.set_size(strlen(res));
    return FullPath.str();
  }

  std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {
    // Make the path canonical if the file exists.
    struct stat buffer;
    if (stat(path.data(), &buffer) != 0)
      return "";
#if defined(LLVM_ON_WIN32)
    char buf[_MAX_PATH];
    char *res = _fullpath(buf, path.data(), _MAX_PATH);
#else
    char buf[PATH_MAX+1];
    char *res = realpath(path.data(), buf);
#endif
    if (res == 0) {
      assert(0 && "Cannot normalize!?");
      return "";
    }
    return res;
  }

  std::string
  DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
    llvm::SmallString<128> Absolute(libStem);
    llvm::sys::fs::make_absolute(Absolute);
    bool isAbsolute = libStem == Absolute;

    // If it is an absolute path, don't try iterate over the paths.
    if (isAbsolute) {
      if (isSharedLib(libStem))
        return normalizePath(libStem);
      else
        return "";
    }

    std::string foundName = lookupLibMaybeAddExt(libStem);
    if (foundName.empty() && !libStem.startswith("lib")) {
      // try with "lib" prefix:
      foundName = lookupLibMaybeAddExt("lib" + libStem.str());
    }

    if (isSharedLib(foundName))
      return normalizePath(foundName);
    return "";
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& libStem,
                                     bool permanent) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (canonicalLoadedLib.empty())
      return kLoadLibNotFound;

    if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
      return kLoadLibAlreadyLoaded;

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,
                                        DONT_RESOLVE_DLL_REFERENCES);
    errMsg = "LoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),
                                     RTLD_LAZY|RTLD_GLOBAL);
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (!dyLibHandle) {
      llvm::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg
                   << '\n';
      return kLoadLibLoadError;
    }
    else if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);

    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            canonicalLoadedLib));
    if (!insRes.second)
      return kLoadLibAlreadyLoaded;
    m_LoadedLibraries.insert(canonicalLoadedLib);
    return kLoadLibSuccess;
  }

  void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (!isLibraryLoaded(canonicalLoadedLib))
      return;

    DyLibHandle dyLibHandle = 0;
    for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
         I != E; ++I) {
      if (I->second == canonicalLoadedLib)
        dyLibHandle = I->first;
    }

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    FreeLibrary((HMODULE)dyLibHandle);
    errMsg = "UnoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    dlclose(const_cast<void*>(dyLibHandle));
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);

    m_DyLibs.erase(dyLibHandle);
    m_LoadedLibraries.erase(canonicalLoadedLib);
  }

  bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
    std::string canonPath = normalizePath(fullPath);
    if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())
      return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }
} // end namespace cling
<|endoftext|>