<commit_before>#include <cassert>
#include <iostream>
#include <list>
#include <utility>
#include <string>

#include "service.h"
#include "proc-service.h"

// Tests of process-service related functionality.
//
// These tests work mostly by completely mocking out the base_process_service class. The mock
// implementations can be found in test-baseproc.cc.

// Friend interface to access base_process_service private/protected members.
class base_process_service_test
{
    public:
    static void exec_succeeded(base_process_service *bsp)
    {
        bsp->exec_succeeded();
    }

    static void handle_exit(base_process_service *bsp, int exit_status)
    {
        bsp->handle_exit_status(exit_status);
    }
};

// Regular service start
void test1()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTING);

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);
}

// Unexpected termination
void test2()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

// Termination via stop request
void test3()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);

    p.stop(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPING);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

// Time-out during start
void test4()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTING);

    p.timer_expired();
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPING);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

#define RUN_TEST(name) \
    std::cout << #name "... "; \
    name(); \
    std::cout << "PASSED" << std::endl;

int main(int argc, char **argv)
{
    RUN_TEST(test1);
    RUN_TEST(test2);
    RUN_TEST(test3);
    RUN_TEST(test4);
}
<commit_msg>Add a proc test, and name each test.<commit_after>#include <cassert>
#include <iostream>
#include <list>
#include <utility>
#include <string>

#include "service.h"
#include "proc-service.h"

// Tests of process-service related functionality.
//
// These tests work mostly by completely mocking out the base_process_service class. The mock
// implementations can be found in test-baseproc.cc.

// Friend interface to access base_process_service private/protected members.
class base_process_service_test
{
    public:
    static void exec_succeeded(base_process_service *bsp)
    {
        bsp->exec_succeeded();
    }

    static void handle_exit(base_process_service *bsp, int exit_status)
    {
        bsp->handle_exit_status(exit_status);
    }
};

// Regular service start
void test_proc_service_start()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTING);

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);
}

// Unexpected termination
void test_proc_unexpected_term()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

// Termination via stop request
void test_term_via_stop()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);

    p.stop(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPING);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

// Time-out during start
void test_proc_start_timeout()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.start(true);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTING);

    p.timer_expired();
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPING);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STOPPED);
}

// Smooth recovery
void test_proc_smooth_recovery()
{
    using namespace std;

    service_set sset;

    string command = "test-command";
    list<pair<unsigned,unsigned>> command_offsets;
    command_offsets.emplace_back(0, command.length());
    std::list<prelim_dep> depends;

    process_service p = process_service(&sset, "testproc", std::move(command), command_offsets, depends);
    p.set_smooth_recovery(true);

    p.start(true);
    sset.process_queues();

    base_process_service_test::exec_succeeded(&p);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);

    base_process_service_test::handle_exit(&p, 0);
    sset.process_queues();

    assert(p.get_state() == service_state_t::STARTED);
}

#define RUN_TEST(name, spacing) \
    std::cout << #name "..." spacing; \
    name(); \
    std::cout << "PASSED" << std::endl;

int main(int argc, char **argv)
{
    RUN_TEST(test_proc_service_start, "   ");
    RUN_TEST(test_proc_unexpected_term, " ");
    RUN_TEST(test_term_via_stop, "        ");
    RUN_TEST(test_proc_start_timeout, "   ");
    RUN_TEST(test_proc_smooth_recovery, " ");
}
<|endoftext|>


<commit_before><commit_msg>`save_data_from_gpu_texture_into_file`: convert `format` to base format.<commit_after><|endoftext|>


<commit_before>/*!
 * \copy
 *     Copyright (c)  2009-2013, Cisco Systems
 *     All rights reserved.
 *
 *     Redistribution and use in source and binary forms, with or without
 *     modification, are permitted provided that the following conditions
 *     are met:
 *
 *        * Redistributions of source code must retain the above copyright
 *          notice, this list of conditions and the following disclaimer.
 *
 *        * Redistributions in binary form must reproduce the above copyright
 *          notice, this list of conditions and the following disclaimer in
 *          the documentation and/or other materials provided with the
 *          distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *     COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *     BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *     ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *     POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * \file	crt_utils_safe_x.cpp
 *
 * \brief	common tool/function utilization
 *
 * \date	03/10/2009 Created
 *
 *************************************************************************************
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#include <sys/types.h>
#include <sys/timeb.h>
#ifndef _MSC_VER
#include <sys/time.h>
#ifndef HAVE_STRNLEN
#define strnlen(a,b) strlen(a)
#endif //!HAVE_STRNLEN
#endif //!_MSC_VER
#else
#include <sys/time.h>
#include <sys/timeb.h>
#endif //_WIN32

#include "macros.h"
#include "crt_util_safe_x.h"	// Safe CRT routines like utils for cross platforms

#if  defined(_WIN32) && defined(_MSC_VER)

#if  defined(_MSC_VER) && (_MSC_VER>=1500)

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list  pArgPtr;
  int32_t  iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen_s (kpStr, iMaxlen);
}

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  WelsFileHandle* pFp = NULL;
  if (fopen_s (&pFp, kpFilename, kpMode) != 0) {
    return NULL;
  }

  return pFp;
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  return _ftime_s (pTp);
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm   sTimeNow;

  localtime_s (&sTimeNow, &kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, &sTimeNow);
}

#else

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strlen (kpStr); //confirmed_safe_unsafe_usage
}

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  _ftime (pTp);
  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif // _MSC_VER

#else  //GCC

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  return strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage
}

#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)
int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen (kpStr, iMaxlen); //confirmed_safe_unsafe_usage
}
#else
int32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {
  // In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or
  // implement strnlen by ourself

#if 1
  return strlen (kpString); //confirmed_safe_unsafe_usage
#else
  const str_t* kpSrc;
  for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\0'; ++kpSrc)
    return kpSrc - kpString;
#endif

}
#endif

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle*   pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  struct timeval  sTv;

  if (gettimeofday (&sTv, NULL)) {
    return -1;
  }

  pTp->time = sTv.tv_sec;
  pTp->millitm = (uint16_t)sTv.tv_usec / 1000;

  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif

int32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {
  return fwrite (kpBuffer, iSize, iCount, pFp);
}

uint16_t WelsGetMillsecond (const SWelsTime* kpTp) {
  return kpTp->millitm;
}

int32_t WelsFflush (WelsFileHandle* pFp) {
  return fflush (pFp);
}
<commit_msg>Make sure the buffer always is null terminated in the *snprintf calls for old MSVC<commit_after>/*!
 * \copy
 *     Copyright (c)  2009-2013, Cisco Systems
 *     All rights reserved.
 *
 *     Redistribution and use in source and binary forms, with or without
 *     modification, are permitted provided that the following conditions
 *     are met:
 *
 *        * Redistributions of source code must retain the above copyright
 *          notice, this list of conditions and the following disclaimer.
 *
 *        * Redistributions in binary form must reproduce the above copyright
 *          notice, this list of conditions and the following disclaimer in
 *          the documentation and/or other materials provided with the
 *          distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *     COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *     BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *     ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *     POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * \file	crt_utils_safe_x.cpp
 *
 * \brief	common tool/function utilization
 *
 * \date	03/10/2009 Created
 *
 *************************************************************************************
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#include <sys/types.h>
#include <sys/timeb.h>
#ifndef _MSC_VER
#include <sys/time.h>
#ifndef HAVE_STRNLEN
#define strnlen(a,b) strlen(a)
#endif //!HAVE_STRNLEN
#endif //!_MSC_VER
#else
#include <sys/time.h>
#include <sys/timeb.h>
#endif //_WIN32

#include "macros.h"
#include "crt_util_safe_x.h"	// Safe CRT routines like utils for cross platforms

#if  defined(_WIN32) && defined(_MSC_VER)

#if  defined(_MSC_VER) && (_MSC_VER>=1500)

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list  pArgPtr;
  int32_t  iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen_s (kpStr, iMaxlen);
}

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  WelsFileHandle* pFp = NULL;
  if (fopen_s (&pFp, kpFilename, kpMode) != 0) {
    return NULL;
  }

  return pFp;
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  return _ftime_s (pTp);
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm   sTimeNow;

  localtime_s (&sTimeNow, &kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, &sTimeNow);
}

#else

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
  if (iRc < 0)
    pBuffer[iSizeOfBuffer - 1] = '\0';

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage

  return pDest;
}

int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strlen (kpStr); //confirmed_safe_unsafe_usage
}

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  int32_t iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
  if (iRc < 0)
    pBuffer[iSizeOfBuffer - 1] = '\0';
  return iRc;
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle* pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  _ftime (pTp);
  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif // _MSC_VER

#else  //GCC

int32_t WelsSnprintf (str_t* pBuffer,  int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {
  va_list pArgPtr;
  int32_t iRc;

  va_start (pArgPtr, kpFormat);

  iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);

  va_end (pArgPtr);

  return iRc;
}

str_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {
  return strncpy (pDest, kpSrc, iCount); //confirmed_safe_unsafe_usage
}

#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)
int32_t WelsStrnlen (const str_t* kpStr,  int32_t iMaxlen) {
  return strnlen (kpStr, iMaxlen); //confirmed_safe_unsafe_usage
}
#else
int32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {
  // In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or
  // implement strnlen by ourself

#if 1
  return strlen (kpString); //confirmed_safe_unsafe_usage
#else
  const str_t* kpSrc;
  for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\0'; ++kpSrc)
    return kpSrc - kpString;
#endif

}
#endif

int32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {
  return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); //confirmed_safe_unsafe_usage
}

WelsFileHandle* WelsFopen (const str_t* kpFilename,  const str_t* kpMode) {
  return fopen (kpFilename, kpMode);
}

int32_t WelsFclose (WelsFileHandle*   pFp) {
  return fclose (pFp);
}

int32_t WelsGetTimeOfDay (SWelsTime* pTp) {
  struct timeval  sTv;

  if (gettimeofday (&sTv, NULL)) {
    return -1;
  }

  pTp->time = sTv.tv_sec;
  pTp->millitm = (uint16_t)sTv.tv_usec / 1000;

  return 0;
}

int32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {
  struct tm*   pTnow;

  pTnow = localtime (&kpTp->time);

  return strftime (pBuffer, iSize, kpFormat, pTnow);
}

#endif

int32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {
  return fwrite (kpBuffer, iSize, iCount, pFp);
}

uint16_t WelsGetMillsecond (const SWelsTime* kpTp) {
  return kpTp->millitm;
}

int32_t WelsFflush (WelsFileHandle* pFp) {
  return fflush (pFp);
}
<|endoftext|>


<commit_before>#pragma once
/** @defgroup ImageRepresentation Image Representation
* @brief Storage, visualization and conversion of images
*
* Classes in this module are responsible for storing, displaying and converting image data
*/

