<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_start_cbs.C
///
/// @brief Start CBS : Trigger CBS
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SE:HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_start_cbs.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9_perv_scom_addresses_fld.H>
#include <p9_perv_scom_addresses_fixes.H>
#include <p9_perv_scom_addresses_fld_fixes.H>

enum P9_START_CBS_Private_Constants
{
    P9_CFAM_CBS_POLL_COUNT = 600, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR
    CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR
    P9_CBS_IDLE_HW_NS_DELAY = 100000, // unit is nano seconds
    P9_CBS_IDLE_SIM_CYCLE_DELAY = 250000 // unit is sim cycles
};

fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
                               & i_target_chip,
                               const bool i_sbe_start)
{
    fapi2::buffer<uint32_t> l_read_reg ;
    bool l_read_vdn_pgood_status = false;
    bool l_sbe_start_value = false;
    bool l_fsi2pib_status = false;
    fapi2::buffer<uint32_t> l_data32;
    fapi2::buffer<uint32_t> l_data32_cbs_cs;
    int l_timeout = 0;
    FAPI_INF("Entering ...");

    l_sbe_start_value = !i_sbe_start;

    FAPI_DBG("Configuring Prevent SBE start option");
    FAPI_IMP("SBE start value : %d", l_sbe_start_value);
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value
    l_data32_cbs_cs.writeBit<3>(l_sbe_start_value);
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("check for VDN_PGOOD");
    //Getting PERV_CBS_ENVSTAT register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_ENVSTAT_FSI,
                                    l_data32));
    l_read_vdn_pgood_status =
        l_data32.getBit<PERV_CBS_ENVSTAT_C4_VDN_GPOOD>();  //l_read_vdn_pgood_status = PERV_CBS_ENVSTAT.PERV_CBS_ENVSTAT_C4_VDN_GPOOD

    FAPI_ASSERT(l_read_vdn_pgood_status,
                fapi2::VDN_PGOOD_NOT_SET(),
                "ERROR:VDN PGOOD OFF, CBS_ENVSTAT BIT 2 NOT SET");

    FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value");
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    l_data32_cbs_cs.clearBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    // HW319150 - pervSoA:  cbs_start is implemented as pulse 0 -> 1
    FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start");
    //Setting CBS_CS register value
    l_data32_cbs_cs.setBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Check cbs_cs_internal_state_vector");
    l_timeout = P9_CFAM_CBS_POLL_COUNT;

    //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE
    while (l_timeout != 0)
    {
        //Getting CBS_CS register value
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                        l_data32_cbs_cs));
        uint32_t l_poll_data = 0;    //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR
        l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data);

        if (l_poll_data == CBS_IDLE_VALUE)
        {
            break;
        }

        fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY);
        --l_timeout;
    }

    FAPI_DBG("Loop Count :%d", l_timeout);

    FAPI_ASSERT(l_timeout > 0,
                fapi2::CBS_CS_INTERNAL_STATE(),
                "ERROR: CBS_CS_INTERNAL_STATE_VECTOR HAS NOT REACHED IDLE STATE VALUE 0x002 ");

    FAPI_DBG("check for VDD status");
    //Getting FSI2PIB_STATUS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_FSI2PIB_STATUS_FSI,
                                    l_data32));
    //l_fsi2pib_status = CFAM.FSI2PIB_STATUS.VDD_NEST_OBSERVE
    l_fsi2pib_status = l_data32.getBit<PERV_FSI2PIB_STATUS_VDD_NEST_OBSERVE>();

    FAPI_ASSERT(l_fsi2pib_status,
                fapi2::VDD_NEST_OBSERVE(),
                "ERROR:VDD OFF, FSI2PIB  BIT 16 NOT SET");

    FAPI_INF("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>FAPI_INF entering and exiting message updates<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_start_cbs.C
///
/// @brief Start CBS : Trigger CBS
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SE:HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_start_cbs.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9_perv_scom_addresses_fld.H>
#include <p9_perv_scom_addresses_fixes.H>
#include <p9_perv_scom_addresses_fld_fixes.H>

enum P9_START_CBS_Private_Constants
{
    P9_CFAM_CBS_POLL_COUNT = 600, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR
    CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR
    P9_CBS_IDLE_HW_NS_DELAY = 100000, // unit is nano seconds
    P9_CBS_IDLE_SIM_CYCLE_DELAY = 250000 // unit is sim cycles
};

fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
                               & i_target_chip,
                               const bool i_sbe_start)
{
    fapi2::buffer<uint32_t> l_read_reg ;
    bool l_read_vdn_pgood_status = false;
    bool l_sbe_start_value = false;
    bool l_fsi2pib_status = false;
    fapi2::buffer<uint32_t> l_data32;
    fapi2::buffer<uint32_t> l_data32_cbs_cs;
    int l_timeout = 0;
    FAPI_INF("p9_start_cbs: Entering ...");

    l_sbe_start_value = !i_sbe_start;

    FAPI_DBG("Configuring Prevent SBE start option");
    FAPI_IMP("SBE start value : %d", l_sbe_start_value);
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value
    l_data32_cbs_cs.writeBit<3>(l_sbe_start_value);
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("check for VDN_PGOOD");
    //Getting PERV_CBS_ENVSTAT register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_ENVSTAT_FSI,
                                    l_data32));
    l_read_vdn_pgood_status =
        l_data32.getBit<PERV_CBS_ENVSTAT_C4_VDN_GPOOD>();  //l_read_vdn_pgood_status = PERV_CBS_ENVSTAT.PERV_CBS_ENVSTAT_C4_VDN_GPOOD

    FAPI_ASSERT(l_read_vdn_pgood_status,
                fapi2::VDN_PGOOD_NOT_SET(),
                "ERROR:VDN PGOOD OFF, CBS_ENVSTAT BIT 2 NOT SET");

    FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value");
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    l_data32_cbs_cs.clearBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    // HW319150 - pervSoA:  cbs_start is implemented as pulse 0 -> 1
    FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start");
    //Setting CBS_CS register value
    l_data32_cbs_cs.setBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Check cbs_cs_internal_state_vector");
    l_timeout = P9_CFAM_CBS_POLL_COUNT;

    //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE
    while (l_timeout != 0)
    {
        //Getting CBS_CS register value
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                        l_data32_cbs_cs));
        uint32_t l_poll_data = 0;    //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR
        l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data);

        if (l_poll_data == CBS_IDLE_VALUE)
        {
            break;
        }

        fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY);
        --l_timeout;
    }

    FAPI_DBG("Loop Count :%d", l_timeout);

    FAPI_ASSERT(l_timeout > 0,
                fapi2::CBS_CS_INTERNAL_STATE(),
                "ERROR: CBS_CS_INTERNAL_STATE_VECTOR HAS NOT REACHED IDLE STATE VALUE 0x002 ");

    FAPI_DBG("check for VDD status");
    //Getting FSI2PIB_STATUS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_FSI2PIB_STATUS_FSI,
                                    l_data32));
    //l_fsi2pib_status = CFAM.FSI2PIB_STATUS.VDD_NEST_OBSERVE
    l_fsi2pib_status = l_data32.getBit<PERV_FSI2PIB_STATUS_VDD_NEST_OBSERVE>();

    FAPI_ASSERT(l_fsi2pib_status,
                fapi2::VDD_NEST_OBSERVE(),
                "ERROR:VDD OFF, FSI2PIB  BIT 16 NOT SET");

    FAPI_INF("p9_start_cbs: Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "InitialiseRest.h"

#include <openssl/ssl.h>
#include <openssl/err.h>

#define OPENSSL_THREAD_DEFINES

#include <openssl/opensslconf.h>

#ifndef OPENSSL_THREADS
#error missing thread support for openssl, please recomple OpenSSL with threads
#endif

#include "Basics/logging.h"

#include "Basics/InitialiseBasics.h"
#include "Rest/HttpResponse.h"
#include "Rest/Version.h"
#include "Statistics/statistics.h"

// -----------------------------------------------------------------------------
// OPEN SSL support
// -----------------------------------------------------------------------------

#ifdef TRI_HAVE_POSIX_THREADS

namespace {
  long* opensslLockCount;
  pthread_mutex_t* opensslLocks;

#if OPENSSL_VERSION_NUMBER < 0x01000000L

  unsigned long opensslThreadId () {
    return (unsigned long) pthread_self();
  }

#else
  // The compiler chooses the right one from the following two,
  // according to the type of the return value of pthread_self():

  template<typename T> void setter (CRYPTO_THREADID* id, T p) {
    CRYPTO_THREADID_set_pointer(id, p);
  }

  template<> void setter (CRYPTO_THREADID* id, unsigned long val) {
    CRYPTO_THREADID_set_numeric(id, val);
  }

  static void arango_threadid_func (CRYPTO_THREADID *id) {
    auto self = pthread_self();

    setter<decltype(self)>(id, self);
  }

#endif

  void opensslLockingCallback (int mode, int type, char const* /* file */, int /* line */) {
    if (mode & CRYPTO_LOCK) {
      pthread_mutex_lock(&(opensslLocks[type]));
      opensslLockCount[type]++;
    }
    else {
      pthread_mutex_unlock(&(opensslLocks[type]));
    }

  }

  void opensslSetup () {
    opensslLockCount = (long*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
    opensslLocks = (pthread_mutex_t*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));

    for (long i = 0;  i < CRYPTO_num_locks();  ++i) {
      opensslLockCount[i] = 0;
      pthread_mutex_init(&(opensslLocks[i]), 0);
    }

#if OPENSSL_VERSION_NUMBER < 0x01000000L
    CRYPTO_set_id_callback(opensslThreadId);
    CRYPTO_set_locking_callback(opensslLockingCallback);
#else
    CRYPTO_THREADID_set_callback(arango_threadid_func);
    CRYPTO_set_locking_callback(opensslLockingCallback);
#endif
  }

  void opensslCleanup () {
    CRYPTO_set_locking_callback(nullptr);

#if OPENSSL_VERSION_NUMBER < 0x01000000L
    CRYPTO_set_id_callback(nullptr);
#else
    CRYPTO_THREADID_set_callback(nullptr);
#endif

    for (long i = 0;  i < CRYPTO_num_locks();  ++i) {
      pthread_mutex_destroy(&(opensslLocks[i]));
    }

    OPENSSL_free(opensslLocks);
    OPENSSL_free(opensslLockCount);
  }
}

#endif

// -----------------------------------------------------------------------------
// initialisation
// -----------------------------------------------------------------------------

namespace triagens {
  namespace rest {
    void InitialiseRest (int argc, char* argv[]) {
      TRIAGENS_BASICS_INITIALISE(argc, argv);

      TRI_InitialiseStatistics();

      SSL_library_init();
      SSL_load_error_strings();
      OpenSSL_add_all_algorithms();
      ERR_load_crypto_strings();

#ifdef TRI_HAVE_POSIX_THREADS
      opensslSetup();
#endif

      Version::initialise();
    }

    void ShutdownRest () {
#ifdef TRI_HAVE_POSIX_THREADS
        opensslCleanup();
#endif

      TRI_ShutdownStatistics();

      TRIAGENS_BASICS_SHUTDOWN;
    }
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Use porting functions for initialisation, so ssl locking works on windows<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "InitialiseRest.h"

#include <openssl/ssl.h>
#include <openssl/err.h>

#define OPENSSL_THREAD_DEFINES

#include <openssl/opensslconf.h>

#ifndef OPENSSL_THREADS
#error missing thread support for openssl, please recomple OpenSSL with threads
#endif

#include "Basics/logging.h"
#include "Basics/threads.h"
#include "Basics/InitialiseBasics.h"
#include "Rest/HttpResponse.h"
#include "Rest/Version.h"
#include "Statistics/statistics.h"

// -----------------------------------------------------------------------------
// OPEN SSL support
// -----------------------------------------------------------------------------

namespace {
  long* opensslLockCount;
  TRI_mutex_t* opensslLocks;

#if OPENSSL_VERSION_NUMBER < 0x01000000L

  unsigned long opensslThreadId () {
    return (unsigned long) TRI_CurrentThreadId();
  }

#else
  // The compiler chooses the right one from the following two,
  // according to the type of the return value of pthread_self():

  template<typename T> void setter (CRYPTO_THREADID* id, T p) {
    CRYPTO_THREADID_set_pointer(id, p);
  }

  template<> void setter (CRYPTO_THREADID* id, unsigned long val) {
    CRYPTO_THREADID_set_numeric(id, val);
  }

  static void arango_threadid_func (CRYPTO_THREADID *id) {
    auto self = TRI_CurrentThreadId();

    setter<decltype(self)>(id, self);
  }

#endif

  void opensslLockingCallback (int mode, int type, char const* /* file */, int /* line */) {
    if (mode & CRYPTO_LOCK) {
      TRI_LockMutex(&(opensslLocks[type]));
      opensslLockCount[type]++;
    }
    else {
      TRI_UnlockMutex(&(opensslLocks[type]));
    }

  }

  void opensslSetup () {
    opensslLockCount = (long*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
    opensslLocks = (TRI_mutex_t*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(TRI_mutex_t));

    for (long i = 0;  i < CRYPTO_num_locks();  ++i) {
      opensslLockCount[i] = 0;
      TRI_InitMutex(&(opensslLocks[i]));
    }

#if OPENSSL_VERSION_NUMBER < 0x01000000L
    CRYPTO_set_id_callback(opensslThreadId);
    CRYPTO_set_locking_callback(opensslLockingCallback);
#else
    CRYPTO_THREADID_set_callback(arango_threadid_func);
    CRYPTO_set_locking_callback(opensslLockingCallback);
#endif
  }

  void opensslCleanup () {
    CRYPTO_set_locking_callback(nullptr);

#if OPENSSL_VERSION_NUMBER < 0x01000000L
    CRYPTO_set_id_callback(nullptr);
#else
    CRYPTO_THREADID_set_callback(nullptr);
#endif

    for (long i = 0;  i < CRYPTO_num_locks();  ++i) {
      TRI_DestroyMutex(&(opensslLocks[i]));
    }

    OPENSSL_free(opensslLocks);
    OPENSSL_free(opensslLockCount);
  }
}

// -----------------------------------------------------------------------------
// initialisation
// -----------------------------------------------------------------------------

namespace triagens {
  namespace rest {
    void InitialiseRest (int argc, char* argv[]) {
      TRIAGENS_BASICS_INITIALISE(argc, argv);

      TRI_InitialiseStatistics();

      SSL_library_init();
      SSL_load_error_strings();
      OpenSSL_add_all_algorithms();
      ERR_load_crypto_strings();

      opensslSetup();

      Version::initialise();
    }

    void ShutdownRest () {
      opensslCleanup();

      TRI_ShutdownStatistics();

      TRIAGENS_BASICS_SHUTDOWN;
    }
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements support for bulk buffered stream output.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include "llvm/System/Program.h"
#include "llvm/System/Process.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include <ostream>

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif

#if defined(_MSC_VER)
#include <io.h>
#include <fcntl.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

using namespace llvm;

raw_ostream::~raw_ostream() {
  // raw_ostream's subclasses should take care to flush the buffer
  // in their destructors.
  assert(OutBufCur == OutBufStart &&
         "raw_ostream destructor called with non-empty buffer!");

  delete [] OutBufStart;

  // If there are any pending errors, report them now. Clients wishing
  // to avoid llvm_report_error calls should check for errors with
  // has_error() and clear the error flag with clear_error() before
  // destructing raw_ostream objects which may have errors.
  if (Error)
    llvm_report_error("IO failure on output stream.");
}

// An out of line virtual method to provide a home for the class vtable.
void raw_ostream::handle() {}

raw_ostream &raw_ostream::operator<<(unsigned long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long N) {
  if (N <  0) {
    *this << '-';
    N = -N;
  }

  return this->operator<<(static_cast<unsigned long>(N));
}

raw_ostream &raw_ostream::operator<<(unsigned long long N) {
  // Output using 32-bit div/mod when possible.
  if (N == static_cast<unsigned long>(N))
    return this->operator<<(static_cast<unsigned long>(N));

  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long long N) {
  if (N <  0) {
    *this << '-';
    N = -N;
  }

  return this->operator<<(static_cast<unsigned long long>(N));
}

raw_ostream &raw_ostream::operator<<(const void *P) {
  uintptr_t N = (uintptr_t) P;
  *this << '0' << 'x';

  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    uintptr_t x = N % 16;
    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
    N /= 16;
  }

  return write(CurPtr, EndPtr-CurPtr);
}

void raw_ostream::flush_nonempty() {
  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
  write_impl(OutBufStart, OutBufCur - OutBufStart);
  OutBufCur = OutBufStart;
}

raw_ostream &raw_ostream::write(unsigned char C) {
  // Group exceptional cases into a single branch.
  if (OutBufCur >= OutBufEnd) {
    if (Unbuffered) {
      write_impl(reinterpret_cast<char*>(&C), 1);
      return *this;
    }

    if (!OutBufStart)
      SetBufferSize();
    else
      flush_nonempty();
  }

  *OutBufCur++ = C;
  return *this;
}

raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
  // Group exceptional cases into a single branch.
  if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
    if (Unbuffered) {
      write_impl(Ptr, Size);
      return *this;
    }

    if (!OutBufStart)
      SetBufferSize();
    else
      flush_nonempty();
  }

  // Handle short strings specially, memcpy isn't very good at very short
  // strings.
  switch (Size) {
  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
  case 0: break;
  default:
    // Normally the string to emit is shorter than the buffer.
    if (Size <= unsigned(OutBufEnd-OutBufCur)) {
      memcpy(OutBufCur, Ptr, Size);
      break;
    }

    // Otherwise we are emitting a string larger than our buffer. We
    // know we already flushed, so just write it out directly.
    write_impl(Ptr, Size);
    Size = 0;
    break;
  }
  OutBufCur += Size;

  return *this;
}

// Formatted output.
raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
  // If we have more than a few bytes left in our output buffer, try
  // formatting directly onto its end.
  //
  // FIXME: This test is a bit silly, since if we don't have enough
  // space in the buffer we will have to flush the formatted output
  // anyway. We should just flush upfront in such cases, and use the
  // whole buffer as our scratch pad. Note, however, that this case is
  // also necessary for correctness on unbuffered streams.
  size_t NextBufferSize = 127;
  if (OutBufEnd-OutBufCur > 3) {
    size_t BufferBytesLeft = OutBufEnd-OutBufCur;
    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);

    // Common case is that we have plenty of space.
    if (BytesUsed < BufferBytesLeft) {
      OutBufCur += BytesUsed;
      return *this;
    }

    // Otherwise, we overflowed and the return value tells us the size to try
    // again with.
    NextBufferSize = BytesUsed;
  }

  // If we got here, we didn't have enough space in the output buffer for the
  // string.  Try printing into a SmallVector that is resized to have enough
  // space.  Iterate until we win.
  SmallVector<char, 128> V;

  while (1) {
    V.resize(NextBufferSize);

    // Try formatting into the SmallVector.
    size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);

    // If BytesUsed fit into the vector, we win.
    if (BytesUsed <= NextBufferSize)
      return write(&V[0], BytesUsed);

    // Otherwise, try again with a new size.
    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
    NextBufferSize = BytesUsed;
  }
}

