<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "query_options.hh"

namespace cql3 {

thread_local const query_options::specific_options query_options::specific_options::DEFAULT{-1, {}, {}, api::missing_timestamp};

thread_local query_options query_options::DEFAULT{db::consistency_level::ONE, std::experimental::nullopt,
    {}, false, query_options::specific_options::DEFAULT, 3, serialization_format::use_32_bit()};

query_options::query_options(std::vector<bytes_opt> values)
        : query_options(db::consistency_level::ONE, { }, std::move(values),
        false, query_options::specific_options::DEFAULT, 3,
                serialization_format::use_32_bit()) {
}

}

<commit_msg>query_options: use version::native_protocol() for version<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "query_options.hh"
#include "version.hh"

namespace cql3 {

thread_local const query_options::specific_options query_options::specific_options::DEFAULT{-1, {}, {}, api::missing_timestamp};

thread_local query_options query_options::DEFAULT{db::consistency_level::ONE, std::experimental::nullopt,
    {}, false, query_options::specific_options::DEFAULT, version::native_protocol(), serialization_format::use_32_bit()};

query_options::query_options(std::vector<bytes_opt> values)
        : query_options(db::consistency_level::ONE, { }, std::move(values),
        false, query_options::specific_options::DEFAULT, 3,
                serialization_format::use_32_bit()) {
}

}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_PRIM_SCAL_FUNCTOR_REDUCE_SUM_HPP

#include <stan/math/prim/meta/return_type.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>

#include <boost/iterator/counting_iterator.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {

namespace internal {

// base definition => compile error
template <typename ReduceFunction, typename Enable = void, typename M, typename T, typename... Args>
struct reduce_sum_impl {};

// todo, double check if I need enable if here
template <typename ReduceFunction, typename M, typename T, typename... Args>
struct reduce_sum_impl<ReduceFunction, require_arithmetic_t<T>, M, T, Args...> {
  using vmapped_t = std::vector<M>;
  using arg1_t = std::vector<Arg1>;
  using arg2_t = std::vector<Arg2>;
  using arg3_t = std::vector<Arg3>;
  using arg4_t = std::vector<Arg4>;
  // todo(Steve): Need helper funcs for manipulating / iterating tuples
  std::tuple<std::vector<Args>...> arg_;
  const vmapped_t& vmapped_;
  const arg1_t& arg1_;
  const arg2_t& arg2_;
  const arg3_t& arg3_;
  const arg4_t& arg4_;
  T terms_sum_;

  // todo(Steve): put back recursive reducer
    reduce_sum_impl(const vmapped_t& vmapped, const T& init, Args&&... args)
        : vmapped_(vmapped),
          arg_(std::make_tuple(std::forward<Args>(args)...))
          terms_sum_(value_of(init)) {}

    reduce_sum_impl(reduce_sum_impl& other, tbb::split)
        : vmapped_(other.vmapped_),
        arg_(other.arg_),
        terms_sum_(0.0) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty()) {
        return;
      }

      auto start = vmapped_.begin();
      std::advance(start, r.begin());
      auto end = vmapped_.begin();
      std::advance(end, r.end());

      const vmapped_t sub_slice(start, end);

      terms_sum_ += ReduceFunction()(r.begin(), r.end() - 1, sub_slice, unpack_tuple_func(args));
    }

    void join(const reduce_sum_impl& child) {
      terms_sum_ += child.terms_sum_;
    }

  // Todo: Better name for this than operator(), collect()?
  template <typename... OtherArgs>
  T operator()(const vmapped_t& vmapped, T init, std::size_t grainsize,
               Args&&... args) const {
    const std::size_t num_jobs = vmapped.size();
    reduce_sum_impl<ReduceFunction, M, T, OtherArgs...> worker(vmapped, init, args...);
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
    return std::move(worker.terms_sum_);
  }
};

}  // namespace internal

/*
 * Note that the ReduceFunction is only passed in as type to prohibit
 * that any internal state of the functor is causing trouble. Thus,
 * the functor must be default constructible without any arguments.
 */
template <typename ReduceFunction, typename M, typename T, typename... Args>
constexpr T reduce_sum(const std::vector<M>& vmapped, T init,
                       std::size_t grainsize, Args&&... args) {
  typedef T return_base_t;
  // void here but need to figure out enable_if stuff
  // We do this somewhere in the opencl code
  return internal::reduce_sum_impl<ReduceFunction, M, T, void, Args...>()(
    vmapped, init, grainsize, std::forward<Args>(args)...);
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>loose stuff needed removed<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_PRIM_SCAL_FUNCTOR_REDUCE_SUM_HPP

#include <stan/math/prim/meta/return_type.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>

#include <boost/iterator/counting_iterator.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {

namespace internal {

// base definition => compile error
template <typename ReduceFunction, typename Enable = void, typename M, typename T, typename... Args>
struct reduce_sum_impl {};

// todo, double check if I need enable if here
template <typename ReduceFunction, typename M, typename T, typename... Args>
struct reduce_sum_impl<ReduceFunction, require_arithmetic_t<T>, M, T, Args...> {
  using vmapped_t = std::vector<M>;
  // todo(Steve): Need helper funcs for manipulating / iterating tuples
  std::tuple<std::vector<Args>...> arg_;
  const vmapped_t& vmapped_;
  T terms_sum_;

  // todo(Steve): put back recursive reducer
    reduce_sum_impl(const vmapped_t& vmapped, const T& init, Args&&... args)
        : vmapped_(vmapped),
          arg_(std::make_tuple(std::forward<Args>(args)...))
          terms_sum_(value_of(init)) {}

    reduce_sum_impl(reduce_sum_impl& other, tbb::split)
        : vmapped_(other.vmapped_),
        arg_(other.arg_),
        terms_sum_(0.0) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty()) {
        return;
      }

      auto start = vmapped_.begin();
      std::advance(start, r.begin());
      auto end = vmapped_.begin();
      std::advance(end, r.end());

      const vmapped_t sub_slice(start, end);

      terms_sum_ += ReduceFunction()(r.begin(), r.end() - 1, sub_slice, unpack_tuple_func(args));
    }

    void join(const reduce_sum_impl& child) {
      terms_sum_ += child.terms_sum_;
    }

  // Todo: Better name for this than operator(), collect()?
  template <typename... OtherArgs>
  T operator()(const vmapped_t& vmapped, T init, std::size_t grainsize,
               Args&&... args) const {
    const std::size_t num_jobs = vmapped.size();
    reduce_sum_impl<ReduceFunction, M, T, OtherArgs...> worker(vmapped, init, args...);
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
    return std::move(worker.terms_sum_);
  }
};

}  // namespace internal

/*
 * Note that the ReduceFunction is only passed in as type to prohibit
 * that any internal state of the functor is causing trouble. Thus,
 * the functor must be default constructible without any arguments.
 */