#include "Widget.hpp"

#ifdef wxUSE_GUI
	#include <wx/image.h>
#endif

namespace xv
{

#ifdef wxUSE_GUI
	typedef wxImage gui_image_t;
#endif

/** @addtogroup ImageRepresentation */
/*@{*/

/** @brief An off-screen image representation native to the selected GUI
*/
class Image : public Widget
{

public:
	Image();
	virtual ~Image();
private:

	gui_image_t *m_guiImage;

	virtual void render(const cv::Mat&);

	/// Display widget in output mode (without OK/Cancel buttons)
	virtual void paint(const cv::Mat&);

	/// Check if point is inside the widget
	virtual bool contains(const cv::Point&);

	/// The user clicked the left mouse button over the widget
	virtual void onMouseDown(const cv::Point&);

	/// The user moved the mouse pointer over the widget
	virtual void onMouseMove(const cv::Point&);

	/// The user released the left mouse button over the widget
	virtual void onMouseUp(const cv::Point&);
};
/*@}*/
}
<commit_msg>Changed doxygen comment style.<commit_after>#pragma once
/** @defgroup ImageRepresentation Image Representation
* @brief Storage, visualization and conversion of images
*
* Classes in this module are responsible for storing, displaying and converting image data.
*/

#include "Widget.hpp"

#ifdef wxUSE_GUI
	#include <wx/image.h>
#endif

namespace xv
{

#ifdef wxUSE_GUI
	typedef wxImage gui_image_t;
#endif

/*!
 * \brief An off-screen image representation native to the selected GUI
 * \ingroup ImageRepresentation
 */
class Image : public Widget
{

public:
	Image();
	virtual ~Image();
private:

	gui_image_t *m_guiImage;

	virtual void render(const cv::Mat&);

	/// Display widget in output mode (without OK/Cancel buttons)
	virtual void paint(const cv::Mat&);

	/// Check if point is inside the widget
	virtual bool contains(const cv::Point&);

	/// The user clicked the left mouse button over the widget
	virtual void onMouseDown(const cv::Point&);

	/// The user moved the mouse pointer over the widget
	virtual void onMouseMove(const cv::Point&);

	/// The user released the left mouse button over the widget
	virtual void onMouseUp(const cv::Point&);
};
/*@}*/
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <exception>
#include    <malloc.h>

#include    "../Memory/Common.h"

#include    "MallocGuard.h"

using   namespace   Stroika::Foundation;
using   Memory::Byte;

#if     qStroika_Foundation_Debug_MallogGuard
namespace {
    using   GuradBytes_ =   Byte[16];
    constexpr   GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };
    constexpr   GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };

    // need header with size, so we can ....
    struct alignas(alignof(long double))  HeaderOrFooter_ {
        GuradBytes_ fGuard;
        size_t      fRequestedBlockSize;
    };

    void    OhShit_ ()
    {
        AssertNotReached ();
        std::terminate ();
    }

    void*   ExposedPtrToBackendPtr_ (void* p)
    {
        if (p == nullptr) {
            OhShit_ ();
        }
        return reinterpret_cast<const HeaderOrFooter_*> (p) - 1;
    }
    void*   BackendPtrToExposedPtr_ (void* p)
    {
        if (p == nullptr) {
            OhShit_ ();
        }
        return reinterpret_cast<const HeaderOrFooter_*> (p) + 1;
    }
    size_t  AdjustMallocSize_ (size_t s)
    {
        return s + 2 * sizeof (HeaderOrFooter_);
    }

    void    Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)
    {
        if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {
            OhShit_ ();
        }
        if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {
            OhShit_ ();
        }
        if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {
            OhShit_ ();
        }
        // OK
    }
    void    Validate_ (const void* p)
    {
        const HeaderOrFooter_*  h = reinterpret_cast<const HeaderOrFooter_*> (p) - 1;
        const HeaderOrFooter_*  fp  = reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (p) + h->fRequestedBlockSize);
        HeaderOrFooter_ footer;
        (void)::memcpy (&footer, fp, sizeof (footer));  // align access
        Validate_ (*h, footer);
    }
    // returns the pointer to use externally
    void*   PatchNewPointer_ (void* p, size_t requestedSize)
    {
        return p;
    }

    // todo variant that does pointer arithmatic
    // defines that contril how we handle failure (debug failure proc)?

}
#endif