//===----------------------------------------------------------------------===//
//  Formatted Output
//===----------------------------------------------------------------------===//

// Out of line virtual method.
void format_object_base::home() {
}

//===----------------------------------------------------------------------===//
//  raw_fd_ostream
//===----------------------------------------------------------------------===//

/// raw_fd_ostream - Open the specified file for writing. If an error
/// occurs, information about the error is put into ErrorInfo, and the
/// stream should be immediately destroyed; the string will be empty
/// if no error occurred.
raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
                               std::string &ErrorInfo) : pos(0) {
  ErrorInfo.clear();

  // Handle "-" as stdout.
  if (Filename[0] == '-' && Filename[1] == 0) {
    FD = STDOUT_FILENO;
    // If user requested binary then put stdout into binary mode if
    // possible.
    if (Binary)
      sys::Program::ChangeStdoutToBinary();
    ShouldClose = false;
    return;
  }

  int Flags = O_WRONLY|O_CREAT|O_TRUNC;
#ifdef O_BINARY
  if (Binary)
    Flags |= O_BINARY;
#endif
  if (!Force)
    Flags |= O_EXCL;
  FD = open(Filename, Flags, 0664);
  if (FD < 0) {
    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
    ShouldClose = false;
  } else {
    ShouldClose = true;
  }
}