template <typename ReduceFunction, typename M, typename T, typename... Args>
constexpr T reduce_sum(const std::vector<M>& vmapped, T init,
                       std::size_t grainsize, Args&&... args) {
  typedef T return_base_t;
  // void here but need to figure out enable_if stuff
  // We do this somewhere in the opencl code
  return internal::reduce_sum_impl<ReduceFunction, M, T, void, Args...>()(
    vmapped, init, grainsize, std::forward<Args>(args)...);
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This determines when to switch between the direct (for small sizes) and in-direct GEMM kernel
// with pre/post-processing kernels (for larger sizes). These can be set in a similar way as for the
// regular kernel tuning parameters: they can be specific for a certain vendor or device or can use
// some common default values.
//
// =================================================================================================

namespace clblast {
namespace database {
// =================================================================================================

const Database::DatabaseEntry KernelSelectionHalf = {
  "KernelSelection", Precision::kHalf, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionSingle = {
  "KernelSelection", Precision::kSingle, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionComplexSingle = {
  "KernelSelection", Precision::kComplexSingle, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionDouble = {
  "KernelSelection", Precision::kDouble, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionComplexDouble = {
  "KernelSelection", Precision::kComplexDouble, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================
} // namespace database
} // namespace clblast
<commit_msg>Add new threshold for ARM<commit_after>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This determines when to switch between the direct (for small sizes) and in-direct GEMM kernel
// with pre/post-processing kernels (for larger sizes). These can be set in a similar way as for the
// regular kernel tuning parameters: they can be specific for a certain vendor or device or can use
// some common default values.
//
// =================================================================================================

namespace clblast {
namespace database {
// =================================================================================================

const Database::DatabaseEntry KernelSelectionHalf = {
  "KernelSelection", Precision::kHalf, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionSingle = {
  "KernelSelection", Precision::kSingle, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    {
      kDeviceTypeGPU, "ARM", {
        { "default",                                         { 128*128*128} },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionComplexSingle = {
  "KernelSelection", Precision::kComplexSingle, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionDouble = {
  "KernelSelection", Precision::kDouble, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================

const Database::DatabaseEntry KernelSelectionComplexDouble = {
  "KernelSelection", Precision::kComplexDouble, {"XGEMM_MIN_INDIRECT_SIZE"}, {
    { // Intel GPUs
      kDeviceTypeGPU, "Intel", {
        { "default",                                         { 1*1*1 } },
      }
    },
    { // NVIDIA GPUs
      kDeviceTypeGPU, "NVIDIA", {
        { "default",                                         { 1280*1280*1280 } },
      }
    },
    { // Default
      kDeviceTypeAll, "default", {
        { "default",                                         { 512*512*512 } },
      }
    },
  }
};

// =================================================================================================
} // namespace database
} // namespace clblast
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.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_pm_get_poundv_bucket.C
/// @brief Grab PM data from attribute
///

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket.H>
#include <attribute_ids.H>

fapi2::ReturnCode p9_pm_get_poundv_bucket(
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
    fapi2::voltageBucketData_t& o_data)
{
    FAPI_IMP("Entering p9_pm_get_poundv_bucket ....");

    //Set up a char array to hold the bucket data from an attr read
    fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr;

    //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA,
                           i_target,
                           l_bucketAttr));

    memcpy(&o_data, l_bucketAttr, sizeof(o_data));

fapi_try_exit:
    FAPI_IMP("Exiting p9_pm_get_poundv_bucket ....");

    return fapi2::current_err;
}
<commit_msg>L3 Update - p9_pm_get_poundv/w_bucket HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.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_pm_get_poundv_bucket.C
/// @brief Grab PM data from attribute
///
/// *HWP HW Owner    : N/A (This is a FW delivered function)
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : PM - Calling this function.
/// *HWP Consumed by : FSP
/// *HWP Level       : 3
///

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket.H>
#include <attribute_ids.H>

// See doxygen in header file
fapi2::ReturnCode p9_pm_get_poundv_bucket(
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
    fapi2::voltageBucketData_t& o_data)
{
    FAPI_DBG("Entering p9_pm_get_poundv_bucket ....");

    //Set up a char array to hold the bucket data from an attr read
    fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr;

    //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA,
                           i_target,
                           l_bucketAttr));

    memcpy(&o_data, l_bucketAttr, sizeof(o_data));

fapi_try_exit:
    FAPI_DBG("Exiting p9_pm_get_poundv_bucket ....");

    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * 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 <string.h>
#include <iostream>

#include "os_time.hpp"
#include "trace_dump.hpp"
#include "retrace.hpp"

namespace retrace {

static bool call_dumped = false;

static void dumpCall(trace::Call &call) {
    if (verbosity >= 0 && !call_dumped) {
        std::cout << call;
        std::cout.flush();
        call_dumped = true;
    }
}

std::ostream &warning(trace::Call &call) {
    dumpCall(call);

    std::cerr << call.no << ": ";
    std::cerr << "warning: ";

    return std::cerr;
}

void ignore(trace::Call &call) {
    (void)call;
}

void unsupported(trace::Call &call) {
    warning(call) << "unsupported " << call.name() << " call\n";
}

inline void Retracer::addCallback(const Entry *entry) {
    assert(entry->name);
    assert(entry->callback);
    map[entry->name] = entry->callback;
}

void Retracer::addCallbacks(const Entry *entries) {
    while (entries->name && entries->callback) {
        addCallback(entries++);
    }
}

void Retracer::retrace(trace::Call &call) {
    call_dumped = false;

    if (verbosity >= 1) {
        if (verbosity >= 2 ||
            !(call.flags & trace::CALL_FLAG_VERBOSE)) {
            dumpCall(call);
        }
    }

    Callback callback = 0;

    trace::Id id = call.sig->id;
    if (id >= callbacks.size()) {
        callbacks.resize(id + 1);
        callback = 0;
    } else {
        callback = callbacks[id];
    }

    if (!callback) {
        Map::const_iterator it = map.find(call.name());
        if (it == map.end()) {
            callback = &unsupported;
        } else {
            callback = it->second;
        }
        callbacks[id] = callback;
    }

    assert(callback);
    assert(callbacks[id] == callback);

    callback(call);
}

} /* namespace retrace */
<commit_msg>Don't dump ignored functions when retracing.<commit_after>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * 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 <string.h>
#include <iostream>

#include "os_time.hpp"
#include "trace_dump.hpp"
#include "retrace.hpp"

namespace retrace {

static bool call_dumped = false;

static void dumpCall(trace::Call &call) {
    if (verbosity >= 0 && !call_dumped) {
        std::cout << call;
        std::cout.flush();
        call_dumped = true;
    }
}

std::ostream &warning(trace::Call &call) {
    dumpCall(call);

    std::cerr << call.no << ": ";
    std::cerr << "warning: ";

    return std::cerr;
}

void ignore(trace::Call &call) {
    (void)call;
}

void unsupported(trace::Call &call) {
    warning(call) << "unsupported " << call.name() << " call\n";
}

inline void Retracer::addCallback(const Entry *entry) {
    assert(entry->name);
    assert(entry->callback);
    map[entry->name] = entry->callback;
}

void Retracer::addCallbacks(const Entry *entries) {
    while (entries->name && entries->callback) {
        addCallback(entries++);
    }
}

void Retracer::retrace(trace::Call &call) {
    call_dumped = false;

    Callback callback = 0;

    trace::Id id = call.sig->id;
    if (id >= callbacks.size()) {
        callbacks.resize(id + 1);
        callback = 0;
    } else {
        callback = callbacks[id];
    }

    if (!callback) {
        Map::const_iterator it = map.find(call.name());
        if (it == map.end()) {
            callback = &unsupported;
        } else {
            callback = it->second;
        }
        callbacks[id] = callback;
    }

    assert(callback);
    assert(callbacks[id] == callback);

    if (verbosity >= 1) {
        if (verbosity >= 2 ||
            (!(call.flags & trace::CALL_FLAG_VERBOSE) &&
             callback != &ignore)) {
            dumpCall(call);
        }
    }

    callback(call);
}

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


<commit_before>#pragma once

#include <cstdint>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>

#include "blackhole/sink/files/rotation/config.hpp"
#include "blackhole/sink/files/rotation/counter.hpp"
#include "blackhole/sink/files/rotation/naming/filter.hpp"
#include "blackhole/sink/files/rotation/timer.hpp"
#include "blackhole/sink/files/rotation/watcher.hpp"

namespace blackhole {

namespace sink {

//! Tag for file sinks with no rotation.
class NoRotation;

template<class Backend, class Watcher, class Timer = rotation::timer_t>
class rotator_t {
    rotation::config_t<Watcher> config;
    Backend& backend;
    Timer m_timer;
    rotation::naming::basename_t generator;
    rotation::counter_t counter;
    Watcher watcher;
public:
    static const char* name() {
        return "rotate";
    }

    rotator_t(const rotation::config_t<Watcher>& config, Backend& backend) :
        config(config),
        backend(backend),
        generator(config.pattern),
        counter(rotation::counter_t::from_string(boost::algorithm::replace_all_copy(config.pattern, "%(filename)s", backend.filename()))),
        watcher(config.watcher)
    {}

    //!@todo: Isolate.
    Timer& timer() {
        return m_timer;
    }

    bool necessary(const std::string& message) const {
        return watcher(backend, message);
    }

    void rotate() const {
        backend.flush();
        backend.close();
        rollover();
        backend.open();
    }

private:
    void rollover() const {
        const std::string& filename = backend.filename();
        const std::string& basename = generator.transform(filename);

        if (counter.valid()) {
            rollover(backend.listdir(), basename);
        }

        if (backend.exists(filename)) {
            backend.rename(filename, backup_filename(basename));
        }
    }

    void rollover(std::vector<std::string> filenames, const std::string& pattern) const {
        filenames.erase(std::remove_if(filenames.begin(),
                                       filenames.end(),
                                       rotation::naming::filter_t(pattern)),
                        filenames.end());
        std::sort(filenames.begin(), filenames.end(),
                  rotation::naming::comparator::time::descending<Backend>(backend));
        if (filenames.size() > static_cast<std::size_t>(config.backups - 1)) {
            filenames.erase(filenames.begin() + config.backups - 1, filenames.end());
        }

        for (int n = filenames.size() - 1; n >= 0; --n) {
            const std::string& filename = filenames.at(n);
            if (backend.exists(filename)) {
                backend.rename(filename, counter.next(filename, n + 1));
            }
        }
    }

    std::string backup_filename(const std::string& pattern) const {
        std::string filename = pattern;
        boost::algorithm::replace_all(filename, "%N", "1");
        std::time_t time = m_timer.current();
        char buf[128];
        if (strftime(buf, 128, filename.data(), std::gmtime(&time)) == 0) {
            // Do nothing.
        }

        return std::string(buf);
    }
};

} // namespace sink

} // namespace blackhole
<commit_msg>[Code Style] Blank line.<commit_after>#pragma once

#include <cstdint>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>

#include "blackhole/sink/files/rotation/config.hpp"
#include "blackhole/sink/files/rotation/counter.hpp"
#include "blackhole/sink/files/rotation/naming/filter.hpp"
#include "blackhole/sink/files/rotation/timer.hpp"
#include "blackhole/sink/files/rotation/watcher.hpp"

namespace blackhole {

namespace sink {

//! Tag for file sinks with no rotation.
class NoRotation;

template<class Backend, class Watcher, class Timer = rotation::timer_t>
class rotator_t {
    rotation::config_t<Watcher> config;
    Backend& backend;
    Timer m_timer;
    rotation::naming::basename_t generator;
    rotation::counter_t counter;
    Watcher watcher;

public:
    static const char* name() {
        return "rotate";
    }

    rotator_t(const rotation::config_t<Watcher>& config, Backend& backend) :
        config(config),
        backend(backend),
        generator(config.pattern),
        counter(rotation::counter_t::from_string(boost::algorithm::replace_all_copy(config.pattern, "%(filename)s", backend.filename()))),
        watcher(config.watcher)
    {}

    //!@todo: Isolate.
    Timer& timer() {
        return m_timer;
    }

    bool necessary(const std::string& message) const {
        return watcher(backend, message);
    }

    void rotate() const {
        backend.flush();
        backend.close();
        rollover();
        backend.open();
    }

private:
    void rollover() const {
        const std::string& filename = backend.filename();
        const std::string& basename = generator.transform(filename);

        if (counter.valid()) {
            rollover(backend.listdir(), basename);
        }

        if (backend.exists(filename)) {
            backend.rename(filename, backup_filename(basename));
        }
    }

    void rollover(std::vector<std::string> filenames, const std::string& pattern) const {
        filenames.erase(std::remove_if(filenames.begin(),
                                       filenames.end(),
                                       rotation::naming::filter_t(pattern)),
                        filenames.end());
        std::sort(filenames.begin(), filenames.end(),
                  rotation::naming::comparator::time::descending<Backend>(backend));
        if (filenames.size() > static_cast<std::size_t>(config.backups - 1)) {
            filenames.erase(filenames.begin() + config.backups - 1, filenames.end());
        }

        for (int n = filenames.size() - 1; n >= 0; --n) {
            const std::string& filename = filenames.at(n);
            if (backend.exists(filename)) {
                backend.rename(filename, counter.next(filename, n + 1));
            }
        }
    }

    std::string backup_filename(const std::string& pattern) const {
        std::string filename = pattern;
        boost::algorithm::replace_all(filename, "%N", "1");
        std::time_t time = m_timer.current();
        char buf[128];
        if (strftime(buf, 128, filename.data(), std::gmtime(&time)) == 0) {
            // Do nothing.
        }

        return std::string(buf);
    }
};

} // namespace sink

} // namespace blackhole
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * 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.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#pragma once
#include <tuple>
#include <cstdint>
#include <type_traits>

#include <boost/system/error_code.hpp>
#include <boost/asio.hpp>
#include <boost/preprocessor.hpp>

#include <crossbow/Serializer.hpp>
#include <crossbow/string.hpp>

#define GEN_CASE(r, data, elem)\
    case data::elem:\
        static_cast<Derived*>(this)->template execute<data::elem>();\
        break;

#define SWITCH_CASE(Name, cmd, tuple) switch(cmd) {\
    BOOST_PP_SEQ_FOR_EACH(GEN_CASE, Name, BOOST_PP_TUPLE_TO_SEQ(tuple))\
}

#define GEN_COMMANDS(Name, tuple) enum class Name {\
    BOOST_PP_TUPLE_ELEM(0, tuple) = 1, \
    BOOST_PP_TUPLE_ENUM(BOOST_PP_TUPLE_POP_FRONT(tuple)) \
};\
template<class Derived>\
struct Name ## _Switch {\
    using type = Name;\
    void execute_impl(Name cmd) {\
        SWITCH_CASE(Name, cmd, tuple)\
    }\
}

namespace crossbow {
namespace protocol {

namespace impl {

template<class... Args>
struct ArgSerializer;

template<class Head, class... Tail>
struct ArgSerializer<Head, Tail...> {
    ArgSerializer<Tail...> rest;

    template<class C>
    void exec(C& c, const Head& head, const Tail&... tail) const {
        c & head;
        rest.exec(c, tail...);
    }
};

template<>
struct ArgSerializer<> {
    template<class C>
    void exec(C&) const {}
};

} // namespace impl

template<class... Args>
struct argsType;
template<class A, class B, class... Tail>
struct argsType<A, B, Tail...> {
    using type = std::tuple<A, B, Tail...>;
};
template<class Arg>
struct argsType<Arg> {
    using type = Arg;
};
template<>
struct argsType<> {
    using type = void;
};

template<class Command, template <Command> class Signature>
class Client {
    boost::asio::ip::tcp::socket& mSocket;
    size_t mCurrSize = 1024;
    std::unique_ptr<uint8_t[]> mCurrentRequest;
public:
    Client(boost::asio::ip::tcp::socket& socket)
        : mSocket(socket), mCurrentRequest(new uint8_t[mCurrSize])
    {
    }

    template<class Callback, class Result>
    typename std::enable_if<std::is_void<Result>::value, void>::type
    readResponse(const Callback& callback, size_t bytes_read = 0) {
        assert(bytes_read <= 1);
        if (bytes_read) {
            boost::system::error_code noError;
            callback(noError);
        }
        mSocket.async_read_some(boost::asio::buffer(mCurrentRequest.get(), mCurrSize),
                [this, callback, bytes_read](const boost::system::error_code& ec, size_t br){
                    if (ec) {
                        error<Result>(ec, callback);
                        return;
                    }
                    readResponse<Callback, Result>(callback, bytes_read + br);
                });
    }

    template<class Callback, class Result>
    typename std::enable_if<!std::is_void<Result>::value, void>::type
    readResponse(const Callback& callback, size_t bytes_read = 0) {
        auto respSize = *reinterpret_cast<size_t*>(mCurrentRequest.get());
        if (bytes_read >= 8 && respSize == bytes_read) {
            // response read
            Result res;
            boost::system::error_code noError;
            crossbow::deserializer ser(mCurrentRequest.get() + sizeof(size_t));
            ser & res;
            callback(noError, res);
            return;
        } else if (bytes_read >= 8 && respSize > mCurrSize) {
            std::unique_ptr<uint8_t[]> newBuf(new uint8_t[respSize]);
            memcpy(newBuf.get(), mCurrentRequest.get(), mCurrSize);
            mCurrentRequest.swap(newBuf);
        }
        mSocket.async_read_some(boost::asio::buffer(mCurrentRequest.get() + bytes_read, mCurrSize - bytes_read),
                [this, callback, bytes_read](const boost::system::error_code& ec, size_t br){
                    if (ec) {
                        Result res;
                        callback(ec, res);
                        return;
                    }
                    readResponse<Callback, Result>(callback, bytes_read + br);
                });
    }

    template<class Res, class Callback>
    typename std::enable_if<std::is_void<Res>::value, void>::type
    error(const boost::system::error_code& ec, const Callback& callback) {
        callback(ec);
    }

    template<class Res, class Callback>
    typename std::enable_if<!std::is_void<Res>::value, void>::type
    error(const boost::system::error_code& ec, const Callback& callback) {
        Res res;
        callback(ec, res);
    }

    template<Command C, class Callback, class... Args>
    void execute(const Callback& callback, const Args&... args) {
        static_assert(
                (std::is_void<typename Signature<C>::arguments>::value && std::is_void<argsType<Args...>>::value) ||
                std::is_same<typename Signature<C>::arguments, typename argsType<Args...>::type>::value,
                "Wrong function arguments");
        using ResType = typename Signature<C>::result;
        crossbow::sizer sizer;
        sizer & sizer.size;
        sizer & C;
        impl::ArgSerializer<Args...> argSerializer;
        argSerializer.exec(sizer, args...);
        if (mCurrSize < sizer.size) {
            mCurrentRequest.reset(new uint8_t[sizer.size]);
            mCurrSize = sizer.size;
        }
        crossbow::serializer ser(mCurrentRequest.get());
        ser & sizer.size;
        ser & C;
        argSerializer.exec(ser, args...);
        ser.buffer.release();
        boost::asio::async_write(mSocket, boost::asio::buffer(mCurrentRequest.get(), sizer.size),
                    [this, callback](const boost::system::error_code& ec, size_t){
                        if (ec) {
                            error<ResType>(ec, callback);
                            return;
                        }
                        readResponse<Callback, ResType>(callback);
                    });
    }
};

template<template <typename> class Cmd_Switch,
         class Command,
         template <Command> class Signature,
         class Implementation>
class Server : Cmd_Switch<Server<Cmd_Switch, Command, Signature, Implementation>> {
    Implementation& mImpl;
    boost::asio::ip::tcp::socket& mSocket;
    size_t mBufSize = 1024;
    std::unique_ptr<uint8_t[]> mBuffer;
    using error_code = boost::system::error_code;
    bool doQuit = false;
public:
    Server(Implementation& impl, boost::asio::ip::tcp::socket& socket)
        : mImpl(impl)
        , mSocket(socket)
        , mBuffer(new uint8_t[mBufSize])
    {}
    void run() {
        read();
    }
    void quit() {
        doQuit = true;
    }
private:
    template<Command C, class Callback>
    typename std::enable_if<std::is_void<typename Signature<C>::arguments>::value, void>::type
    execute(Callback callback) {
        mImpl.template execute<C>(callback);
    }

    template<Command C, class Callback>
    typename std::enable_if<!std::is_void<typename Signature<C>::arguments>::value, void>::type
    execute(Callback callback) {
        using Args = typename Signature<C>::arguments;
        Args args;
        crossbow::deserializer des(mBuffer.get() + sizeof(size_t) + sizeof(Command));
        des & args;
        mImpl.template execute<C>(args, callback);
    }

    template<Command C>
    typename std::enable_if<std::is_void<typename Signature<C>::result>::value, void>::type execute() {
        execute<C>([this]() {
            // send the result back
            mBuffer[0] = 1;
            boost::asio::async_write(mSocket,
                    boost::asio::buffer(mBuffer.get(), 1),
                    [this](const error_code& ec, size_t bytes_written) {
                        if (ec) {
                            std::cerr << ec.message() << std::endl;
                            return;
                        }
                        read(0);
                    }
            );
        });
    }

    template<Command C>
    typename std::enable_if<!std::is_void<typename Signature<C>::result>::value, void>::type execute() {
        using Res = typename Signature<C>::result;
        execute<C>([this](const Res& result) {
            // Serialize result
            crossbow::sizer sizer;
            sizer & sizer.size;
            sizer & result;
            if (mBufSize < sizer.size) {
                mBuffer.reset(new uint8_t[sizer.size]);
            }
            crossbow::serializer ser(mBuffer.get());
            ser & sizer.size;
            ser & result;
            ser.buffer.release();
            // send the result back
            boost::asio::async_write(mSocket,
                    boost::asio::buffer(mBuffer.get(), sizer.size),
                    [this](const error_code& ec, size_t bytes_written) {
                        if (ec) {
                            std::cerr << ec.message() << std::endl;
                            mSocket.close();
                            mImpl.close();
                            return;
                        }
                        read(0);
                    }
            );
        });
    }
    void read(size_t bytes_read = 0) {
        if (bytes_read == 0 && doQuit) {
            mSocket.get_io_service().stop();
        }
        size_t reqSize = 0;
        if (bytes_read != 0) {
            reqSize = *reinterpret_cast<size_t*>(mBuffer.get());
        }
        if (bytes_read != 0 && reqSize == bytes_read) {
            // done reading
            auto cmd = *reinterpret_cast<Command*>(mBuffer.get() + sizeof(size_t));
            this->execute_impl(cmd);
            return;
        } else if (bytes_read >= 8 && reqSize > mBufSize) {
            std::unique_ptr<uint8_t[]> newBuf(new uint8_t[reqSize]);
            memcpy(newBuf.get(), mBuffer.get(), mBufSize);
            mBuffer.swap(newBuf);
            mBufSize = reqSize;
        }
        mSocket.async_read_some(boost::asio::buffer(mBuffer.get() + bytes_read, mBufSize - bytes_read),
                [this, bytes_read](const error_code& ec, size_t br){
                    if (ec) {
                        std::cerr << ec.message() << std::endl;
                        mSocket.close();
                        mImpl.close();
                        return;
                    }
                    read(bytes_read + br);
                });
    }
};

} // namespace protocol
} // namespace crossbow

<commit_msg>protocol fix<commit_after>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * 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.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#pragma once
#include <tuple>
#include <cstdint>
#include <type_traits>

#include <boost/system/error_code.hpp>
#include <boost/asio.hpp>
#include <boost/preprocessor.hpp>

#include <crossbow/Serializer.hpp>
#include <crossbow/string.hpp>

#define GEN_CASE(r, data, elem)\
    case data::elem:\
        static_cast<Derived*>(this)->template execute<data::elem>();\
        break;

#define SWITCH_CASE(Name, cmd, tuple) switch(cmd) {\
    BOOST_PP_SEQ_FOR_EACH(GEN_CASE, Name, BOOST_PP_TUPLE_TO_SEQ(tuple))\
}

#define GEN_COMMANDS(Name, tuple) enum class Name {\
    BOOST_PP_TUPLE_ELEM(0, tuple) = 1, \
    BOOST_PP_TUPLE_ENUM(BOOST_PP_TUPLE_POP_FRONT(tuple)) \
};\
template<class Derived>\
struct Name ## _Switch {\
    using type = Name;\
    void execute_impl(Name cmd) {\
        SWITCH_CASE(Name, cmd, tuple)\
    }\
}

#define SERVER_TYPE_S(Name, Signature) crossbow::protocol::Server<Name ## _Switch, Name, Signature, Impl>
#define SERVER_TYPE(Name, Impl) crossbow::protocol::Server<Name ## _Switch, Name, Signature, Impl>

namespace crossbow {
namespace protocol {

namespace impl {

template<class... Args>
struct ArgSerializer;

template<class Head, class... Tail>
struct ArgSerializer<Head, Tail...> {
    ArgSerializer<Tail...> rest;

    template<class C>
    void exec(C& c, const Head& head, const Tail&... tail) const {
        c & head;
        rest.exec(c, tail...);
    }
};

template<>
struct ArgSerializer<> {
    template<class C>
    void exec(C&) const {}
};

} // namespace impl

template<class... Args>
struct argsType;
template<class A, class B, class... Tail>
struct argsType<A, B, Tail...> {
    using type = std::tuple<A, B, Tail...>;
};
template<class Arg>
struct argsType<Arg> {
    using type = Arg;
};
template<>
struct argsType<> {
    using type = void;
};

template<class Command, template <Command> class Signature>
class Client {
    boost::asio::ip::tcp::socket& mSocket;
    size_t mCurrSize = 1024;
    std::unique_ptr<uint8_t[]> mCurrentRequest;
public:
    Client(boost::asio::ip::tcp::socket& socket)
        : mSocket(socket), mCurrentRequest(new uint8_t[mCurrSize])
    {
    }

    template<class Callback, class Result>
    typename std::enable_if<std::is_void<Result>::value, void>::type
    readResponse(const Callback& callback, size_t bytes_read = 0) {
        assert(bytes_read <= 1);
        if (bytes_read) {
            boost::system::error_code noError;
            callback(noError);
        }
        mSocket.async_read_some(boost::asio::buffer(mCurrentRequest.get(), mCurrSize),
                [this, callback, bytes_read](const boost::system::error_code& ec, size_t br){
                    if (ec) {
                        error<Result>(ec, callback);
                        return;
                    }
                    readResponse<Callback, Result>(callback, bytes_read + br);
                });
    }

    template<class Callback, class Result>
    typename std::enable_if<!std::is_void<Result>::value, void>::type
    readResponse(const Callback& callback, size_t bytes_read = 0) {
        auto respSize = *reinterpret_cast<size_t*>(mCurrentRequest.get());
        if (bytes_read >= 8 && respSize == bytes_read) {
            // response read
            Result res;
            boost::system::error_code noError;
            crossbow::deserializer ser(mCurrentRequest.get() + sizeof(size_t));
            ser & res;
            callback(noError, res);
            return;
        } else if (bytes_read >= 8 && respSize > mCurrSize) {
            std::unique_ptr<uint8_t[]> newBuf(new uint8_t[respSize]);
            memcpy(newBuf.get(), mCurrentRequest.get(), mCurrSize);
            mCurrentRequest.swap(newBuf);
        }
        mSocket.async_read_some(boost::asio::buffer(mCurrentRequest.get() + bytes_read, mCurrSize - bytes_read),
                [this, callback, bytes_read](const boost::system::error_code& ec, size_t br){
                    if (ec) {
                        Result res;
                        callback(ec, res);
                        return;
                    }
                    readResponse<Callback, Result>(callback, bytes_read + br);
                });
    }

    template<class Res, class Callback>
    typename std::enable_if<std::is_void<Res>::value, void>::type
    error(const boost::system::error_code& ec, const Callback& callback) {
        callback(ec);
    }

    template<class Res, class Callback>
    typename std::enable_if<!std::is_void<Res>::value, void>::type
    error(const boost::system::error_code& ec, const Callback& callback) {
        Res res;
        callback(ec, res);
    }

    template<Command C, class Callback, class... Args>
    void execute(const Callback& callback, const Args&... args) {
        static_assert(
                (std::is_void<typename Signature<C>::arguments>::value && std::is_void<argsType<Args...>>::value) ||
                std::is_same<typename Signature<C>::arguments, typename argsType<Args...>::type>::value,
                "Wrong function arguments");
        using ResType = typename Signature<C>::result;
        crossbow::sizer sizer;
        sizer & sizer.size;
        sizer & C;
        impl::ArgSerializer<Args...> argSerializer;
        argSerializer.exec(sizer, args...);
        if (mCurrSize < sizer.size) {
            mCurrentRequest.reset(new uint8_t[sizer.size]);
            mCurrSize = sizer.size;
        }
        crossbow::serializer ser(mCurrentRequest.get());
        ser & sizer.size;
        ser & C;
        argSerializer.exec(ser, args...);
        ser.buffer.release();
        boost::asio::async_write(mSocket, boost::asio::buffer(mCurrentRequest.get(), sizer.size),
                    [this, callback](const boost::system::error_code& ec, size_t){
                        if (ec) {
                            error<ResType>(ec, callback);
                            return;
                        }
                        readResponse<Callback, ResType>(callback);
                    });
    }
};

template<template <typename> class Cmd_Switch,
         class Command,
         template <Command> class Signature,
         class Implementation>
class Server : public Cmd_Switch<Server<Cmd_Switch, Command, Signature, Implementation>> {
    friend struct Cmd_Switch<Server<Cmd_Switch, Command, Signature, Implementation>>;
    Implementation& mImpl;
    boost::asio::ip::tcp::socket& mSocket;
    size_t mBufSize = 1024;
    std::unique_ptr<uint8_t[]> mBuffer;
    using error_code = boost::system::error_code;
    bool doQuit = false;
public:
    Server(Implementation& impl, boost::asio::ip::tcp::socket& socket)
        : mImpl(impl)
        , mSocket(socket)
        , mBuffer(new uint8_t[mBufSize])
    {}
    void run() {
        read();
    }
    void quit() {
        doQuit = true;
    }
private:
    template<Command C, class Callback>
    typename std::enable_if<std::is_void<typename Signature<C>::arguments>::value, void>::type
    execute(Callback callback) {
        mImpl.template execute<C>(callback);
    }

    template<Command C, class Callback>
    typename std::enable_if<!std::is_void<typename Signature<C>::arguments>::value, void>::type
    execute(Callback callback) {
        using Args = typename Signature<C>::arguments;
        Args args;
        crossbow::deserializer des(mBuffer.get() + sizeof(size_t) + sizeof(Command));
        des & args;
        mImpl.template execute<C>(args, callback);
    }

    template<Command C>
    typename std::enable_if<std::is_void<typename Signature<C>::result>::value, void>::type execute() {
        execute<C>([this]() {
            // send the result back
            mBuffer[0] = 1;
            boost::asio::async_write(mSocket,
                    boost::asio::buffer(mBuffer.get(), 1),
                    [this](const error_code& ec, size_t bytes_written) {
                        if (ec) {
                            std::cerr << ec.message() << std::endl;
                            return;
                        }
                        read(0);
                    }
            );
        });
    }

    template<Command C>
    typename std::enable_if<!std::is_void<typename Signature<C>::result>::value, void>::type execute() {
        using Res = typename Signature<C>::result;
        execute<C>([this](const Res& result) {
            // Serialize result
            crossbow::sizer sizer;
            sizer & sizer.size;
            sizer & result;
            if (mBufSize < sizer.size) {
                mBuffer.reset(new uint8_t[sizer.size]);
            }
            crossbow::serializer ser(mBuffer.get());
            ser & sizer.size;
            ser & result;
            ser.buffer.release();
            // send the result back
            boost::asio::async_write(mSocket,
                    boost::asio::buffer(mBuffer.get(), sizer.size),
                    [this](const error_code& ec, size_t bytes_written) {
                        if (ec) {
                            std::cerr << ec.message() << std::endl;
                            mSocket.close();
                            mImpl.close();
                            return;
                        }
                        read(0);
                    }
            );
        });
    }
    void read(size_t bytes_read = 0) {
        if (bytes_read == 0 && doQuit) {
            mSocket.get_io_service().stop();
        }
        size_t reqSize = 0;
        if (bytes_read != 0) {
            reqSize = *reinterpret_cast<size_t*>(mBuffer.get());
        }
        if (bytes_read != 0 && reqSize == bytes_read) {
            // done reading
            auto cmd = *reinterpret_cast<Command*>(mBuffer.get() + sizeof(size_t));
            this->execute_impl(cmd);
            return;
        } else if (bytes_read >= 8 && reqSize > mBufSize) {
            std::unique_ptr<uint8_t[]> newBuf(new uint8_t[reqSize]);
            memcpy(newBuf.get(), mBuffer.get(), mBufSize);
            mBuffer.swap(newBuf);
            mBufSize = reqSize;
        }
        mSocket.async_read_some(boost::asio::buffer(mBuffer.get() + bytes_read, mBufSize - bytes_read),
                [this, bytes_read](const error_code& ec, size_t br){
                    if (ec) {
                        std::cerr << ec.message() << std::endl;
                        mSocket.close();
                        mImpl.close();
                        return;
                    }
                    read(bytes_read + br);
                });
    }
};

} // namespace protocol
} // namespace crossbow

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS sixtyfour04 (1.13.132); FILE MERGED 2006/03/15 16:14:06 cmc 1.13.132.1: #i63168# make sc 64bit happy<commit_after><|endoftext|>


<commit_before><commit_msg>renamed misleading names<commit_after><|endoftext|>


<commit_before>/***********************************************************************
 Moses - statistical machine translation system
 Copyright (C) 2006-2011 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "RuleTable/LoaderFactory.h"

#include "InputFileStream.h"
#include "RuleTable/LoaderCompact.h"
#include "RuleTable/LoaderHiero.h"
#include "RuleTable/LoaderStandard.h"
#include "UserMessage.h"
#include "Util.h"

#include <sstream>

namespace Moses
{

// Determines the rule table type by peeking inside the file then creates
// a suitable RuleTableLoader object.
std::auto_ptr<RuleTableLoader> RuleTableLoaderFactory::Create(
    const std::string &path)
{
  InputFileStream input(path);
  std::string line;
  std::getline(input, line);
  std::vector<std::string> tokens;
  Tokenize(tokens, line);
  if (tokens.size() == 1) {
    if (tokens[0] == "1") {
      return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderCompact());
    }
    std::stringstream msg;
    msg << "Unsupported compact rule table format: " << tokens[0];
    UserMessage::Add(msg.str());
    return std::auto_ptr<RuleTableLoader>();
  }
  else if (tokens[0] == "[X]" && tokens[1] == "|||") {
    return std::auto_ptr<RuleTableLoader>(new
        RuleTableLoaderHiero());

  }

  return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderStandard());
}

}  // namespace Moses
<commit_msg>fixed segfault when pt is empty<commit_after>/***********************************************************************
 Moses - statistical machine translation system
 Copyright (C) 2006-2011 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "RuleTable/LoaderFactory.h"

#include "InputFileStream.h"
#include "RuleTable/LoaderCompact.h"
#include "RuleTable/LoaderHiero.h"
#include "RuleTable/LoaderStandard.h"
#include "UserMessage.h"
#include "Util.h"

#include <sstream>
#include <iostream>

using namespace std;

namespace Moses
{

// Determines the rule table type by peeking inside the file then creates
// a suitable RuleTableLoader object.
std::auto_ptr<RuleTableLoader> RuleTableLoaderFactory::Create(
    const std::string &path)
{
  InputFileStream input(path);
  std::string line;
  bool cont = std::getline(input, line);

  if (cont) {
    std::vector<std::string> tokens;
    Tokenize(tokens, line);
    if (tokens.size() == 1) {
      if (tokens[0] == "1") {
        return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderCompact());
      }
      std::stringstream msg;
      msg << "Unsupported compact rule table format: " << tokens[0];
      UserMessage::Add(msg.str());
      return std::auto_ptr<RuleTableLoader>();
    }
    else if (tokens[0] == "[X]" && tokens[1] == "|||") {
      return std::auto_ptr<RuleTableLoader>(new
          RuleTableLoaderHiero());

    }

    return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderStandard());
  }
  else
  { // empty phrase table
    return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderStandard());
  }
}

}  // namespace Moses
<|endoftext|>


<commit_before><commit_msg>coverity#708097 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>#pragma once
/* RLTK (RogueLike Tool Kit) 1.00
 * Copyright (c) 2016-Present, Bracket Productions.
 * Licensed under the LGPL - see LICENSE file.
 *
 * Provides a wrapper for bitmap fonts.
 */

#include <functional>
#include "geometry.hpp"

namespace rltk {

namespace visibility_private {

template<class location_t_>
void internal_2d_sweep(const location_t_ &position, const location_t_ &destination, const int &range, std::function<void(location_t_)> set_visible,
	std::function<bool(location_t_)> is_opaque)
{
	bool blocked = false;
	line_func(position.x, position.y, destination.x, destination.y, [&blocked, &is_opaque, &set_visible, &range, &position] (int X, int Y) {
		float distance = distance2d(position.x, position.y, X, Y);
		if (distance <= range) {
			location_t_ pos;
			pos.x = X;
			pos.y = Y;
			if (!blocked) set_visible(pos);
			if (!is_opaque(pos)) blocked = true;
		}
	});
}

}

/* Simple all-direction visibility sweep in 2 dimensions. This requires that your location_t utilize an x and y
 * component. Parameters:
 * position - where you are sweeping from.
 * range - the number of tiles you can traverse.
 * set_visible - a callback (such as bool set_visible(location_t & loc)) to say "this is visible"
 * is_opaque - a callback to ask your map if you can see through a tile.
 */
template<class location_t_>
void visibility_sweep_2d(const location_t_ &position, const int &range, std::function<void(location_t_)> set_visible,
	std::function<bool(location_t_)> is_opaque)
{
	// You can always see yourself
	set_visible(position);

	// Box-sweep
	for (int i=0-range; i<range; ++i) {

		// Going up
		location_t_ destination;
		destination.x = position.x + i;
		destination.y = position.y - range;
		visibility_private::internal_2d_sweep(position, destination, range, set_visible, is_opaque);

		// Going down
		destination.x = position.x + i;
		destination.y = position.y + range;
		visibility_private::internal_2d_sweep(position, destination, range, set_visible, is_opaque);

		// Going left
		destination.x = position.x - range;
		destination.y = position.y + i;
		visibility_private::internal_2d_sweep(position, destination, range, set_visible, is_opaque);

		// Going right
		destination.x = position.x + range;
		destination.y = position.y + i;
		visibility_private::internal_2d_sweep(position, destination, range, set_visible, is_opaque);
	}
}

}
<commit_msg>Improve box-sweep readability by exposing an offset rather than repeatedly calculating a destination.<commit_after>#pragma once
/* RLTK (RogueLike Tool Kit) 1.00
 * Copyright (c) 2016-Present, Bracket Productions.
 * Licensed under the LGPL - see LICENSE file.
 *
 * Provides a wrapper for bitmap fonts.
 */

#include <functional>
#include "geometry.hpp"

namespace rltk {

namespace visibility_private {

template<class location_t_>
void internal_2d_sweep(const location_t_ &position, const int &range, std::function<void(location_t_)> set_visible,
	std::function<bool(location_t_)> is_opaque, const std::pair<int,int> offset)
{
	bool blocked = false;
	line_func(position.x, position.y, position.x + offset.first, position.y + offset.second, [&blocked, &is_opaque, &set_visible, &range, &position] (int X, int Y) {
		float distance = distance2d(position.x, position.y, X, Y);
		if (distance <= range) {
			location_t_ pos;
			pos.x = X;
			pos.y = Y;
			if (!blocked) set_visible(pos);
			if (!is_opaque(pos)) blocked = true;
		}
	});
}

}

/* Simple all-direction visibility sweep in 2 dimensions. This requires that your location_t utilize an x and y
 * component. Parameters:
 * position - where you are sweeping from.
 * range - the number of tiles you can traverse.
 * set_visible - a callback (such as bool set_visible(location_t & loc)) to say "this is visible"
 * is_opaque - a callback to ask your map if you can see through a tile.
 */
template<class location_t_>
void visibility_sweep_2d(const location_t_ &position, const int &range, std::function<void(location_t_)> set_visible,
	std::function<bool(location_t_)> is_opaque)
{
	// You can always see yourself
	set_visible(position);

	// Box-sweep
	for (int i=0-range; i<range; ++i) {
		visibility_private::internal_2d_sweep(position, range, set_visible, is_opaque, std::make_pair(i, 0-range));
		visibility_private::internal_2d_sweep(position, range, set_visible, is_opaque, std::make_pair(i, range));
		visibility_private::internal_2d_sweep(position, range, set_visible, is_opaque, std::make_pair(0-range, i));
		visibility_private::internal_2d_sweep(position, range, set_visible, is_opaque, std::make_pair(range, i));
	}
}

}
<|endoftext|>


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

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>

#include "hiddevice.h"
#include "rmi4update.h"

#define VERSION_MAJOR		1
#define VERSION_MINOR		3
#define VERSION_SUBMINOR	1

#define RMI4UPDATE_GETOPTS	"hfd:t:pclv"

void printHelp(const char *prog_name)
{
	fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
	fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
	fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
	fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
	fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
	fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
	fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
	fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
	fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}

void printVersion()
{
	fprintf(stdout, "rmi4update version %d.%d.%d\n",
		VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}

int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
	HIDDevice rmidevice;
	int rc = UPDATE_SUCCESS;
	std::stringstream ss;

	rc = rmidevice.Open(deviceFile);
	if (rc)
		return rc;

	rmidevice.ScanPDT(0x1);
	rmidevice.QueryBasicProperties();

	if (configid) {
		ss << std::hex << rmidevice.GetConfigID();
	} else {
		ss << rmidevice.GetFirmwareVersionMajor() << "."
			<< rmidevice.GetFirmwareVersionMinor() << "."
			<< rmidevice.GetFirmwareID();

		if (rmidevice.InBootloader())
			ss << " bootloader";
	}

	props = ss.str();

	return rc;
}

int main(int argc, char **argv)
{
	int rc;
	FirmwareImage image;
	int opt;
	int index;
	char *deviceName = NULL;
	const char *firmwareName = NULL;
	bool force = false;
	static struct option long_options[] = {
		{"help", 0, NULL, 'h'},
		{"force", 0, NULL, 'f'},
		{"device", 1, NULL, 'd'},
		{"fw-props", 0, NULL, 'p'},
		{"config-id", 0, NULL, 'c'},
		{"lockdown", 0, NULL, 'l'},
		{"version", 0, NULL, 'v'},
		{"device-type", 1, NULL, 't'},
		{0, 0, 0, 0},
	};
	bool printFirmwareProps = false;
	bool printConfigid = false;
	bool performLockdown = false;
	HIDDevice device;
	enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;

	while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
		switch (opt) {
			case 'h':
				printHelp(argv[0]);
				return 0;
			case 'f':
				force = true;
				break;
			case 'd':
				deviceName = optarg;
				break;
			case 'p':
				printFirmwareProps = true;
				break;
			case 'c':
				printFirmwareProps = true;
				printConfigid = true;
				break;
			case 'l':
				performLockdown = true;
				break;
			case 't':
				if (!strcasecmp((const char *)optarg, "touchpad"))
					deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
				else if (!strcasecmp((const char *)optarg, "touchscreen"))
					deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
				break;
			case 'v':
				printVersion();
				return 0;
			default:
				break;

		}
	}

	if (printFirmwareProps) {
		std::string props;

		if (!deviceName) {
			fprintf(stderr, "Specifiy which device to query\n");
			return 1;
		}
		rc = GetFirmwareProps(deviceName, props, printConfigid);
		if (rc) {
			fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
			return 1;
		}
		fprintf(stdout, "%s\n", props.c_str());
		return 0;
	}

	if (optind < argc) {
		firmwareName = argv[optind];
	} else {
		printHelp(argv[0]);
		return -1;
	}

	rc = image.Initialize(firmwareName);
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
		return 1;
	}

	if (deviceName) {
		 rc = device.Open(deviceName);
		 if (rc) {
			fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
				strerror(errno));
			return 1;
		}
	} else {
		if (!device.FindDevice(deviceType))
			return 1;
	}

	RMI4Update update(device, image);
	rc = update.UpdateFirmware(force, performLockdown);

	if (rc != UPDATE_SUCCESS)
	{
		device.Reset();
		return 1;
	}

	return 0;
}
<commit_msg>Update version for v1.3.2 release<commit_after>/*
 * Copyright (C) 2014 Andrew Duggan
 * Copyright (C) 2014 Synaptics Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>

#include "hiddevice.h"
#include "rmi4update.h"

#define VERSION_MAJOR		1
#define VERSION_MINOR		3
#define VERSION_SUBMINOR	2

#define RMI4UPDATE_GETOPTS	"hfd:t:pclv"

void printHelp(const char *prog_name)
{
	fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
	fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
	fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
	fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
	fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
	fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
	fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
	fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
	fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}

void printVersion()
{
	fprintf(stdout, "rmi4update version %d.%d.%d\n",
		VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}

int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
	HIDDevice rmidevice;
	int rc = UPDATE_SUCCESS;
	std::stringstream ss;

	rc = rmidevice.Open(deviceFile);
	if (rc)
		return rc;

	rmidevice.ScanPDT(0x1);
	rmidevice.QueryBasicProperties();

	if (configid) {
		ss << std::hex << rmidevice.GetConfigID();
	} else {
		ss << rmidevice.GetFirmwareVersionMajor() << "."
			<< rmidevice.GetFirmwareVersionMinor() << "."
			<< rmidevice.GetFirmwareID();

		if (rmidevice.InBootloader())
			ss << " bootloader";
	}

	props = ss.str();

	return rc;
}

int main(int argc, char **argv)
{
	int rc;
	FirmwareImage image;
	int opt;
	int index;
	char *deviceName = NULL;
	const char *firmwareName = NULL;
	bool force = false;
	static struct option long_options[] = {
		{"help", 0, NULL, 'h'},
		{"force", 0, NULL, 'f'},
		{"device", 1, NULL, 'd'},
		{"fw-props", 0, NULL, 'p'},
		{"config-id", 0, NULL, 'c'},
		{"lockdown", 0, NULL, 'l'},
		{"version", 0, NULL, 'v'},
		{"device-type", 1, NULL, 't'},
		{0, 0, 0, 0},
	};
	bool printFirmwareProps = false;
	bool printConfigid = false;
	bool performLockdown = false;
	HIDDevice device;
	enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;

	while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
		switch (opt) {
			case 'h':
				printHelp(argv[0]);
				return 0;
			case 'f':
				force = true;
				break;
			case 'd':
				deviceName = optarg;
				break;
			case 'p':
				printFirmwareProps = true;
				break;
			case 'c':
				printFirmwareProps = true;
				printConfigid = true;
				break;
			case 'l':
				performLockdown = true;
				break;
			case 't':
				if (!strcasecmp((const char *)optarg, "touchpad"))
					deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
				else if (!strcasecmp((const char *)optarg, "touchscreen"))
					deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
				break;
			case 'v':
				printVersion();
				return 0;
			default:
				break;

		}
	}

	if (printFirmwareProps) {
		std::string props;

		if (!deviceName) {
			fprintf(stderr, "Specifiy which device to query\n");
			return 1;
		}
		rc = GetFirmwareProps(deviceName, props, printConfigid);
		if (rc) {
			fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
			return 1;
		}
		fprintf(stdout, "%s\n", props.c_str());
		return 0;
	}

	if (optind < argc) {
		firmwareName = argv[optind];
	} else {
		printHelp(argv[0]);
		return -1;
	}

	rc = image.Initialize(firmwareName);
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
		return 1;
	}

	if (deviceName) {
		 rc = device.Open(deviceName);
		 if (rc) {
			fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
				strerror(errno));
			return 1;
		}
	} else {
		if (!device.FindDevice(deviceType))
			return 1;
	}

	RMI4Update update(device, image);
	rc = update.UpdateFirmware(force, performLockdown);

	if (rc != UPDATE_SUCCESS)
	{
		device.Reset();
		return 1;
	}

	return 0;
}
<|endoftext|>


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

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>

#include "hiddevice.h"
#include "rmi4update.h"

#define VERSION_MAJOR		1
#define VERSION_MINOR		2
#define VERSION_SUBMINOR	7

#define RMI4UPDATE_GETOPTS	"hfd:pclv"

void printHelp(const char *prog_name)
{
	fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
	fprintf(stdout, "\t-h, --help\tPrint this message\n");
	fprintf(stdout, "\t-f, --force\tForce updating firmware even it the image provided is older\n\t\t\tthen the current firmware on the device.\n");
	fprintf(stdout, "\t-d, --device\thidraw device file associated with the device being updated.\n");
	fprintf(stdout, "\t-p, --fw-props\tPrint the firmware properties.\n");
	fprintf(stdout, "\t-c, --config-id\tPrint the config id.\n");
	fprintf(stdout, "\t-l, --lockdown\tPerform lockdown.\n");
	fprintf(stdout, "\t-v, --version\tPrint version number.\n");
}

void printVersion()
{
	fprintf(stdout, "rmi4update version %d.%d.%d\n",
		VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}

int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
	HIDDevice rmidevice;
	int rc = UPDATE_SUCCESS;
	std::stringstream ss;

	rc = rmidevice.Open(deviceFile);
	if (rc)
		return rc;

	rmidevice.ScanPDT(0x1);
	rmidevice.QueryBasicProperties();

	if (configid) {
		ss << std::hex << rmidevice.GetConfigID();
	} else {
		ss << rmidevice.GetFirmwareVersionMajor() << "."
			<< rmidevice.GetFirmwareVersionMinor() << "."
			<< std::hex << rmidevice.GetFirmwareID();

		if (rmidevice.InBootloader())
			ss << " bootloader";
	}

	props = ss.str();

	return rc;
}

int main(int argc, char **argv)
{
	int rc;
	FirmwareImage image;
	int opt;
	int index;
	char *deviceName = NULL;
	const char *firmwareName = NULL;
	bool force = false;
	static struct option long_options[] = {
		{"help", 0, NULL, 'h'},
		{"force", 0, NULL, 'f'},
		{"device", 1, NULL, 'd'},
		{"fw-props", 0, NULL, 'p'},
		{"config-id", 0, NULL, 'c'},
		{"lockdown", 0, NULL, 'l'},
		{"version", 0, NULL, 'v'},
		{0, 0, 0, 0},
	};
	bool printFirmwareProps = false;
	bool printConfigid = false;
	bool performLockdown = false;
	HIDDevice device;

	while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
		switch (opt) {
			case 'h':
				printHelp(argv[0]);
				return 0;
			case 'f':
				force = true;
				break;
			case 'd':
				deviceName = optarg;
				break;
			case 'p':
				printFirmwareProps = true;
				break;
			case 'c':
				printFirmwareProps = true;
				printConfigid = true;
				break;
			case 'l':
				performLockdown = true;
				break;
			case 'v':
				printVersion();
				return 0;
			default:
				break;

		}
	}

	if (printFirmwareProps) {
		std::string props;

		if (!deviceName) {
			fprintf(stderr, "Specifiy which device to query\n");
			return 1;
		}
		rc = GetFirmwareProps(deviceName, props, printConfigid);
		if (rc) {
			fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
			return 1;
		}
		fprintf(stdout, "%s\n", props.c_str());
		return 0;
	}

	if (optind < argc) {
		firmwareName = argv[optind];
	} else {
		printHelp(argv[0]);
		return -1;
	}

	rc = image.Initialize(firmwareName);
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
		return 1;
	}

	if (deviceName) {
		 rc = device.Open(deviceName);
		 if (rc) {
			fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
				strerror(errno));
			return 1;
		}
		//device.SetTransportDevice(deviceName);
		//device.g_transportDeviceName = deviceName;	// leon
	} else {
		if (!device.FindDevice())
			return 1;
	}

	RMI4Update update(device, image);
	rc = update.UpdateFirmware(force, performLockdown);

	return rc == UPDATE_SUCCESS ? 0 : 1;
}
<commit_msg>update version to v1.2.8<commit_after>/*
 * Copyright (C) 2014 Andrew Duggan
 * Copyright (C) 2014 Synaptics Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>

#include "hiddevice.h"
#include "rmi4update.h"

#define VERSION_MAJOR		1
#define VERSION_MINOR		2
#define VERSION_SUBMINOR	8

#define RMI4UPDATE_GETOPTS	"hfd:pclv"

void printHelp(const char *prog_name)
{
	fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
	fprintf(stdout, "\t-h, --help\tPrint this message\n");
	fprintf(stdout, "\t-f, --force\tForce updating firmware even it the image provided is older\n\t\t\tthen the current firmware on the device.\n");
	fprintf(stdout, "\t-d, --device\thidraw device file associated with the device being updated.\n");
	fprintf(stdout, "\t-p, --fw-props\tPrint the firmware properties.\n");
	fprintf(stdout, "\t-c, --config-id\tPrint the config id.\n");
	fprintf(stdout, "\t-l, --lockdown\tPerform lockdown.\n");
	fprintf(stdout, "\t-v, --version\tPrint version number.\n");
}

void printVersion()
{
	fprintf(stdout, "rmi4update version %d.%d.%d\n",
		VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}

int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
	HIDDevice rmidevice;
	int rc = UPDATE_SUCCESS;
	std::stringstream ss;

	rc = rmidevice.Open(deviceFile);
	if (rc)
		return rc;

	rmidevice.ScanPDT(0x1);
	rmidevice.QueryBasicProperties();

	if (configid) {
		ss << std::hex << rmidevice.GetConfigID();
	} else {
		ss << rmidevice.GetFirmwareVersionMajor() << "."
			<< rmidevice.GetFirmwareVersionMinor() << "."
			<< std::hex << rmidevice.GetFirmwareID();

		if (rmidevice.InBootloader())
			ss << " bootloader";
	}

	props = ss.str();

	return rc;
}

int main(int argc, char **argv)
{
	int rc;
	FirmwareImage image;
	int opt;
	int index;
	char *deviceName = NULL;
	const char *firmwareName = NULL;
	bool force = false;
	static struct option long_options[] = {
		{"help", 0, NULL, 'h'},
		{"force", 0, NULL, 'f'},
		{"device", 1, NULL, 'd'},
		{"fw-props", 0, NULL, 'p'},
		{"config-id", 0, NULL, 'c'},
		{"lockdown", 0, NULL, 'l'},
		{"version", 0, NULL, 'v'},
		{0, 0, 0, 0},
	};
	bool printFirmwareProps = false;
	bool printConfigid = false;
	bool performLockdown = false;
	HIDDevice device;

	while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
		switch (opt) {
			case 'h':
				printHelp(argv[0]);
				return 0;
			case 'f':
				force = true;
				break;
			case 'd':
				deviceName = optarg;
				break;
			case 'p':
				printFirmwareProps = true;
				break;
			case 'c':
				printFirmwareProps = true;
				printConfigid = true;
				break;
			case 'l':
				performLockdown = true;
				break;
			case 'v':
				printVersion();
				return 0;
			default:
				break;

		}
	}

	if (printFirmwareProps) {
		std::string props;

		if (!deviceName) {
			fprintf(stderr, "Specifiy which device to query\n");
			return 1;
		}
		rc = GetFirmwareProps(deviceName, props, printConfigid);
		if (rc) {
			fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
			return 1;
		}
		fprintf(stdout, "%s\n", props.c_str());
		return 0;
	}

	if (optind < argc) {
		firmwareName = argv[optind];
	} else {
		printHelp(argv[0]);
		return -1;
	}

	rc = image.Initialize(firmwareName);
	if (rc != UPDATE_SUCCESS) {
		fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
		return 1;
	}

	if (deviceName) {
		 rc = device.Open(deviceName);
		 if (rc) {
			fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
				strerror(errno));
			return 1;
		}
		//device.SetTransportDevice(deviceName);
		//device.g_transportDeviceName = deviceName;	// leon
	} else {
		if (!device.FindDevice())
			return 1;
	}

	RMI4Update update(device, image);
	rc = update.UpdateFirmware(force, performLockdown);

	return rc == UPDATE_SUCCESS ? 0 : 1;
}
<|endoftext|>