#if     qStroika_Foundation_Debug_MallogGuard

extern "C"  void    __libc_free (void* __ptr);
extern "C"  void*   __libc_malloc (size_t __size);
extern "C"  void*   __libc_realloc (void* __ptr, size_t __size);
extern "C"  void*   __libc_calloc (size_t __nmemb, size_t __size);
extern "C"  void    __libc_free (void* __ptr);
extern "C"  size_t  __malloc_usable_size (void* __ptr);
/* Allocate SIZE bytes allocated to ALIGNMENT bytes.  */
extern "C"  void*   __libc_memalign (size_t __alignment, size_t __size);

#if 0
weak_alias (__malloc_info, malloc_info)
5256
5257
5258    strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5259    strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5260    strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5261    strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5262    strong_alias (__libc_memalign, __memalign)
5263    weak_alias (__libc_memalign, memalign)
5264    strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5265    strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5266    strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5267    strong_alias (__libc_mallinfo, __mallinfo)
5268    weak_alias (__libc_mallinfo, mallinfo)
5269    strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5270
5271    weak_alias (__malloc_stats, malloc_stats)
5272    weak_alias (__malloc_usable_size, malloc_usable_size)
5273    weak_alias (__malloc_trim, malloc_trim)
5274    weak_alias (__malloc_get_state, malloc_get_state)
5275    weak_alias (__malloc_set_state, malloc_set_state)
#endif

extern "C"  void*   calloc (size_t __nmemb, size_t __size)
{
    size_t  n   =   __nmemb * __size;
    void*   p   =   malloc (n);
    (void)::memset (p, 0, n);
    return p;
}

extern "C"  void    cfree (void* __ptr)
{
    free (__ptr);
}

extern "C"  void    free (void* __ptr)
{
    void*   p = ExposedPtrToBackendPtr_ (__ptr);
    __libc_free (p);
}

extern "C"  void*   malloc (size_t __size)
{
    void*   p   =   __libc_malloc (AdjustMallocSize_ (__size));
    if (p != nullptr) {
        p = BackendPtrToExposedPtr_ (p);
    }
    return p;
}

extern "C"  void*    realloc (void* __ptr, size_t __size)
{
    void*   p   =   ExposedPtrToBackendPtr_ (__ptr);
    size_t  n   =   AdjustMallocSize_ (__size);
    p = __libc_realloc (p, n);
    if (p != nullptr) {
        p = BackendPtrToExposedPtr_ (p);
    }
    return p;
}

extern "C"  void*   valloc (size_t __size)
{
    OhShit_ ();
    return nullptr;
}

extern "C"  void*   pvalloc (size_t __size)
{
    OhShit_ ();
    return nullptr;
}

extern "C"  void*   memalign (size_t __alignment, size_t __size)
{
    OhShit_ ();
    return nullptr;
}
#endif
<commit_msg>patch/validate ptrs on qStroika_Foundation_Debug_MallogGuard<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <exception>
#include    <malloc.h>

#include    "../Memory/Common.h"

#include    "MallocGuard.h"

using   namespace   Stroika::Foundation;
using   Memory::Byte;

#if     qStroika_Foundation_Debug_MallogGuard
namespace {
    using   GuradBytes_ =   Byte[16];
    constexpr   GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };
    constexpr   GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };

    // need header with size, so we can ....
    struct alignas(alignof(long double))  HeaderOrFooter_ {
        GuradBytes_ fGuard;
        size_t      fRequestedBlockSize;
    };

    void    OhShit_ ()
    {
        AssertNotReached ();
        std::terminate ();
    }

    void*   ExposedPtrToBackendPtr_ (void* p)
    {
        if (p == nullptr) {
            OhShit_ ();
        }
        return reinterpret_cast<const HeaderOrFooter_*> (p) - 1;
    }
    void*   BackendPtrToExposedPtr_ (void* p)
    {
        if (p == nullptr) {
            OhShit_ ();
        }
        return reinterpret_cast<const HeaderOrFooter_*> (p) + 1;
    }
    size_t  AdjustMallocSize_ (size_t s)
    {
        return s + 2 * sizeof (HeaderOrFooter_);
    }

    void    Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)
    {
        if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {
            OhShit_ ();
        }
        if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {
            OhShit_ ();
        }
        if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {
            OhShit_ ();
        }
        // OK
    }
    void    ValidateBackendPtr_ (const void* p)
    {
        const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);
        const HeaderOrFooter_*  fp  =   reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (hp + 1) + hp->fRequestedBlockSize);
        HeaderOrFooter_ footer;
        (void)::memcpy (&footer, fp, sizeof (footer));  // align access
        Validate_ (*h, footer);
    }
    void   PatchNewPointer_ (void* p, size_t requestedSize)
    {
        HeaderOrFooter_*  hp   =   reinterpret_cast< HeaderOrFooter_*> (p);
        (void)::memcpy (begin (hp->fGuard[0]), begin (kMallocGuardHeader_),  NEltsOf (kMallocGuardHeader_));
        hp->fRequestedBlockSize = requestedSize;
        HeaderOrFooter_*  fp  =    reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast<Byte*> (hp + 1) + hp->fRequestedBlockSize);
        (void)::memcpy (begin (fp->fGuard[0]), begin (kMallocGuardFooter_),  NEltsOf (kMallocGuardFooter_));
        fp->fRequestedBlockSize = requestedSize;
        return p;
    }
}
#endif

#if     qStroika_Foundation_Debug_MallogGuard

extern "C"  void    __libc_free (void* __ptr);
extern "C"  void*   __libc_malloc (size_t __size);
extern "C"  void*   __libc_realloc (void* __ptr, size_t __size);
extern "C"  void*   __libc_calloc (size_t __nmemb, size_t __size);
extern "C"  void    __libc_free (void* __ptr);
extern "C"  size_t  __malloc_usable_size (void* __ptr);
extern "C"  void*   __libc_memalign (size_t __alignment, size_t __size);

#if 0
weak_alias (__malloc_info, malloc_info)
5256
5257
5258    strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5259    strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5260    strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5261    strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5262    strong_alias (__libc_memalign, __memalign)
5263    weak_alias (__libc_memalign, memalign)
5264    strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5265    strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5266    strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5267    strong_alias (__libc_mallinfo, __mallinfo)
5268    weak_alias (__libc_mallinfo, mallinfo)
5269    strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5270
5271    weak_alias (__malloc_stats, malloc_stats)
5272    weak_alias (__malloc_usable_size, malloc_usable_size)
5273    weak_alias (__malloc_trim, malloc_trim)
5274    weak_alias (__malloc_get_state, malloc_get_state)
5275    weak_alias (__malloc_set_state, malloc_set_state)
#endif

extern "C"  void*   calloc (size_t __nmemb, size_t __size)
{
    size_t  n   =   __nmemb * __size;
    void*   p   =   malloc (n);
    (void)::memset (p, 0, n);
    return p;
}