raw_fd_ostream::~raw_fd_ostream() {
  if (FD >= 0) {
    flush();
    if (ShouldClose)
      if (::close(FD) != 0)
        error_detected();
  }
}

void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
  assert (FD >= 0 && "File already closed.");
  pos += Size;
  if (::write(FD, Ptr, Size) != (ssize_t) Size)
    error_detected();
}

void raw_fd_ostream::close() {
  assert (ShouldClose);
  ShouldClose = false;
  flush();
  if (::close(FD) != 0)
    error_detected();
  FD = -1;
}

uint64_t raw_fd_ostream::seek(uint64_t off) {
  flush();
  pos = ::lseek(FD, off, SEEK_SET);
  if (pos != off)
    error_detected();
  return pos;
}

raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
                                         bool bg) {
  if (sys::Process::ColorNeedsFlush())
    flush();
  const char *colorcode =
    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
    : sys::Process::OutputColor(colors, bold, bg);
  if (colorcode) {
    size_t len = strlen(colorcode);
    write(colorcode, len);
    // don't account colors towards output characters
    pos -= len;
  }
  return *this;
}

raw_ostream &raw_fd_ostream::resetColor() {
  if (sys::Process::ColorNeedsFlush())
    flush();
  const char *colorcode = sys::Process::ResetColor();
  if (colorcode) {
    size_t len = strlen(colorcode);
    write(colorcode, len);
    // don't account colors towards output characters
    pos -= len;
  }
  return *this;
}

//===----------------------------------------------------------------------===//
//  raw_stdout/err_ostream
//===----------------------------------------------------------------------===//

raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
                                                        true) {}

// An out of line virtual method to provide a home for the class vtable.
void raw_stdout_ostream::handle() {}
void raw_stderr_ostream::handle() {}

/// outs() - This returns a reference to a raw_ostream for standard output.
/// Use it like: outs() << "foo" << "bar";
raw_ostream &llvm::outs() {
  static raw_stdout_ostream S;
  return S;
}

/// errs() - This returns a reference to a raw_ostream for standard error.
/// Use it like: errs() << "foo" << "bar";
raw_ostream &llvm::errs() {
  static raw_stderr_ostream S;
  return S;
}

/// nulls() - This returns a reference to a raw_ostream which discards output.
raw_ostream &llvm::nulls() {
  static raw_null_ostream S;
  return S;
}

//===----------------------------------------------------------------------===//
//  raw_os_ostream
//===----------------------------------------------------------------------===//

raw_os_ostream::~raw_os_ostream() {
  flush();
}

void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.write(Ptr, Size);
}

uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }

uint64_t raw_os_ostream::tell() {
  return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
}

//===----------------------------------------------------------------------===//
//  raw_string_ostream
//===----------------------------------------------------------------------===//

raw_string_ostream::~raw_string_ostream() {
  flush();
}

void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.append(Ptr, Size);
}

//===----------------------------------------------------------------------===//
//  raw_svector_ostream
//===----------------------------------------------------------------------===//

raw_svector_ostream::~raw_svector_ostream() {
  flush();
}

void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.append(Ptr, Ptr + Size);
}

uint64_t raw_svector_ostream::current_pos() { return OS.size(); }

uint64_t raw_svector_ostream::tell() {
  return OS.size() + GetNumBytesInBuffer();
}

//===----------------------------------------------------------------------===//
//  raw_null_ostream
//===----------------------------------------------------------------------===//

raw_null_ostream::~raw_null_ostream() {
#ifndef NDEBUG
  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
  // with raw_null_ostream, but it's better to have raw_null_ostream follow
  // the rules than to change the rules just for raw_null_ostream.
  flush();
#endif
}

void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
}

uint64_t raw_null_ostream::current_pos() {
  return 0;
}
<commit_msg>Perform simplification noticed by Reid.<commit_after>//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements support for bulk buffered stream output.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include "llvm/System/Program.h"
#include "llvm/System/Process.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include <ostream>

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif

#if defined(_MSC_VER)
#include <io.h>
#include <fcntl.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

using namespace llvm;

raw_ostream::~raw_ostream() {
  // raw_ostream's subclasses should take care to flush the buffer
  // in their destructors.
  assert(OutBufCur == OutBufStart &&
         "raw_ostream destructor called with non-empty buffer!");

  delete [] OutBufStart;

  // If there are any pending errors, report them now. Clients wishing
  // to avoid llvm_report_error calls should check for errors with
  // has_error() and clear the error flag with clear_error() before
  // destructing raw_ostream objects which may have errors.
  if (Error)
    llvm_report_error("IO failure on output stream.");
}

// An out of line virtual method to provide a home for the class vtable.
void raw_ostream::handle() {}