extern "C"  void    cfree (void* __ptr)
{
    free (__ptr);
}

extern "C"  void    free (void* __ptr)
{
    void*   p = ExposedPtrToBackendPtr_ (__ptr);
    ValidateBackendPtr_ (p);
    __libc_free (p);
}

extern "C"  void*   malloc (size_t __size)
{
    void*   p   =   __libc_malloc (AdjustMallocSize_ (__size));
    PatchNewPointer_ (p, __size);
    ValidateBackendPtr_ (p);
    if (p != nullptr) {
        p = BackendPtrToExposedPtr_ (p);
    }
    return p;
}

extern "C"  void*    realloc (void* __ptr, size_t __size)
{
    void*   p   =   ExposedPtrToBackendPtr_ (__ptr);
    ValidateBackendPtr_ (p);
    size_t  n   =   AdjustMallocSize_ (__size);
    p = __libc_realloc (p, n);
    if (p != nullptr) {
        PatchNewPointer_ (p, __size);
        ValidateBackendPtr_ (p);
        p = BackendPtrToExposedPtr_ (p);
    }
    return p;
}

extern "C"  void*   valloc (size_t __size)
{
    OhShit_ ();
    return nullptr;
}

extern "C"  void*   pvalloc (size_t __size)
{
    OhShit_ ();
    return nullptr;
}

extern "C"  void*   memalign (size_t __alignment, size_t __size)
{
    OhShit_ ();
    return nullptr;
}
#endif
<|endoftext|>


<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019.  All rights reserved
*/
#include "../../StroikaPreComp.h"

#include "../../Characters/Format.h"
#include "../../Characters/ToString.h"
#include "../../IO/FileAccessException.h"

#include "Socket-Private_.h"

#include "Socket.h"

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;

using namespace Stroika::Foundation::IO::Network::PRIVATE_;

/*
 * Notes:
 *      http://stackoverflow.com/questions/2693709/what-was-the-motivation-for-adding-the-ipv6-v6only-flag
 *  Windows:
 *      https://msdn.microsoft.com/en-us/library/windows/desktop/bb513665(v=vs.85).aspx
 *      Windows Vista and later only
 *
 *  not sure how to handle this best cuz not every OS will support dual-stack (or will it?)
 *
 *  So assume no dual-stack sockets. That seems best --LGP 2017-04-24
 */
namespace {
    constexpr bool kUseDualStackSockets_ = false; // opposite of IPV6_V6ONLY
}

/*
 ********************************************************************************
 ******************************** Network::Socket *******************************
 ********************************************************************************
 */
Socket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const optional<IPPROTO>& protocol)
{
#if qPlatform_Windows
    IO::Network::Platform::Windows::WinSock::AssureStarted ();
#endif
    Socket::PlatformNativeHandle sfd;
#if qPlatform_POSIX
    ThrowPOSIXErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (ValueOrDefault (protocol))); }));
#elif qPlatform_Windows
    DISABLE_COMPILER_MSC_WARNING_START (28193) // dump warning about examining sfd
    ThrowWSASystemErrorIfSOCKET_ERROR (sfd = ::socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (ValueOrDefault (protocol))));
    DISABLE_COMPILER_MSC_WARNING_END (28193)
#else
    AssertNotImplemented ();
#endif
    if (family == SocketAddress::FamilyType::INET6) {
        int useIPV6Only = not kUseDualStackSockets_;
#if qPlatform_Linux
        // Linux follows the RFC, and uses dual-stack mode by default
        constexpr bool kOSDefaultIPV6Only_{false};
        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;
#elif qPlatfom_Windows
        // Windows defaults to NOT dual sockets, so nothing todo for windows
        constexpr bool kOSDefaultIPV6Only_{true};
        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;
#else
        bool mustSet = true;
#endif
        if (mustSet) {
            if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*> (&useIPV6Only), sizeof (useIPV6Only)) < 0) {
                AssertNotReached ();
            }
        }
    }
    return sfd;
}

/*
 ********************************************************************************
 ***************************** Network::Socket::Ptr *****************************
 ********************************************************************************
 */
Socket::PlatformNativeHandle Socket::Ptr::Detach ()
{
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    PlatformNativeHandle                               h = kINVALID_NATIVE_HANDLE_;
    if (fRep_ != nullptr) {
        h = fRep_->Detach ();
    }
    fRep_.reset ();
    return h;
}

Socket::Type Socket::Ptr::GetType () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    return getsockopt<Type> (SOL_SOCKET, SO_TYPE);
}

void Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)
{
    Debug::TraceContextBumper                          ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"IO::Network::Socket::Bind", L"sockAddr=%s bindFlags.fReUseAddr=%s", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    RequireNotNull (fRep_); // Construct with Socket::Kind::SOCKET_STREAM?

    // Indicates that the rules used in validating addresses supplied in a bind(2) call should allow
    // reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when
    // there is an active listening socket bound to the address. When the listening socket is bound
    // to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.
    setsockopt<int> (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);

    sockaddr_storage     useSockAddr = sockAddr.As<sockaddr_storage> ();
    PlatformNativeHandle sfd         = fRep_->GetNativeSocket ();
#if qPlatform_Windows
    try {
        ThrowWSASystemErrorIfSOCKET_ERROR (::bind (sfd, (sockaddr*)&useSockAddr, static_cast<int> (sockAddr.GetRequiredSize ())));
    }
    catch (const system_error& e) {
        if (e.code ().category () == system_category () and e.code ().value () == WSAEACCES) {
            Throw (SystemErrorException<> (e.code (), Characters::Format (L"Cannot Bind to %s: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)", Characters::ToString (sockAddr).c_str ())));
        }
        else {
            ReThrow ();
        }
    }
#else
    // EACCESS reproted as FileAccessException - which is crazy confusing.
    // @todo - find a better way, but for now remap this...
    try {
        ThrowPOSIXErrNoIfNegative (Handle_ErrNoResultInterruption ([sfd, &useSockAddr, &sockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sockAddr.GetRequiredSize ()); }));
    }
    catch (const IO::FileAccessException&) {
        Throw (Exception (Characters::Format (L"Cannot Bind to %s: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)", Characters::ToString (sockAddr).c_str ())));
    }
#endif
    catch (...) {
        Throw (Exception (Characters::Format (L"Cannot Bind to %s: %s", Characters::ToString (sockAddr).c_str (), Characters::ToString (current_exception ()).c_str ())));
    }
}

bool Socket::Ptr::IsOpen () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (fRep_ != nullptr) {
        return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;
    }
    return false;
}

String Socket::Ptr::ToString () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    StringBuilder                                       sb;
    if (fRep_ == nullptr) {
        sb += L"nullptr";
    }
    else {
        sb += L"{";
        sb += L"Native-Socket: " + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L"CLOSED" : Characters::ToString (fRep_->GetNativeSocket ())) + L", ";
        if (auto ola = GetLocalAddress ()) {
            sb += L"Local-Address: " + Characters::ToString (*ola);
        }
        sb += L"}";
    }
    return sb.str ();
}
<commit_msg>start using 'activity' exception code in IO::Network::Socket..::Bind () - still needs work but better<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019.  All rights reserved
*/
#include "../../StroikaPreComp.h"

#include "../../Characters/Format.h"
#include "../../Characters/ToString.h"
#include "../../Execution/Activity.h"
#include "../../IO/FileAccessException.h"

#include "Socket-Private_.h"

#include "Socket.h"

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;

using namespace Stroika::Foundation::IO::Network::PRIVATE_;

/*
 * Notes:
 *      http://stackoverflow.com/questions/2693709/what-was-the-motivation-for-adding-the-ipv6-v6only-flag
 *  Windows:
 *      https://msdn.microsoft.com/en-us/library/windows/desktop/bb513665(v=vs.85).aspx
 *      Windows Vista and later only
 *
 *  not sure how to handle this best cuz not every OS will support dual-stack (or will it?)
 *
 *  So assume no dual-stack sockets. That seems best --LGP 2017-04-24
 */
namespace {
    constexpr bool kUseDualStackSockets_ = false; // opposite of IPV6_V6ONLY
}

/*
 ********************************************************************************
 ******************************** Network::Socket *******************************
 ********************************************************************************
 */
Socket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const optional<IPPROTO>& protocol)
{
#if qPlatform_Windows
    IO::Network::Platform::Windows::WinSock::AssureStarted ();
#endif
    Socket::PlatformNativeHandle sfd;
#if qPlatform_POSIX
    ThrowPOSIXErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (ValueOrDefault (protocol))); }));
#elif qPlatform_Windows
    DISABLE_COMPILER_MSC_WARNING_START (28193) // dump warning about examining sfd
    ThrowWSASystemErrorIfSOCKET_ERROR (sfd = ::socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (ValueOrDefault (protocol))));
    DISABLE_COMPILER_MSC_WARNING_END (28193)
#else
    AssertNotImplemented ();
#endif
    if (family == SocketAddress::FamilyType::INET6) {
        int useIPV6Only = not kUseDualStackSockets_;
#if qPlatform_Linux
        // Linux follows the RFC, and uses dual-stack mode by default
        constexpr bool kOSDefaultIPV6Only_{false};
        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;
#elif qPlatfom_Windows
        // Windows defaults to NOT dual sockets, so nothing todo for windows
        constexpr bool kOSDefaultIPV6Only_{true};
        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;
#else
        bool mustSet = true;
#endif
        if (mustSet) {
            if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*> (&useIPV6Only), sizeof (useIPV6Only)) < 0) {
                AssertNotReached ();
            }
        }
    }
    return sfd;
}

/*
 ********************************************************************************
 ***************************** Network::Socket::Ptr *****************************
 ********************************************************************************
 */
Socket::PlatformNativeHandle Socket::Ptr::Detach ()
{
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    PlatformNativeHandle                               h = kINVALID_NATIVE_HANDLE_;
    if (fRep_ != nullptr) {
        h = fRep_->Detach ();
    }
    fRep_.reset ();
    return h;
}

Socket::Type Socket::Ptr::GetType () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    return getsockopt<Type> (SOL_SOCKET, SO_TYPE);
}

void Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)
{
    Debug::TraceContextBumper                          ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"IO::Network::Socket::Bind", L"sockAddr=%s bindFlags.fReUseAddr=%s", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    RequireNotNull (fRep_); // Construct with Socket::Kind::SOCKET_STREAM?

    auto                    bindingActivity = Execution::LazyEvalActivity{[&]() -> Characters::String { return L"binding to " + Characters::ToString (sockAddr); }};
    [[maybe_unused]] auto&& declareActivity = Execution::DeclareActivity{&bindingActivity};

    // Indicates that the rules used in validating addresses supplied in a bind(2) call should allow
    // reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when
    // there is an active listening socket bound to the address. When the listening socket is bound
    // to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.
    setsockopt<int> (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);

    sockaddr_storage     useSockAddr = sockAddr.As<sockaddr_storage> ();
    PlatformNativeHandle sfd         = fRep_->GetNativeSocket ();
#if qPlatform_Windows
    try {
        ThrowWSASystemErrorIfSOCKET_ERROR (::bind (sfd, (sockaddr*)&useSockAddr, static_cast<int> (sockAddr.GetRequiredSize ())));
    }
    catch (const system_error& e) {
        if (e.code ().category () == system_category () and e.code ().value () == WSAEACCES) {
            // @todo adjust message to reflect activity ... stuff - redo - this double adds
            Throw (SystemErrorException<> (e.code (), Characters::Format (L"Cannot Bind to %s: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)", Characters::ToString (sockAddr).c_str ())));
        }
        else {
            ReThrow ();
        }
    }
#else
    // EACCESS reproted as FileAccessException - which is crazy confusing.
    // @todo - find a better way, but for now remap this...
    try {
        ThrowPOSIXErrNoIfNegative (Handle_ErrNoResultInterruption ([sfd, &useSockAddr, &sockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sockAddr.GetRequiredSize ()); }));
    }
    catch (const IO::FileAccessException&) {
        // @todo adjust message to reflect activity ... stuff - redo - this double adds
        Throw (Exception (Characters::Format (L"Cannot Bind to %s: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)", Characters::ToString (sockAddr).c_str ())));
    }
#endif
    catch (...) {
        ReThrow ();
        // Throw (Exception (Characters::Format (L"Cannot Bind to %s: %s", Characters::ToString (sockAddr).c_str (), Characters::ToString (current_exception ()).c_str ())));
    }
}

bool Socket::Ptr::IsOpen () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (fRep_ != nullptr) {
        return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;
    }
    return false;
}

String Socket::Ptr::ToString () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    StringBuilder                                       sb;
    if (fRep_ == nullptr) {
        sb += L"nullptr";
    }
    else {
        sb += L"{";
        sb += L"Native-Socket: " + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L"CLOSED" : Characters::ToString (fRep_->GetNativeSocket ())) + L", ";
        if (auto ola = GetLocalAddress ()) {
            sb += L"Local-Address: " + Characters::ToString (*ola);
        }
        sb += L"}";
    }
    return sb.str ();
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"

#include <itkObject.h>
#include <mitkWeakPointer.h>

int mitkWeakPointerTest(int /*argc*/, char * /*argv*/ [])
{
  MITK_TEST_BEGIN("WeakPointer")

  int deleteEventCallbackCalled = 0;

  mitk::WeakPointer<itk::Object> weakPointer;

  weakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()
  {
    ++deleteEventCallbackCalled;
  });

  mitk::WeakPointer<itk::Object> weakPointer2;

  // Testing constructors and reference counting
  itk::Object::Pointer smartPointer = itk::Object::New();
  mitk::WeakPointer<itk::Object> weakPointer3(smartPointer);
  mitk::WeakPointer<itk::Object> weakPointer4(weakPointer);
  {
    itk::Object::Pointer tmpSmartPointer(weakPointer.Lock());
    itk::Object::Pointer tmpSmartPointer2(weakPointer2.Lock());
    MITK_TEST_CONDITION_REQUIRED(tmpSmartPointer.GetPointer() == tmpSmartPointer2.GetPointer(),
                                 "Testing equal pointers");
  }

  weakPointer = smartPointer;
  weakPointer2 = weakPointer;

  MITK_TEST_CONDITION_REQUIRED(1 == smartPointer->GetReferenceCount(), "Testing reference count");
  smartPointer = nullptr;
  MITK_TEST_CONDITION_REQUIRED(weakPointer.IsExpired(), "Testing expired weak pointer (smart pointer assignment)");
  MITK_TEST_CONDITION_REQUIRED(weakPointer2.IsExpired(), "Testing expired weak pointer (weak pointer assignment)");
  MITK_TEST_CONDITION_REQUIRED(weakPointer3.IsExpired(), "Testing expired weak pointer (smart pointer constructor)");
  MITK_TEST_CONDITION_REQUIRED(weakPointer4.IsExpired(), "Testing expired weak pointer (copy constructor)");
  MITK_TEST_CONDITION_REQUIRED(1 == deleteEventCallbackCalled, "Testing call of delete event callback");

  MITK_TEST_END()
}
<commit_msg>Port mitk weak pointer test, add setUp and tearDown<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Testing
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"