raw_ostream &raw_ostream::operator<<(unsigned long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long N) {
  if (N <  0) {
    *this << '-';
    N = -N;
  }

  return this->operator<<(static_cast<unsigned long>(N));
}

raw_ostream &raw_ostream::operator<<(unsigned long long N) {
  // Output using 32-bit div/mod when possible.
  if (N == static_cast<unsigned long>(N))
    return this->operator<<(static_cast<unsigned long>(N));

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long long N) {
  if (N <  0) {
    *this << '-';
    N = -N;
  }

  return this->operator<<(static_cast<unsigned long long>(N));
}

raw_ostream &raw_ostream::operator<<(const void *P) {
  uintptr_t N = (uintptr_t) P;
  *this << '0' << 'x';

  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    uintptr_t x = N % 16;
    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
    N /= 16;
  }

  return write(CurPtr, EndPtr-CurPtr);
}

void raw_ostream::flush_nonempty() {
  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
  write_impl(OutBufStart, OutBufCur - OutBufStart);
  OutBufCur = OutBufStart;
}

raw_ostream &raw_ostream::write(unsigned char C) {
  // Group exceptional cases into a single branch.
  if (OutBufCur >= OutBufEnd) {
    if (Unbuffered) {
      write_impl(reinterpret_cast<char*>(&C), 1);
      return *this;
    }

    if (!OutBufStart)
      SetBufferSize();
    else
      flush_nonempty();
  }

  *OutBufCur++ = C;
  return *this;
}

raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
  // Group exceptional cases into a single branch.
  if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
    if (Unbuffered) {
      write_impl(Ptr, Size);
      return *this;
    }

    if (!OutBufStart)
      SetBufferSize();
    else
      flush_nonempty();
  }

  // Handle short strings specially, memcpy isn't very good at very short
  // strings.
  switch (Size) {
  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
  case 0: break;
  default:
    // Normally the string to emit is shorter than the buffer.
    if (Size <= unsigned(OutBufEnd-OutBufCur)) {
      memcpy(OutBufCur, Ptr, Size);
      break;
    }

    // Otherwise we are emitting a string larger than our buffer. We
    // know we already flushed, so just write it out directly.
    write_impl(Ptr, Size);
    Size = 0;
    break;
  }
  OutBufCur += Size;

  return *this;
}

// Formatted output.
raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
  // If we have more than a few bytes left in our output buffer, try
  // formatting directly onto its end.
  //
  // FIXME: This test is a bit silly, since if we don't have enough
  // space in the buffer we will have to flush the formatted output
  // anyway. We should just flush upfront in such cases, and use the
  // whole buffer as our scratch pad. Note, however, that this case is
  // also necessary for correctness on unbuffered streams.
  size_t NextBufferSize = 127;
  if (OutBufEnd-OutBufCur > 3) {
    size_t BufferBytesLeft = OutBufEnd-OutBufCur;
    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);

    // Common case is that we have plenty of space.
    if (BytesUsed < BufferBytesLeft) {
      OutBufCur += BytesUsed;
      return *this;
    }

    // Otherwise, we overflowed and the return value tells us the size to try
    // again with.
    NextBufferSize = BytesUsed;
  }

  // If we got here, we didn't have enough space in the output buffer for the
  // string.  Try printing into a SmallVector that is resized to have enough
  // space.  Iterate until we win.
  SmallVector<char, 128> V;

  while (1) {
    V.resize(NextBufferSize);

    // Try formatting into the SmallVector.
    size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);

    // If BytesUsed fit into the vector, we win.
    if (BytesUsed <= NextBufferSize)
      return write(&V[0], BytesUsed);

    // Otherwise, try again with a new size.
    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
    NextBufferSize = BytesUsed;
  }
}

//===----------------------------------------------------------------------===//
//  Formatted Output
//===----------------------------------------------------------------------===//

// Out of line virtual method.
void format_object_base::home() {
}

//===----------------------------------------------------------------------===//
//  raw_fd_ostream
//===----------------------------------------------------------------------===//

/// raw_fd_ostream - Open the specified file for writing. If an error
/// occurs, information about the error is put into ErrorInfo, and the
/// stream should be immediately destroyed; the string will be empty
/// if no error occurred.
raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
                               std::string &ErrorInfo) : pos(0) {
  ErrorInfo.clear();

  // Handle "-" as stdout.
  if (Filename[0] == '-' && Filename[1] == 0) {
    FD = STDOUT_FILENO;
    // If user requested binary then put stdout into binary mode if
    // possible.
    if (Binary)
      sys::Program::ChangeStdoutToBinary();
    ShouldClose = false;
    return;
  }

  int Flags = O_WRONLY|O_CREAT|O_TRUNC;
#ifdef O_BINARY
  if (Binary)
    Flags |= O_BINARY;
#endif
  if (!Force)
    Flags |= O_EXCL;
  FD = open(Filename, Flags, 0664);
  if (FD < 0) {
    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
    ShouldClose = false;
  } else {
    ShouldClose = true;
  }
}

raw_fd_ostream::~raw_fd_ostream() {
  if (FD >= 0) {
    flush();
    if (ShouldClose)
      if (::close(FD) != 0)
        error_detected();
  }
}

void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
  assert (FD >= 0 && "File already closed.");
  pos += Size;
  if (::write(FD, Ptr, Size) != (ssize_t) Size)
    error_detected();
}

void raw_fd_ostream::close() {
  assert (ShouldClose);
  ShouldClose = false;
  flush();
  if (::close(FD) != 0)
    error_detected();
  FD = -1;
}

uint64_t raw_fd_ostream::seek(uint64_t off) {
  flush();
  pos = ::lseek(FD, off, SEEK_SET);
  if (pos != off)
    error_detected();
  return pos;
}

raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
                                         bool bg) {
  if (sys::Process::ColorNeedsFlush())
    flush();
  const char *colorcode =
    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
    : sys::Process::OutputColor(colors, bold, bg);
  if (colorcode) {
    size_t len = strlen(colorcode);
    write(colorcode, len);
    // don't account colors towards output characters
    pos -= len;
  }
  return *this;
}

raw_ostream &raw_fd_ostream::resetColor() {
  if (sys::Process::ColorNeedsFlush())
    flush();
  const char *colorcode = sys::Process::ResetColor();
  if (colorcode) {
    size_t len = strlen(colorcode);
    write(colorcode, len);
    // don't account colors towards output characters
    pos -= len;
  }
  return *this;
}

//===----------------------------------------------------------------------===//
//  raw_stdout/err_ostream
//===----------------------------------------------------------------------===//

raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
                                                        true) {}

// An out of line virtual method to provide a home for the class vtable.
void raw_stdout_ostream::handle() {}
void raw_stderr_ostream::handle() {}

/// outs() - This returns a reference to a raw_ostream for standard output.
/// Use it like: outs() << "foo" << "bar";
raw_ostream &llvm::outs() {
  static raw_stdout_ostream S;
  return S;
}

/// errs() - This returns a reference to a raw_ostream for standard error.
/// Use it like: errs() << "foo" << "bar";
raw_ostream &llvm::errs() {
  static raw_stderr_ostream S;
  return S;
}

/// nulls() - This returns a reference to a raw_ostream which discards output.
raw_ostream &llvm::nulls() {
  static raw_null_ostream S;
  return S;
}

//===----------------------------------------------------------------------===//
//  raw_os_ostream
//===----------------------------------------------------------------------===//

raw_os_ostream::~raw_os_ostream() {
  flush();
}

void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.write(Ptr, Size);
}

uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }

uint64_t raw_os_ostream::tell() {
  return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
}

//===----------------------------------------------------------------------===//
//  raw_string_ostream
//===----------------------------------------------------------------------===//

raw_string_ostream::~raw_string_ostream() {
  flush();
}

void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.append(Ptr, Size);
}

//===----------------------------------------------------------------------===//
//  raw_svector_ostream
//===----------------------------------------------------------------------===//

raw_svector_ostream::~raw_svector_ostream() {
  flush();
}

void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
  OS.append(Ptr, Ptr + Size);
}

uint64_t raw_svector_ostream::current_pos() { return OS.size(); }

uint64_t raw_svector_ostream::tell() {
  return OS.size() + GetNumBytesInBuffer();
}

//===----------------------------------------------------------------------===//
//  raw_null_ostream
//===----------------------------------------------------------------------===//

raw_null_ostream::~raw_null_ostream() {
#ifndef NDEBUG
  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
  // with raw_null_ostream, but it's better to have raw_null_ostream follow
  // the rules than to change the rules just for raw_null_ostream.
  flush();
#endif
}

void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
}

uint64_t raw_null_ostream::current_pos() {
  return 0;
}
<|endoftext|>


<commit_before>//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements support for bulk buffered stream output.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/raw_ostream.h"
#include <ostream>
using namespace llvm;

#include <fcntl.h>

#if defined(_MSC_VER)
#include <io.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

// An out of line virtual method to provide a home for the class vtable.
void raw_ostream::handle() {}

raw_ostream &raw_ostream::operator<<(unsigned long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long N) {
  if (N <  0) {
    if (OutBufCur >= OutBufEnd)
      flush_impl();
    *OutBufCur++ = '-';

    N = -N;
  }

  return this->operator<<(static_cast<unsigned long>(N));
}

raw_ostream &raw_ostream::operator<<(unsigned long long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long long N) {
  if (N <  0) {
    if (OutBufCur >= OutBufEnd)
      flush_impl();
    *OutBufCur++ = '-';

    N = -N;
  }

  return this->operator<<(static_cast<unsigned long long>(N));
}

raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
  if (OutBufCur+Size > OutBufEnd)
    flush_impl();

  // Handle short strings specially, memcpy isn't very good at very short
  // strings.
  switch (Size) {
  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
  case 0: break;
  default:
    // Normally the string to emit is shorter than the buffer.
    if (Size <= unsigned(OutBufEnd-OutBufStart)) {
      memcpy(OutBufCur, Ptr, Size);
      break;
    }

    // If emitting a string larger than our buffer, emit in chunks.  In this
    // case we know that we just flushed the buffer.
    while (Size) {
      unsigned NumToEmit = OutBufEnd-OutBufStart;
      if (Size < NumToEmit) NumToEmit = Size;
      assert(OutBufCur == OutBufStart);
      memcpy(OutBufStart, Ptr, NumToEmit);
      Ptr += NumToEmit;
      Size -= NumToEmit;
      OutBufCur = OutBufStart + NumToEmit;
      flush_impl();
    }
    break;
  }
  OutBufCur += Size;
  return *this;
}

//===----------------------------------------------------------------------===//
//  raw_fd_ostream
//===----------------------------------------------------------------------===//

/// raw_fd_ostream - Open the specified file for writing.  If an error occurs,
/// information about the error is put into ErrorInfo, and the stream should
/// be immediately destroyed.
raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo) {
  // Handle "-" as stdout.
  if (Filename[0] == '-' && Filename[1] == 0) {
    FD = STDOUT_FILENO;
    ShouldClose = false;
    return;
  }

  FD = open(Filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
  if (FD < 0) {
    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
    ShouldClose = false;
  } else {
    ShouldClose = true;
  }
}

raw_fd_ostream::~raw_fd_ostream() {
  flush();
  if (ShouldClose)
    close(FD);
}

void raw_fd_ostream::flush_impl() {
  if (OutBufCur-OutBufStart)
    ::write(FD, OutBufStart, OutBufCur-OutBufStart);
  HandleFlush();
}

//===----------------------------------------------------------------------===//
//  raw_stdout/err_ostream
//===----------------------------------------------------------------------===//

raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false) {}

// An out of line virtual method to provide a home for the class vtable.
void raw_stdout_ostream::handle() {}
void raw_stderr_ostream::handle() {}

/// outs() - This returns a reference to a raw_ostream for standard output.
/// Use it like: outs() << "foo" << "bar";
raw_ostream &llvm::outs() {
  static raw_stdout_ostream S;
  return S;
}

/// errs() - This returns a reference to a raw_ostream for standard error.
/// Use it like: errs() << "foo" << "bar";
raw_ostream &llvm::errs() {
  static raw_stderr_ostream S;
  return S;
}

//===----------------------------------------------------------------------===//
//  raw_os_ostream
//===----------------------------------------------------------------------===//

/// flush_impl - The is the piece of the class that is implemented by
/// subclasses.  This outputs the currently buffered data and resets the
/// buffer to empty.
void raw_os_ostream::flush_impl() {
  if (OutBufCur-OutBufStart)
    OS.write(OutBufStart, OutBufCur-OutBufStart);
  HandleFlush();
}
<commit_msg>improve support for systems that need unistd.h to get STDOUT_FILENO. Patch contributed by Bjorn Reese!<commit_after>//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements support for bulk buffered stream output.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/raw_ostream.h"
#include "llvm/Config/config.h"
#include <ostream>

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif

#if defined(_MSC_VER)
#include <io.h>
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

using namespace llvm;

// An out of line virtual method to provide a home for the class vtable.
void raw_ostream::handle() {}

raw_ostream &raw_ostream::operator<<(unsigned long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long N) {
  if (N <  0) {
    if (OutBufCur >= OutBufEnd)
      flush_impl();
    *OutBufCur++ = '-';

    N = -N;
  }

  return this->operator<<(static_cast<unsigned long>(N));
}

raw_ostream &raw_ostream::operator<<(unsigned long long N) {
  // Zero is a special case.
  if (N == 0)
    return *this << '0';

  char NumberBuffer[20];
  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
  char *CurPtr = EndPtr;

  while (N) {
    *--CurPtr = '0' + char(N % 10);
    N /= 10;
  }
  return write(CurPtr, EndPtr-CurPtr);
}

raw_ostream &raw_ostream::operator<<(long long N) {
  if (N <  0) {
    if (OutBufCur >= OutBufEnd)
      flush_impl();
    *OutBufCur++ = '-';

    N = -N;
  }

  return this->operator<<(static_cast<unsigned long long>(N));
}

raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
  if (OutBufCur+Size > OutBufEnd)
    flush_impl();

  // Handle short strings specially, memcpy isn't very good at very short
  // strings.
  switch (Size) {
  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
  case 0: break;
  default:
    // Normally the string to emit is shorter than the buffer.
    if (Size <= unsigned(OutBufEnd-OutBufStart)) {
      memcpy(OutBufCur, Ptr, Size);
      break;
    }

    // If emitting a string larger than our buffer, emit in chunks.  In this
    // case we know that we just flushed the buffer.
    while (Size) {
      unsigned NumToEmit = OutBufEnd-OutBufStart;
      if (Size < NumToEmit) NumToEmit = Size;
      assert(OutBufCur == OutBufStart);
      memcpy(OutBufStart, Ptr, NumToEmit);
      Ptr += NumToEmit;
      Size -= NumToEmit;
      OutBufCur = OutBufStart + NumToEmit;
      flush_impl();
    }
    break;
  }
  OutBufCur += Size;
  return *this;
}

//===----------------------------------------------------------------------===//
//  raw_fd_ostream
//===----------------------------------------------------------------------===//

/// raw_fd_ostream - Open the specified file for writing.  If an error occurs,
/// information about the error is put into ErrorInfo, and the stream should
/// be immediately destroyed.
raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo) {
  // Handle "-" as stdout.
  if (Filename[0] == '-' && Filename[1] == 0) {
    FD = STDOUT_FILENO;
    ShouldClose = false;
    return;
  }

  FD = open(Filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
  if (FD < 0) {
    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
    ShouldClose = false;
  } else {
    ShouldClose = true;
  }
}

raw_fd_ostream::~raw_fd_ostream() {
  flush();
  if (ShouldClose)
    close(FD);
}

void raw_fd_ostream::flush_impl() {
  if (OutBufCur-OutBufStart)
    ::write(FD, OutBufStart, OutBufCur-OutBufStart);
  HandleFlush();
}

//===----------------------------------------------------------------------===//
//  raw_stdout/err_ostream
//===----------------------------------------------------------------------===//

raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false) {}

// An out of line virtual method to provide a home for the class vtable.
void raw_stdout_ostream::handle() {}
void raw_stderr_ostream::handle() {}

/// outs() - This returns a reference to a raw_ostream for standard output.
/// Use it like: outs() << "foo" << "bar";
raw_ostream &llvm::outs() {
  static raw_stdout_ostream S;
  return S;
}

/// errs() - This returns a reference to a raw_ostream for standard error.
/// Use it like: errs() << "foo" << "bar";
raw_ostream &llvm::errs() {
  static raw_stderr_ostream S;
  return S;
}

//===----------------------------------------------------------------------===//
//  raw_os_ostream
//===----------------------------------------------------------------------===//