// std includes
#include <string>

// MITK includes
#include <mitkWeakPointer.h>

// ITK includes
#include <itkObject.h>

class mitkWeakPointerTestSuite : public mitk::TestFixture
{
	CPPUNIT_TEST_SUITE(mitkWeakPointerTestSuite);

	MITK_TEST(EqualPointers_Success);
	MITK_TEST(ExpiredWeakPointerWithSmartPointerAssignment_Success);
	MITK_TEST(ExpiredWeakPointerWithWeakPointerAssignment_Success);
	MITK_TEST(ExpiredWeakPointerWithSmartPointerConstructor_Success);
	MITK_TEST(ExpiredWeakPointerWithWeakPointerConstructor_Success);
	MITK_TEST(DeleteEventCall_Success);

	CPPUNIT_TEST_SUITE_END();

private:
	mitk::WeakPointer<itk::Object> m_WeakPointer;
	mitk::WeakPointer<itk::Object>  m_WeakPointer2;
	itk::Object::Pointer m_SmartPointer;

public:
	void setUp()
	{
		m_SmartPointer = itk::Object::New();
		m_WeakPointer = m_SmartPointer;
		m_WeakPointer2 = m_WeakPointer;
	}

	void tearDown()
	{
		m_SmartPointer = nullptr;
		m_WeakPointer = nullptr;
		m_WeakPointer2 = nullptr;
	}

	void EqualPointers_Success()
	{
		int deleteEventCallbackCalled = deleteEventCallbackCalled = 0;
		m_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()
		{
			++deleteEventCallbackCalled;
		});
		itk::Object::Pointer tmpSmartPointer(m_WeakPointer.Lock());
		itk::Object::Pointer tmpSmartPointer2(m_WeakPointer2.Lock());
		CPPUNIT_ASSERT_MESSAGE("Testing equal pointers", tmpSmartPointer.GetPointer() == tmpSmartPointer2.GetPointer());
	}

	void ReferenceCountOfPointers_Success()
	{
		CPPUNIT_ASSERT_MESSAGE("Testing reference count", 1 == m_SmartPointer->GetReferenceCount());
	}

	void ExpiredWeakPointerWithSmartPointerAssignment_Success()
	{
		m_SmartPointer = nullptr;
		CPPUNIT_ASSERT_MESSAGE("Testing expired weak pointer (smart pointer assignment)", m_WeakPointer.IsExpired());
	}

	void ExpiredWeakPointerWithWeakPointerAssignment_Success()
	{
		m_SmartPointer = nullptr;
		CPPUNIT_ASSERT_MESSAGE("Testing expired weak pointer (weak pointer assignment)", m_WeakPointer2.IsExpired());
	}

	void ExpiredWeakPointerWithSmartPointerConstructor_Success()
	{
		int deleteEventCallbackCalled = 0;
		mitk::WeakPointer<itk::Object> weakPointer3(m_SmartPointer);
		m_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()
		{
			++deleteEventCallbackCalled;
		});
		m_SmartPointer = nullptr;
		CPPUNIT_ASSERT_MESSAGE("Testing expired weak pointer (smart pointer constructor)", weakPointer3.IsExpired());
	}

	void ExpiredWeakPointerWithWeakPointerConstructor_Success()
	{
		int deleteEventCallbackCalled = 0;
		m_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()
		{
			++deleteEventCallbackCalled;
		});
		mitk::WeakPointer<itk::Object> weakPointer4(m_WeakPointer);
		m_WeakPointer = m_SmartPointer;
		m_SmartPointer = nullptr;
		CPPUNIT_ASSERT_MESSAGE("Testing expired weak pointer (copy constructor)", weakPointer4.IsExpired());
	}

	void DeleteEventCall_Success()
	{
		int deleteEventCallbackCalled = 0;
		m_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()
		{
			++deleteEventCallbackCalled;
		});
		m_WeakPointer = m_SmartPointer;
		m_SmartPointer = nullptr;
		CPPUNIT_ASSERT_MESSAGE("Testing call of delete event callback", 1 == deleteEventCallbackCalled);
	}

};
MITK_TEST_SUITE_REGISTRATION(mitkWeakPointer)
<|endoftext|>


<commit_before>#include "stan/math/functions/modified_bessel_first_kind.hpp"
#include <gtest/gtest.h>

TEST(MathFunctions, modified_bessel_first_kind) {
  using stan::math::modified_bessel_first_kind;

  EXPECT_FLOAT_EQ(11.301921952136330496356270183217102497412616594,
                  modified_bessel_first_kind(0,4.0));
  EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595,
                  modified_bessel_first_kind(1,-3.0));
  EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595,
                  modified_bessel_first_kind(-1,-3.0));
}
<commit_msg>added failing test<commit_after>#include <stan/math/functions/modified_bessel_first_kind.hpp>
#include <gtest/gtest.h>

TEST(MathFunctions, modified_bessel_first_kind) {
  using stan::math::modified_bessel_first_kind;

  EXPECT_FLOAT_EQ(11.301921952136330496356270183217102497412616594,
                  modified_bessel_first_kind(0,4.0));
  EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595,
                  modified_bessel_first_kind(1,-3.0));
  EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595,
                  modified_bessel_first_kind(-1,-3.0));
}

TEST(MathFunctions, modified_bessel_first_kind_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();

  EXPECT_THROW(stan::math::modified_bessel_first_kind(1, nan), std::domain_error);
}
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Copyright 2011 Intel Corporation
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *********************************************************************/

#include <stdlib.h>

#include <iostream>

#include "os_path.hpp"
#include "trace_tools.hpp"