/// flush_impl - The is the piece of the class that is implemented by
/// subclasses.  This outputs the currently buffered data and resets the
/// buffer to empty.
void raw_os_ostream::flush_impl() {
  if (OutBufCur-OutBufStart)
    OS.write(OutBufStart, OutBufCur-OutBufStart);
  HandleFlush();
}
<|endoftext|>


<commit_before>/*
 *   Copyright 2012 Coherent Theory LLC
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Library General Public License as
 *   published by the Free Software Foundation; either version 2, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "assethandler.h"

#include <QDebug>
#include <QDir>
#include <QLibraryInfo>
#include <QPluginLoader>

#include "installjob.h"

namespace Bodega
{

class AssetHandler::Private
{
public:
    Private()
        : ops(0)
    {
    }

    AssetOperations *ops;
};

AssetHandler::AssetHandler(QObject *parent)
    : QObject(parent),
      d(new Private)
{
}

AssetHandler::~AssetHandler()
{
    delete d;
}

void AssetHandler::setOperations(AssetOperations *operations)
{
    d->ops = operations;
}

AssetOperations *AssetHandler::operations() const
{
    return d->ops;
}

QString AssetHandler::launchText() const
{
    return QString();
}

bool AssetHandler::isInstalled() const
{
    return false;
}

Bodega::InstallJob *AssetHandler::install(QNetworkReply *reply, Session *session)
{
    return new InstallJob(reply, session);
}

Bodega::UninstallJob *AssetHandler::uninstall()
{
    //return new UninstallJob();
    return 0;
}

AssetHandler *AssetHandler::create(const QString &type, AssetOperations *parent)
{
    QString plugin;
    //FIXME: a better registration system is badly needed
    if (type == QLatin1String("application/epub+zip") ||
        type == QLatin1String("application/pdf")) {
        plugin = QLatin1String("epub");
    } else if (type == QLatin1String("application/x-plasma")) {
        plugin = QLatin1String("plasmoid");
    } else if (type == QLatin1String("application/x-desktop-wallpaper")) {
        plugin = QLatin1String("wallpaper");
    }

    AssetHandler * handler = 0;

    if (!plugin.isEmpty()) {
        QDir pluginsDir(QLibraryInfo::location(QLibraryInfo::PluginsPath) + QLatin1String("/bodegaassethandlers/"));
        const QString path = pluginsDir.absoluteFilePath(QLatin1String("lib") + plugin + QLatin1String("handlerplugin"));
        QPluginLoader pluginLoader(path);

        QObject *plugin = pluginLoader.instance();
        if (plugin) {
            handler = qobject_cast<Bodega::AssetHandler *>(plugin);
        } else {
            qWarning() << "Plugin load failed" << pluginLoader.errorString();
        }

        if (!handler) {
            delete plugin;
        }
    }

    if (!handler) {
        handler = new AssetHandler;
    }

    handler->setParent(parent);
    handler->setOperations(parent);
    return handler;
}

void AssetHandler::launch()
{
}

} // namespace Bodega

#include "assethandler.moc"

<commit_msg>.so is indeed necessary. sucks<commit_after>/*
 *   Copyright 2012 Coherent Theory LLC
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Library General Public License as
 *   published by the Free Software Foundation; either version 2, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "assethandler.h"

#include <QDebug>
#include <QDir>
#include <QLibraryInfo>
#include <QPluginLoader>

#include "installjob.h"

namespace Bodega
{

class AssetHandler::Private
{
public:
    Private()
        : ops(0)
    {
    }

    AssetOperations *ops;
};

AssetHandler::AssetHandler(QObject *parent)
    : QObject(parent),
      d(new Private)
{
}

AssetHandler::~AssetHandler()
{
    delete d;
}

void AssetHandler::setOperations(AssetOperations *operations)
{
    d->ops = operations;
}

AssetOperations *AssetHandler::operations() const
{
    return d->ops;
}

QString AssetHandler::launchText() const
{
    return QString();
}

bool AssetHandler::isInstalled() const
{
    return false;
}

Bodega::InstallJob *AssetHandler::install(QNetworkReply *reply, Session *session)
{
    return new InstallJob(reply, session);
}

Bodega::UninstallJob *AssetHandler::uninstall()
{
    //return new UninstallJob();
    return 0;
}

AssetHandler *AssetHandler::create(const QString &type, AssetOperations *parent)
{
    QString plugin;
    //FIXME: a better registration system is badly needed
    if (type == QLatin1String("application/epub+zip") ||
        type == QLatin1String("application/pdf")) {
        plugin = QLatin1String("epub");
    } else if (type == QLatin1String("application/x-plasma")) {
        plugin = QLatin1String("plasmoid");
    } else if (type == QLatin1String("application/x-desktop-wallpaper")) {
        plugin = QLatin1String("wallpaper");
    }

    AssetHandler * handler = 0;

    if (!plugin.isEmpty()) {
        QDir pluginsDir(QLibraryInfo::location(QLibraryInfo::PluginsPath) + QLatin1String("/bodegaassethandlers/"));
        //FIXME: the .so is non-portable. need some ifdef's here if this is to work on non-UNIX.
        //remind me why QPluginLoader doesn't do this when QLibrary does?
        const QString path = pluginsDir.absoluteFilePath(QLatin1String("lib") + plugin + QLatin1String("handlerplugin.so"));
        QPluginLoader pluginLoader(path);

        QObject *plugin = pluginLoader.instance();
        if (plugin) {
            handler = qobject_cast<Bodega::AssetHandler *>(plugin);
        } else {
            qWarning() << "Plugin load failed" << pluginLoader.errorString() << path;
        }

        if (!handler) {
            delete plugin;
        }
    }

    if (!handler) {
        handler = new AssetHandler;
    }

    handler->setParent(parent);
    handler->setOperations(parent);
    return handler;
}

void AssetHandler::launch()
{
}

} // namespace Bodega

#include "assethandler.moc"

<|endoftext|>


<commit_before>
#include <cstring>
#include <cassert>
#ifdef _WIN32
#include <windows.h>
#else
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

#include "File.h"
#include "String.h"

File::File()
{
#ifdef _WIN32
  assert(sizeof(void*) >= sizeof(HANDLE));
  fp = INVALID_HANDLE_VALUE;
#else
  fp = 0;
#endif
}

File::~File()
{
  close();
}

void File::close()
{
#ifdef _WIN32
  if(fp != INVALID_HANDLE_VALUE)
  {
    CloseHandle((HANDLE)fp);
    fp = INVALID_HANDLE_VALUE;
  }
#else
  if(fp)
  {
    fclose((FILE*)fp);
    fp = 0;
  }
#endif
}

bool File::unlink(const String& file)
{
#ifdef _WIN32
  if(!DeleteFile(file.getData()))
  {
    error = GetLastError();
    return false;
  }
#else
  if(::unlink(file.getData()) != 0)
  {
    error = errno;
    return false;
  }
#endif
  return true;
}

bool File::open(const String& file, Flags flags)
{
#ifdef _WIN32
  if(fp != INVALID_HANDLE_VALUE)
    return false;
  DWORD desiredAccess = 0, creationDisposition = 0;
  if(flags & writeFlag)
  {
    desiredAccess |= GENERIC_WRITE;
    creationDisposition |= CREATE_ALWAYS;
  }
  if(flags & readFlag)
  {
    desiredAccess |= GENERIC_READ;
    if(!(flags & writeFlag))
      creationDisposition |= OPEN_EXISTING;
  }
  fp = CreateFileA(file.getData(), desiredAccess, FILE_SHARE_READ, NULL, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  if(fp == INVALID_HANDLE_VALUE)
  {
    error = GetLastError();
    return false;
  }
#else
  if(fp)
    return false;
  const char* mode = flags & (writeFlag | readFlag) == (writeFlag | readFlag) ? "w+" : (flags & writeFlag ? "w" : "r");
  fp = fopen(file.getData(), mode);
  if(!fp)
  {
    error = errno;
    return false;
  }
#endif

  return true;
}

int File::read(char* buffer, int len)
{
#ifdef _WIN32
  DWORD i;
  if(!ReadFile((HANDLE)fp, buffer, len, &i, NULL))
  {
    error = GetLastError();
    return 0;
  }
  return i;
#else
  size_t i = fread(buffer, 1, len, (FILE*)fp);
  if(i == 0)
  {
    error = errno;
    return 0;
  }
  return (int)i;
#endif
}

int File::write(const char* buffer, int len)
{
#ifdef _WIN32
  DWORD i;
  if(!WriteFile((HANDLE)fp, buffer, len, &i, NULL))
  {
    error = GetLastError();
    return 0;
  }
  if(i != len)
  {
    error = GetLastError();
    return i;
  }
  return i;
#else
  size_t i = fwrite(buffer, 1, len, (FILE*)fp);
  if(i != len)
  {
    error = errno;
    return (int)i;
  }
  return (int)i;
#endif
}

bool File::write(const String& data)
{
  return write(data.getData(), data.getLength()) == data.getLength();
}

String File::getDirname(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '\\' || *pos == '/')
      return file.substr(0, pos - start);
  return String(".");
}

String File::getBasename(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '\\' || *pos == '/')
      return file.substr(pos - start + 1);
  return file;
}

String File::getExtension(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '.')
      return file.substr(pos - start + 1);
    else if(*pos == '\\' || *pos == '/')
      return String();
  return String();
}

String File::getWithoutExtension(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '.')
      return file.substr(0, pos - start);
    else if(*pos == '\\' || *pos == '/')
      return String();
  return String();
}

bool File::getWriteTime(const String& file, long long& writeTime)
{
#ifdef _WIN32
  WIN32_FIND_DATAA wfd;
  HANDLE hFind = FindFirstFileA(file.getData(), &wfd);
  if(hFind == INVALID_HANDLE_VALUE)
    return false;
  assert(sizeof(DWORD) == 4);
  writeTime = ((long long)wfd.ftLastWriteTime.dwHighDateTime) << 32LL | ((long long)wfd.ftLastWriteTime.dwLowDateTime);
  FindClose(hFind);
  return true;
#else
  struct stat buf;
  if(stat(file.getData(), &buf) != 0)
    return false;
  return buf.st_mtime;
#endif
}

bool File::exists(const String& file)
{
#ifdef _WIN32
  WIN32_FIND_DATAA wfd;
  HANDLE hFind = FindFirstFileA(file.getData(), &wfd);
  if(hFind == INVALID_HANDLE_VALUE)
    return false;
  //bool isDir = (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY;
  FindClose(hFind);
  //return isDir;
  return true;
#else
  struct stat buf;
  if(lstat(file.getData(), &buf) != 0)
    return false;
  return true;
#endif
}

<commit_msg>Fix file mode bug in posix implementation of File::open<commit_after>
#include <cstring>
#include <cassert>
#ifdef _WIN32
#include <windows.h>
#else
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

#include "File.h"
#include "String.h"

File::File()
{
#ifdef _WIN32
  assert(sizeof(void*) >= sizeof(HANDLE));
  fp = INVALID_HANDLE_VALUE;
#else
  fp = 0;
#endif
}

File::~File()
{
  close();
}

void File::close()
{
#ifdef _WIN32
  if(fp != INVALID_HANDLE_VALUE)
  {
    CloseHandle((HANDLE)fp);
    fp = INVALID_HANDLE_VALUE;
  }
#else
  if(fp)
  {
    fclose((FILE*)fp);
    fp = 0;
  }
#endif
}

bool File::unlink(const String& file)
{
#ifdef _WIN32
  if(!DeleteFile(file.getData()))
  {
    error = GetLastError();
    return false;
  }
#else
  if(::unlink(file.getData()) != 0)
  {
    error = errno;
    return false;
  }
#endif
  return true;
}

bool File::open(const String& file, Flags flags)
{
#ifdef _WIN32
  if(fp != INVALID_HANDLE_VALUE)
    return false;
  DWORD desiredAccess = 0, creationDisposition = 0;
  if(flags & writeFlag)
  {
    desiredAccess |= GENERIC_WRITE;
    creationDisposition |= CREATE_ALWAYS;
  }
  if(flags & readFlag)
  {
    desiredAccess |= GENERIC_READ;
    if(!(flags & writeFlag))
      creationDisposition |= OPEN_EXISTING;
  }
  fp = CreateFileA(file.getData(), desiredAccess, FILE_SHARE_READ, NULL, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  if(fp == INVALID_HANDLE_VALUE)
  {
    error = GetLastError();
    return false;
  }
#else
  if(fp)
    return false;
  const char* mode = (flags & (writeFlag | readFlag)) == (writeFlag | readFlag) ? "w+" : (flags & writeFlag ? "w" : "r");
  fp = fopen(file.getData(), mode);
  if(!fp)
  {
    error = errno;
    return false;
  }
#endif

  return true;
}

int File::read(char* buffer, int len)
{
#ifdef _WIN32
  DWORD i;
  if(!ReadFile((HANDLE)fp, buffer, len, &i, NULL))
  {
    error = GetLastError();
    return 0;
  }
  return i;
#else
  size_t i = fread(buffer, 1, len, (FILE*)fp);
  if(i == 0)
  {
    error = errno;
    return 0;
  }
  return (int)i;
#endif
}

int File::write(const char* buffer, int len)
{
#ifdef _WIN32
  DWORD i;
  if(!WriteFile((HANDLE)fp, buffer, len, &i, NULL))
  {
    error = GetLastError();
    return 0;
  }
  if(i != len)
  {
    error = GetLastError();
    return i;
  }
  return i;
#else
  size_t i = fwrite(buffer, 1, len, (FILE*)fp);
  if(i != len)
  {
    error = errno;
    return (int)i;
  }
  return (int)i;
#endif
}

bool File::write(const String& data)
{
  return write(data.getData(), data.getLength()) == data.getLength();
}

String File::getDirname(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '\\' || *pos == '/')
      return file.substr(0, pos - start);
  return String(".");
}

String File::getBasename(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '\\' || *pos == '/')
      return file.substr(pos - start + 1);
  return file;
}

String File::getExtension(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '.')
      return file.substr(pos - start + 1);
    else if(*pos == '\\' || *pos == '/')
      return String();
  return String();
}

String File::getWithoutExtension(const String& file)
{
  const char* start = file.getData();
  const char* pos = &start[file.getLength() - 1];
  for(; pos >= start; --pos)
    if(*pos == '.')
      return file.substr(0, pos - start);
    else if(*pos == '\\' || *pos == '/')
      return String();
  return String();
}

bool File::getWriteTime(const String& file, long long& writeTime)
{
#ifdef _WIN32
  WIN32_FIND_DATAA wfd;
  HANDLE hFind = FindFirstFileA(file.getData(), &wfd);
  if(hFind == INVALID_HANDLE_VALUE)
    return false;
  assert(sizeof(DWORD) == 4);
  writeTime = ((long long)wfd.ftLastWriteTime.dwHighDateTime) << 32LL | ((long long)wfd.ftLastWriteTime.dwLowDateTime);
  FindClose(hFind);
  return true;
#else
  struct stat buf;
  if(stat(file.getData(), &buf) != 0)
    return false;
  return buf.st_mtime;
#endif
}

bool File::exists(const String& file)
{
#ifdef _WIN32
  WIN32_FIND_DATAA wfd;
  HANDLE hFind = FindFirstFileA(file.getData(), &wfd);
  if(hFind == INVALID_HANDLE_VALUE)
    return false;
  //bool isDir = (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY;
  FindClose(hFind);
  //return isDir;
  return true;
#else
  struct stat buf;
  if(lstat(file.getData(), &buf) != 0)
    return false;
  return true;
#endif
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandeglwindow.h"

#include "qwaylandscreen.h"
#include "qwaylandglcontext.h"

#include <QtPlatformSupport/private/qeglconvenience_p.h>

#include <QtGui/QWindow>
#include <QtGui/QWindowSystemInterface>

QWaylandEglWindow::QWaylandEglWindow(QWindow *window)
    : QWaylandWindow(window)
    , m_waylandEglWindow(0)
    , m_eglSurface(0)
    , m_eglConfig(0)
    , m_format(window->format())
{
    m_eglIntegration = static_cast<QWaylandEglIntegration *>(mDisplay->eglIntegration());

    //super creates a new surface
    newSurfaceCreated();
}

QWaylandEglWindow::~QWaylandEglWindow()
{
    if (m_eglSurface) {
        eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
        m_eglSurface = 0;
    }
}

QWaylandWindow::WindowType QWaylandEglWindow::windowType() const
{
    return QWaylandWindow::Egl;
}

void QWaylandEglWindow::setGeometry(const QRect &rect)
{
    QWaylandWindow::setGeometry(rect);
    if (m_waylandEglWindow){
        wl_egl_window_resize(m_waylandEglWindow, rect.width(), rect.height(), 0, 0);
        QWindowSystemInterface::handleGeometryChange(window(), rect);
    }
}

void QWaylandEglWindow::newSurfaceCreated()
{
    if (m_waylandEglWindow)
        wl_egl_window_destroy(m_waylandEglWindow);

    wl_visual *visual = QWaylandScreen::waylandScreenFromWindow(window())->visual();
    QSize size = geometry().size();
    if (!size.isValid())
        size = QSize(0,0);

    if (m_eglSurface) {
        eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
        m_eglSurface = 0;
    }

    m_waylandEglWindow = wl_egl_window_create(mSurface, size.width(), size.height(), visual);
}

QSurfaceFormat QWaylandEglWindow::format() const
{
    return m_format;
}

EGLSurface QWaylandEglWindow::eglSurface() const
{
    if (!m_waylandEglWindow)
        return 0;

    if (!m_eglSurface) {
        if (!m_eglConfig)
            m_eglConfig = q_configFromGLFormat(m_eglIntegration->eglDisplay(), window()->format(), true);

        EGLNativeWindowType window = m_waylandEglWindow;
        m_eglSurface = eglCreateWindowSurface(m_eglIntegration->eglDisplay(), m_eglConfig, window, 0);
    }

    return m_eglSurface;
}

<commit_msg>Flush window property changes also with EGL surfaces<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandeglwindow.h"

#include "qwaylandscreen.h"
#include "qwaylandglcontext.h"

#include <QtPlatformSupport/private/qeglconvenience_p.h>

#include <QtGui/QWindow>
#include <QtGui/QWindowSystemInterface>

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif

QWaylandEglWindow::QWaylandEglWindow(QWindow *window)
    : QWaylandWindow(window)
    , m_waylandEglWindow(0)
    , m_eglSurface(0)
    , m_eglConfig(0)
    , m_format(window->format())
{
    m_eglIntegration = static_cast<QWaylandEglIntegration *>(mDisplay->eglIntegration());

    //super creates a new surface
    newSurfaceCreated();
}

QWaylandEglWindow::~QWaylandEglWindow()
{
    if (m_eglSurface) {
        eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
        m_eglSurface = 0;
    }
}

QWaylandWindow::WindowType QWaylandEglWindow::windowType() const
{
    return QWaylandWindow::Egl;
}

void QWaylandEglWindow::setGeometry(const QRect &rect)
{
    QWaylandWindow::setGeometry(rect);
    if (m_waylandEglWindow){
        wl_egl_window_resize(m_waylandEglWindow, rect.width(), rect.height(), 0, 0);
        QWindowSystemInterface::handleGeometryChange(window(), rect);
    }
}

void QWaylandEglWindow::newSurfaceCreated()
{
    if (m_waylandEglWindow)
        wl_egl_window_destroy(m_waylandEglWindow);

    wl_visual *visual = QWaylandScreen::waylandScreenFromWindow(window())->visual();
    QSize size = geometry().size();
    if (!size.isValid())
        size = QSize(0,0);

    if (m_eglSurface) {
        eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
        m_eglSurface = 0;
    }

    m_waylandEglWindow = wl_egl_window_create(mSurface, size.width(), size.height(), visual);

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    QWaylandWindowManagerIntegration::instance()->flushPropertyChanges(this);
#endif
}

QSurfaceFormat QWaylandEglWindow::format() const
{
    return m_format;
}

EGLSurface QWaylandEglWindow::eglSurface() const
{
    if (!m_waylandEglWindow)
        return 0;

    if (!m_eglSurface) {
        if (!m_eglConfig)
            m_eglConfig = q_configFromGLFormat(m_eglIntegration->eglDisplay(), window()->format(), true);

        EGLNativeWindowType window = m_waylandEglWindow;
        m_eglSurface = eglCreateWindowSurface(m_eglIntegration->eglDisplay(), m_eglConfig, window, 0);
    }

    return m_eglSurface;
}

<|endoftext|>


<commit_before><commit_msg>GTK theming plugin: convert big if statement to switch structure<commit_after><|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03, c++11, c++14
// <optional>

// constexpr optional(const optional<T>&& rhs);
//   If is_trivially_move_constructible_v<T> is true,
//    this constructor shall be a constexpr constructor.

#include <optional>
#include <type_traits>
#include <cassert>

#include "test_macros.h"

struct S {
    constexpr S()   : v_(0) {}
    S(int v)        : v_(v) {}
    constexpr S(const S  &rhs) : v_(rhs.v_) {} // not trivially moveable
    constexpr S(const S &&rhs) : v_(rhs.v_) {} // not trivially moveable
    int v_;
    };

int main(int, char**)
{
    static_assert (!std::is_trivially_move_constructible_v<S>, "" );
    constexpr std::optional<S> o1;
    constexpr std::optional<S> o2 = std::move(o1);  // not constexpr

  return 0;
}
<commit_msg>Update test to better check for the non-constexpr-ness of a move constructor. Fixes PR#41577.<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03, c++11, c++14
// <optional>

// constexpr optional(const optional<T>&& rhs);
//  C++17 said:
//   If is_trivially_move_constructible_v<T> is true,
//    this constructor shall be a constexpr constructor.
//
//  P0602 changed this to:
//     If is_trivially_move_constructible_v<T> is true, this constructor is trivial.
//
//  which means that it can't be constexpr if T is not trivially move-constructible,
//    because you have to do a placement new to get the value into place.
//    Except in the case where it is moving from an empty optional - that could be
//    made to be constexpr (and libstdc++ does so).

#include <optional>
#include <type_traits>
#include <cassert>

#include "test_macros.h"

struct S {
    constexpr S()   : v_(0) {}
    S(int v)        : v_(v) {}
    constexpr S(const S  &rhs) : v_(rhs.v_) {} // not trivially moveable
    constexpr S(      S &&rhs) : v_(rhs.v_) {} // not trivially moveable
    int v_;
    };

constexpr bool test() // expected-error {{constexpr function never produces a constant expression}}
{
    std::optional<S> o1{3};
    std::optional<S> o2 = std::move(o1);
    return o2.has_value();  // return -something-
}

int main(int, char**)
{
    static_assert (!std::is_trivially_move_constructible_v<S>, "" );
    static_assert (test(), "");  // expected-error {{static_assert expression is not an integral constant expression}}
    return 0;
}
<|endoftext|>


<commit_before>#include "aerial_autonomy/tests/qrotor_backstepping_controller_connector_tests.h"
#include <gtest/gtest.h>

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbPos) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 5;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << .1, .1, 0, 0, 0, 0;
  tf::Vector3 pos_err(.05, .05, .05);
  tf::Vector3 vel_err(0, 0, 0);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbVel) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 5;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << .1, .1, 0, 0, 0, 0;
  tf::Vector3 pos_err(0, 0, 0);
  tf::Vector3 vel_err(.05, .05, .05);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbPosVel) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 5;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << .1, .1, 0, 0, 0, 0;
  tf::Vector3 pos_err(.05, .05, .05);
  tf::Vector3 vel_err(.05, .05, .05);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Add test when control is out of bounds<commit_after>#include "aerial_autonomy/tests/qrotor_backstepping_controller_connector_tests.h"
#include <gtest/gtest.h>

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbPos) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 3;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << 1, 1, 0, 0, 0, 0;
  tf::Vector3 pos_err(.05, .05, .05);
  tf::Vector3 vel_err(0, 0, 0);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbVel) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 3;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << 1, 1, 0, 0, 0, 0;
  tf::Vector3 pos_err(0, 0, 0);
  tf::Vector3 vel_err(.05, .05, .05);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

TEST_F(QrotorBacksteppingControllerConnectorTests, InitialDisturbPosVel) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 3;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << 1, 1, 0, 0, 0, 0;
  tf::Vector3 pos_err(.05, .05, .05);
  tf::Vector3 vel_err(.05, .05, .05);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilConvergence(goal, total_time, pos_err, vel_err);
}

TEST_F(QrotorBacksteppingControllerConnectorTests, OutOfBounds) {
  int r = 4;
  Eigen::VectorXd tau_vec(1);
  tau_vec << 6;
  double total_time = tau_vec.sum();
  Eigen::MatrixXd path(2, 3);
  path << 0, 0, 0, 3, 3, 0;
  tf::Vector3 pos_err(0, 0, -5);
  tf::Vector3 vel_err(0, 0, 3);
  std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
      new MinimumSnapReferenceTrajectory(r, tau_vec, path));
  runUntilOutOfBounds(goal, total_time, pos_err, vel_err);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>