namespace trace {

#if defined(__APPLE__)
#define CLI_TRACE_VARIABLE "DYLD_LIBRARY_PATH"
#define CLI_TRACE_WRAPPER  "OpenGL"
#elif defined(_WIN32)
#define CLI_TRACE_VARIABLE ""
#define CLI_TRACE_WRAPPER  "opengl32.dll"
#else
#define CLI_TRACE_VARIABLE "LD_PRELOAD"
#define CLI_TRACE_WRAPPER  "glxtrace.so"
#endif

os::Path
findFile(const char *relPath,
         const char *absPath,
         bool verbose)
{
    os::Path complete;

    /* First look in the same directory from which this process is
     * running, (to support developers running a compiled program that
     * has not been installed. */
    os::Path process_dir = os::getProcessName();

    process_dir.trimFilename();

    complete = process_dir;
    complete.join(relPath);

    if (complete.exists())
        return complete;

    /* Second, look in the directory for installed wrappers. */
    complete = absPath;
    if (complete.exists())
        return complete;

    if (verbose) {
        std::cerr << "error: cannot find " << relPath << " or " << absPath << "\n";
    }

    return "";
}

int
traceProgram(char * const *argv,
             const char *output,
             bool verbose)
{
    os::Path wrapper;

    wrapper = findFile("wrappers/" CLI_TRACE_WRAPPER, APITRACE_WRAPPER_INSTALL_DIR CLI_TRACE_WRAPPER, verbose);

    if (!wrapper.length()) {
        return 1;
    }

#if defined(_WIN32)

    std::cerr <<
        "The 'apitrace trace' command is not supported for this operating system.\n"
        "Instead, you will need to copy opengl32.dll, d3d8.dll, or d3d9.dll from\n"
        APITRACE_WRAPPER_INSTALL_DIR "\n"
        "to the directory with the application to trace, then run the application.\n";

#else

#if defined(__APPLE__)
    /* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the
     * directory, not the file. */
    wrapper.trimFilename();
#endif

    if (verbose) {
        std::cerr << CLI_TRACE_VARIABLE << "=" << wrapper.str() << "\n";
    }

    /* FIXME: Don't modify the current environment */
    setenv(CLI_TRACE_VARIABLE, wrapper.str(), 1);

    if (output) {
        setenv("TRACE_FILE", output, 1);
    }

    if (verbose) {
        const char *sep = "";
        for (char * const * arg = argv; *arg; ++arg) {
            std::cerr << *arg << sep;
            sep = " ";
        }
        std::cerr << "\n";
    }

    execvp(argv[0], argv);

    unsetenv(CLI_TRACE_VARIABLE);
    if (output) {
        unsetenv("TRACE_FILE");
    }

    std::cerr << "error: Failed to execute " << argv[0] << "\n";
#endif

    return 1;
}

} /* namespace trace */
<commit_msg>Fix "apitrace trace" when running from installed location.<commit_after>/*********************************************************************
 *
 * Copyright 2011 Intel Corporation
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *********************************************************************/

#include <stdlib.h>

#include <iostream>

#include "os_path.hpp"
#include "trace_tools.hpp"

namespace trace {

#if defined(__APPLE__)
#define CLI_TRACE_VARIABLE "DYLD_LIBRARY_PATH"
#define CLI_TRACE_WRAPPER  "OpenGL"
#elif defined(_WIN32)
#define CLI_TRACE_VARIABLE ""
#define CLI_TRACE_WRAPPER  "opengl32.dll"
#else
#define CLI_TRACE_VARIABLE "LD_PRELOAD"
#define CLI_TRACE_WRAPPER  "glxtrace.so"
#endif

os::Path
findFile(const char *relPath,
         const char *absPath,
         bool verbose)
{
    os::Path complete;

    /* First look in the same directory from which this process is
     * running, (to support developers running a compiled program that
     * has not been installed. */
    os::Path process_dir = os::getProcessName();

    process_dir.trimFilename();

    complete = process_dir;
    complete.join(relPath);

    if (complete.exists())
        return complete;

    /* Second, look in the directory for installed wrappers. */
    complete = absPath;
    if (complete.exists())
        return complete;

    if (verbose) {
        std::cerr << "error: cannot find " << relPath << " or " << absPath << "\n";
    }

    return "";
}

int
traceProgram(char * const *argv,
             const char *output,
             bool verbose)
{
    os::Path wrapper;

    wrapper = findFile("wrappers/" CLI_TRACE_WRAPPER, APITRACE_WRAPPER_INSTALL_DIR "/" CLI_TRACE_WRAPPER, verbose);

    if (!wrapper.length()) {
        return 1;
    }

#if defined(_WIN32)

    std::cerr <<
        "The 'apitrace trace' command is not supported for this operating system.\n"
        "Instead, you will need to copy opengl32.dll, d3d8.dll, or d3d9.dll from\n"
        APITRACE_WRAPPER_INSTALL_DIR "\n"
        "to the directory with the application to trace, then run the application.\n";

#else

#if defined(__APPLE__)
    /* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the
     * directory, not the file. */
    wrapper.trimFilename();
#endif

    if (verbose) {
        std::cerr << CLI_TRACE_VARIABLE << "=" << wrapper.str() << "\n";
    }

    /* FIXME: Don't modify the current environment */
    setenv(CLI_TRACE_VARIABLE, wrapper.str(), 1);

    if (output) {
        setenv("TRACE_FILE", output, 1);
    }

    if (verbose) {
        const char *sep = "";
        for (char * const * arg = argv; *arg; ++arg) {
            std::cerr << *arg << sep;
            sep = " ";
        }
        std::cerr << "\n";
    }

    execvp(argv[0], argv);

    unsetenv(CLI_TRACE_VARIABLE);
    if (output) {
        unsetenv("TRACE_FILE");
    }

    std::cerr << "error: Failed to execute " << argv[0] << "\n";
#endif

    return 1;
}

} /* namespace trace */
<|endoftext|>


<commit_before>AliAnalysisTaskEMCALTriggerQA * AddTaskEMCALTriggerQA(TString outputFile = ""){

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEMCALTriggerQA", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisTaskEMCALTriggerQA * qatrigger = new AliAnalysisTaskEMCALTriggerQA("QATrigger");

  AliEMCALRecoUtils * reco = qatrigger->GetRecoUtils();
  reco->SwitchOnRejectExoticCluster();

  // Pass the bad channels, temporary, to fix
  TString fileName="$ALICE_ROOT/OADB/EMCAL/EMCALBadChannels.root";
  AliOADBContainer *contBC=new AliOADBContainer("");
  contBC->InitFromFile((char*)fileName.Data(),"AliEMCALBadChannels");
  TObjArray *arrayBC=(TObjArray*)contBC->GetObject(162500); // LHC11e run
  if(arrayBC){
    TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject("pass1");
    if(arrayBCpass){

      reco->SwitchOnBadChannelsRemoval();
      printf("trigger REMOVE bad cells \n");

      for (Int_t i=0; i<10; ++i) {
        TH2I *hbm = reco->GetEMCALChannelStatusMap(i);
        if (hbm)
          delete hbm;
        hbm=(TH2I*)arrayBCpass->FindObject(Form("EMCALBadChannelMap_Mod%d",i));

        if (!hbm) {
          AliError(Form("Can not get EMCALBadChannelMap_Mod%d",i));
          continue;
        }

        hbm->SetDirectory(0);
        reco->SetEMCALChannelStatusMap(i,hbm);
      }
    } else printf("trigger AliEMCALRecoUtils ---Do NOT remove bad channels 1\n");
  }  else  printf("trigger AliEMCALRecoUtils ---Do NOT remove bad channels 2\n");

  // Extra channels, temporary, need fix

  Int_t badAbsID[]={103, 1263, 1275, 1860, 2117, 2298, 2776, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3712, 3713, 3714, 3715, 3716, 3717, 3718, 3719, 3720, 3721, 3722, 3723, 3724, 3725, 3726, 3727, 3764, 6111, 6800, 6801, 6802, 6803, 6804, 6805, 6806, 6807, 6808, 6809, 6810, 6811, 6812, 6813, 6814, 6815, 7430, 7491, 8352, 8353, 8354, 8356, 8357, 8362, 8808, 8810, 8812, 8814, 9217, 9361, 9704, 9769, 9802, 9837, 9839, 9888, 9946, 10117, 11462,
    74, 152, 759, 1059, 1175, 1204, 1288, 1376, 1382, 1386, 1519, 1967, 2026, 2047, 2112, 2114, 2115, 2116, 2118, 2119, 2120, 2123, 2124, 2125, 2350, 2506, 2540, 2793, 2891, 2985, 3135, 3503, 4377, 4817, 5600, 5601, 5602, 5603, 5612, 5613, 5614, 5615, 5648, 5649, 5650, 5651, 5660, 5661, 5662, 5663, 5836, 6104, 6481, 7371, 7375, 7425, 7572, 7874, 9269, 9302, 9389, 9696, 9697, 9698, 9700, 9701, 9702, 9703, 9705, 9706, 9707, 9708, 9709, 9710, 9711, 9750, 9758, 9792, 9793, 9794, 9795, 9798, 9800, 9801, 9803, 9804, 9815, 9824, 9825, 9828, 9829, 9830, 9831, 9832, 9833, 9834, 9835, 9836, 9838, 9872, 9874, 9875, 9878, 9882, 9883, 9889, 9890, 9891, 9892, 9893, 9894, 9896, 9897, 9898, 9899, 9900, 9901, 9902, 9903, 9927, 9937, 9938, 9939, 9940, 9941, 9942, 9943, 9947, 9948, 9949, 9950, 9951, 10112, 10113, 10114, 10115, 10116, 10118, 10119, 10120, 10121, 10122, 10123, 10124, 10125, 10718, 10723, 10771, 11042, 11091, 11363,
    191, 1968, 2210, 2339, 2391, 6331, 7089, 10126, 10127,
    46, 97, 145, 167, 173, 189, 238, 241, 337, 401, 433, 480, 527, 574, 594, 719, 816, 960, 1008, 1056, 1057, 1102, 1150, 1151, 1152, 1199, 1249, 1423, 1679, 1681, 1822, 1824, 1873, 1918, 2017, 2056, 2110, 2158, 2296, 2332, 2340, 2348, 2351, 2353, 2361, 2381, 2389, 2400, 2434, 2463, 2469, 2481, 2490, 2496, 2519, 2534, 2555, 2590, 2640, 2675, 2687, 2827, 2828, 2830, 2841, 2843, 2869, 2874, 2877, 2878, 2883, 2973, 3022, 3024, 3035, 3039, 3060, 3066, 3070, 3071, 3102, 3109, 3169, 3263, 3275, 3378, 3407, 3412, 4366, 4417, 4558, 4560, 4753, 4797, 8355, 9024, 9025, 9819, 11043};

  Int_t iCol = -1, iRow = -1, iSM =-1, iMod = -1,iIphi =-1,iIeta = -1;

  AliEMCALGeometry* geom = AliEMCALGeometry::GetInstance("EMCAL_COMPLETEV1");
  //printf("Total bad %d\n",sizeof(badAbsID)/sizeof(Int_t));
  for(Int_t i=0;i < sizeof(badAbsID)/sizeof(Int_t); i++){
    geom->GetCellIndex(badAbsID[i],iSM,iMod,iIphi,iIeta);
    // Gives SuperModule and Tower numbers
    geom->GetCellPhiEtaIndexInSModule(iSM,iMod,
                                      iIphi, iIeta,iRow,iCol);
    //printf("bad ID %d, col %d, row %d, sm %d, previous status %d\n",badAbsID[i],iCol,iRow,iSM, reco->GetEMCALChannelStatus(iSM , iCol, iRow));
    reco->SetEMCALChannelStatus(iSM , iCol, iRow,1);
  }

  reco->GetEMCALChannelStatus(8 , 27, 101-4*24);
  reco->GetEMCALChannelStatus(9 , 68-48-2, 111-4*24);
  reco->GetEMCALChannelStatus(3 , 74-48, 31-24);

  reco->GetEMCALChannelStatus(8 , 23, 98-4*24);
  reco->GetEMCALChannelStatus(8 , 30, 100-4*24);
  reco->GetEMCALChannelStatus(8 , 31, 100-4*24);
  reco->GetEMCALChannelStatus(8 , 31, 96-4*24);

  reco->GetEMCALChannelStatus(8 , 37, 103-4*24);
  reco->GetEMCALChannelStatus(8 , 38, 102-4*24);
  reco->GetEMCALChannelStatus(8 , 39, 102-4*24);
  reco->GetEMCALChannelStatus(8 , 37, 101-4*24);
  reco->GetEMCALChannelStatus(8 , 38, 101-4*24);
  reco->GetEMCALChannelStatus(8 , 39, 101-4*24);
  reco->GetEMCALChannelStatus(8 , 37, 99-4*24);
  reco->GetEMCALChannelStatus(8 , 38, 99-4*24);
  reco->GetEMCALChannelStatus(8 , 39, 99-4*24);

  if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer("EMCALQATrigger", TList::Class(), AliAnalysisManager::kOutputContainer,  Form("%s:EMCALQATrigger",outputFile.Data()));
  mgr->AddTask(qatrigger);
  mgr->ConnectInput  (qatrigger, 0, cinput1);
  mgr->ConnectOutput (qatrigger, 1, coutput);

  return qatrigger;

}
<commit_msg>remove hardcoded bad cells to be removed, pass run number to AODB<commit_after>AliAnalysisTaskEMCALTriggerQA * AddTaskEMCALTriggerQA(TString outputFile = "", Int_t run = 0){

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTriggerQA", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEMCALTriggerQA", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisTaskEMCALTriggerQA * qatrigger = new AliAnalysisTaskEMCALTriggerQA("QATrigger");

  AliEMCALRecoUtils * reco = qatrigger->GetRecoUtils();
  reco->SwitchOnRejectExoticCluster();

  // Pass the bad channels, need to access run number
  TString fileName="$ALICE_ROOT/OADB/EMCAL/EMCALBadChannels.root";
  AliOADBContainer *contBC=new AliOADBContainer("");
  contBC->InitFromFile((char*)fileName.Data(),"AliEMCALBadChannels");
  TObjArray *arrayBC=(TObjArray*)contBC->GetObject(run);
  if(arrayBC){
    TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject("pass1");
    if(arrayBCpass){

      reco->SwitchOnBadChannelsRemoval();
      printf("trigger REMOVE bad cells \n");

      for (Int_t i=0; i<10; ++i) {
        TH2I *hbm = reco->GetEMCALChannelStatusMap(i);
        if (hbm)
          delete hbm;
        hbm=(TH2I*)arrayBCpass->FindObject(Form("EMCALBadChannelMap_Mod%d",i));

        if (!hbm) {
          AliError(Form("Can not get EMCALBadChannelMap_Mod%d",i));
          continue;
        }

        hbm->SetDirectory(0);
        reco->SetEMCALChannelStatusMap(i,hbm);
      }
    } else printf("trigger AliEMCALRecoUtils ---Do NOT remove bad channels 1\n");
  }  else  printf("trigger AliEMCALRecoUtils ---Do NOT remove bad channels 2\n");

  if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();

  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer("EMCALQATrigger", TList::Class(), AliAnalysisManager::kOutputContainer,  Form("%s:EMCALQATrigger",outputFile.Data()));
  mgr->AddTask(qatrigger);
  mgr->ConnectInput  (qatrigger, 0, cinput1);
  mgr->ConnectOutput (qatrigger, 1, coutput);

  return qatrigger;

}
<|endoftext|>