<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.

   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 "paddle/fluid/operators/activation_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace framework {
class Tensor;
}  // namespace framework
namespace platform {
class MKLDNNDeviceContext;
}  // namespace platform
}  // namespace paddle

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::Tensor;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::stream;
using platform::GetMKLDNNFormat;
using platform::MKLDNNDeviceContext;
using platform::to_void_cast;

template <typename Functor>
class MKLDNNActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *x = ctx.Input<Tensor>("X");
    PADDLE_ENFORCE_EQ(
        x->layout(), DataLayout::kMKLDNN,
        platform::errors::InvalidArgument("Wrong layout set for X tensor"));
    PADDLE_ENFORCE_NE(
        x->format(), MKLDNNMemoryFormat::undef,
        platform::errors::InvalidArgument("Wrong format set for X tensor"));

    Functor functor;
    functor(ctx);
  }
};

template <typename Functor>
class MKLDNNActivationGradKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
    PADDLE_ENFORCE_EQ(diff_y->layout(), DataLayout::kMKLDNN,
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input OutGrad tensor"));
    PADDLE_ENFORCE_NE(diff_y->format(), MKLDNNMemoryFormat::undef,
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input OutGrad tensor"));

    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
                     mkldnn::algorithm algorithm) {
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Output<Tensor>("Out");

  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<float>("threshold");
  }

  PADDLE_ENFORCE(
      x->dims().size() == 2 || x->dims().size() == 3 || x->dims().size() == 4,
      platform::errors::Unimplemented("Input dim must be with 2, 3 or 4"));

  auto src_tz = framework::vectorize<int64_t>(x->dims());

  auto src_format = src_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();

  platform::ActivationMKLDNNHandler<T> handler(
      src_tz, algorithm, alpha, beta, src_format, dev_ctx, ctx.GetPlace(),
      ctx.InputName("X"));

  auto src_memory_p = handler.AcquireSrcMemory(x);
  auto dst_memory_p =
      x->IsSharedBufferWith(*y) ? src_memory_p : handler.AcquireDstMemory(y);
  auto activation_p = handler.AcquireForwardPrimitive();

  mkldnn::stream astream(dev_ctx.GetEngine());
  activation_p->execute(astream, {{MKLDNN_ARG_FROM, *src_memory_p},
                                  {MKLDNN_ARG_TO, *dst_memory_p}});
  astream.wait();

  y->set_layout(DataLayout::kMKLDNN);
  y->set_format(GetMKLDNNFormat(*dst_memory_p));
}

template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
                  mkldnn::algorithm algorithm) {
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

  const auto *x = ctx.Input<Tensor>("X");
  const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *diff_x = ctx.Output<Tensor>(framework::GradVarName("X"));

  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<float>("threshold");
  }

  auto diff_dst_tz = framework::vectorize<int64_t>(diff_y->dims());

  // diff_dst and src dims should be the same
  auto src_format =
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();

  auto diff_y_format =
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : diff_y->format();

  platform::ActivationMKLDNNHandler<T> handler(
      diff_dst_tz, algorithm, alpha, beta, src_format, diff_y_format, dev_ctx,
      ctx.GetPlace(), ctx.InputName("X"));

  auto src_memory_p = handler.AcquireBackwardSrcMemory(x);
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(diff_y);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(diff_x);
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

  mkldnn::stream astream(dev_ctx.GetEngine());
  activation_backward_p->execute(astream,
                                 {{MKLDNN_ARG_SRC, *src_memory_p},
                                  {MKLDNN_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {MKLDNN_ARG_DIFF_SRC, *diff_src_memory_p}});
  astream.wait();

  diff_x->set_layout(DataLayout::kMKLDNN);
  diff_x->set_format(GetMKLDNNFormat(*diff_src_memory_p));
}

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    eltwise_forward<T>(ctx, algorithm);
  }
};

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    eltwise_grad<T>(ctx, algorithm);
  }
};

template <typename T>
struct GeluMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
      eltwise_forward<T>(ctx, mkldnn::algorithm::eltwise_gelu_tanh);
    } else {
      eltwise_forward<T>(ctx, mkldnn::algorithm::eltwise_gelu_erf);
    }
  }
};

template <typename T>
struct GeluMKLDNNGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_tanh);
    } else {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_erf);
    }
  }
};

template <typename T>
using ReluMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_relu>;

template <typename T>
using Relu6MKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

template <typename T>
using SwishMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_swish>;

template <typename T>
using SigmoidMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_logistic>;

template <typename T>
using TanhMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
using SqrtMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
using AbsMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_abs>;

template <typename T>
using ReluMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_relu>;

template <typename T>
using Relu6MKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

template <typename T>
using SwishMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_swish>;

template <typename T>
using SigmoidMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_logistic>;

template <typename T>
using TanhMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
using SqrtMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
using AbsMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_abs>;
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

#define REGISTER_ACTIVATION_MKLDNN_KERNEL(act_type, functor, grad_functor) \
  REGISTER_OP_KERNEL(act_type, MKLDNN, ::paddle::platform::CPUPlace,       \
                     ops::MKLDNNActivationKernel<ops::functor<float>>);    \
  REGISTER_OP_KERNEL(                                                      \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,               \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

#define REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(act_type, functor,             \
                                               grad_functor)                  \
  REGISTER_OP_KERNEL(                                                         \
      act_type, MKLDNN, ::paddle::platform::CPUPlace,                         \
      ops::MKLDNNActivationKernel<ops::functor<float>>,                       \
      ops::MKLDNNActivationKernel<ops::functor<paddle::platform::bfloat16>>); \
  REGISTER_OP_KERNEL(                                                         \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,                  \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                     \
  __macro(relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);          \
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);       \
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);    \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);       \
  __macro(sigmoid, SigmoidMKLDNNFunctor, SigmoidMKLDNNGradFunctor); \
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradFunctor);          \
  __macro(sqrt, SqrtMKLDNNFunctor, SqrtMKLDNNGradFunctor);          \
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(gelu, GeluMKLDNNFunctor,
                                       GeluMKLDNNGradFunctor);
<commit_msg>correct the allowed dimension size (#30326)<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.

   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 "paddle/fluid/operators/activation_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace framework {
class Tensor;
}  // namespace framework
namespace platform {
class MKLDNNDeviceContext;
}  // namespace platform
}  // namespace paddle

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::Tensor;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::stream;
using platform::GetMKLDNNFormat;
using platform::MKLDNNDeviceContext;
using platform::to_void_cast;

template <typename Functor>
class MKLDNNActivationKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *x = ctx.Input<Tensor>("X");
    PADDLE_ENFORCE_EQ(
        x->layout(), DataLayout::kMKLDNN,
        platform::errors::InvalidArgument("Wrong layout set for X tensor"));
    PADDLE_ENFORCE_NE(
        x->format(), MKLDNNMemoryFormat::undef,
        platform::errors::InvalidArgument("Wrong format set for X tensor"));

    Functor functor;
    functor(ctx);
  }
};

template <typename Functor>
class MKLDNNActivationGradKernel
    : public framework::OpKernel<typename Functor::ELEMENT_TYPE> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
    PADDLE_ENFORCE_EQ(diff_y->layout(), DataLayout::kMKLDNN,
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input OutGrad tensor"));
    PADDLE_ENFORCE_NE(diff_y->format(), MKLDNNMemoryFormat::undef,
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input OutGrad tensor"));

    Functor functor;
    functor(ctx);
  }
};

template <typename T>
void eltwise_forward(const framework::ExecutionContext &ctx,
                     mkldnn::algorithm algorithm) {
  PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                    paddle::platform::errors::PreconditionNotMet(
                        "Operator DNNL eletwise_forward must use CPUPlace"));
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

  const auto *x = ctx.Input<Tensor>("X");
  auto *y = ctx.Output<Tensor>("Out");

  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<float>("threshold");
  }

  PADDLE_ENFORCE(
      x->dims().size() >= 1 || x->dims().size() <= 6,
      platform::errors::Unimplemented("Input dimension size can be 1, 2, 3, 4, "
                                      "5, or 6, but now the dimension size is",
                                      x->dims().size()));

  auto src_tz = framework::vectorize<int64_t>(x->dims());

  auto src_format = src_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();

  platform::ActivationMKLDNNHandler<T> handler(
      src_tz, algorithm, alpha, beta, src_format, dev_ctx, ctx.GetPlace(),
      ctx.InputName("X"));

  auto src_memory_p = handler.AcquireSrcMemory(x);
  auto dst_memory_p =
      x->IsSharedBufferWith(*y) ? src_memory_p : handler.AcquireDstMemory(y);
  auto activation_p = handler.AcquireForwardPrimitive();

  mkldnn::stream astream(dev_ctx.GetEngine());
  activation_p->execute(astream, {{MKLDNN_ARG_FROM, *src_memory_p},
                                  {MKLDNN_ARG_TO, *dst_memory_p}});
  astream.wait();

  y->set_layout(DataLayout::kMKLDNN);
  y->set_format(GetMKLDNNFormat(*dst_memory_p));
}

template <typename T>
void eltwise_grad(const framework::ExecutionContext &ctx,
                  mkldnn::algorithm algorithm) {
  auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

  const auto *x = ctx.Input<Tensor>("X");
  const auto *diff_y = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto *diff_x = ctx.Output<Tensor>(framework::GradVarName("X"));

  float alpha = ctx.HasAttr("alpha") ? ctx.Attr<float>("alpha") : 0;
  float beta = ctx.HasAttr("beta") ? ctx.Attr<float>("beta") : 0;

  // paddle uses beta but mkldnn uses alpha for swish
  if (algorithm == mkldnn::algorithm::eltwise_swish) {
    std::swap(alpha, beta);
  } else if (algorithm == dnnl::algorithm::eltwise_bounded_relu) {
    alpha = ctx.Attr<float>("threshold");
  }

  auto diff_dst_tz = framework::vectorize<int64_t>(diff_y->dims());

  // diff_dst and src dims should be the same
  auto src_format =
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : x->format();

  auto diff_y_format =
      diff_dst_tz.size() == 2 ? MKLDNNMemoryFormat::nc : diff_y->format();

  platform::ActivationMKLDNNHandler<T> handler(
      diff_dst_tz, algorithm, alpha, beta, src_format, diff_y_format, dev_ctx,
      ctx.GetPlace(), ctx.InputName("X"));

  auto src_memory_p = handler.AcquireBackwardSrcMemory(x);
  auto diff_dst_memory_p = handler.AcquireDiffDstMemory(diff_y);
  auto diff_src_memory_p = handler.AcquireDiffSrcMemory(diff_x);
  auto activation_backward_p = handler.AcquireBackwardPrimitive();

  mkldnn::stream astream(dev_ctx.GetEngine());
  activation_backward_p->execute(astream,
                                 {{MKLDNN_ARG_SRC, *src_memory_p},
                                  {MKLDNN_ARG_DIFF_DST, *diff_dst_memory_p},
                                  {MKLDNN_ARG_DIFF_SRC, *diff_src_memory_p}});
  astream.wait();

  diff_x->set_layout(DataLayout::kMKLDNN);
  diff_x->set_format(GetMKLDNNFormat(*diff_src_memory_p));
}

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationFunc : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    eltwise_forward<T>(ctx, algorithm);
  }
};

template <typename T, mkldnn::algorithm algorithm>
struct MKLDNNActivationGradFunc : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    eltwise_grad<T>(ctx, algorithm);
  }
};

template <typename T>
struct GeluMKLDNNFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
      eltwise_forward<T>(ctx, mkldnn::algorithm::eltwise_gelu_tanh);
    } else {
      eltwise_forward<T>(ctx, mkldnn::algorithm::eltwise_gelu_erf);
    }
  }
};

template <typename T>
struct GeluMKLDNNGradFunctor : public BaseActivationFunctor<T> {
  void operator()(const framework::ExecutionContext &ctx) const {
    const bool approximate = ctx.Attr<bool>("approximate");
    if (approximate) {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_tanh);
    } else {
      eltwise_grad<T>(ctx, mkldnn::algorithm::eltwise_gelu_erf);
    }
  }
};

template <typename T>
using ReluMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_relu>;

template <typename T>
using Relu6MKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

template <typename T>
using SwishMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_swish>;

template <typename T>
using SigmoidMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_logistic>;

template <typename T>
using TanhMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
using SqrtMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
using AbsMKLDNNFunctor =
    MKLDNNActivationFunc<T, mkldnn::algorithm::eltwise_abs>;

template <typename T>
using ReluMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_relu>;

template <typename T>
using Relu6MKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_bounded_relu>;

template <typename T>
using SwishMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_swish>;

template <typename T>
using SigmoidMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_logistic>;

template <typename T>
using TanhMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_tanh>;

template <typename T>
using SqrtMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_sqrt>;

template <typename T>
using AbsMKLDNNGradFunctor =
    MKLDNNActivationGradFunc<T, mkldnn::algorithm::eltwise_abs>;
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

#define REGISTER_ACTIVATION_MKLDNN_KERNEL(act_type, functor, grad_functor) \
  REGISTER_OP_KERNEL(act_type, MKLDNN, ::paddle::platform::CPUPlace,       \
                     ops::MKLDNNActivationKernel<ops::functor<float>>);    \
  REGISTER_OP_KERNEL(                                                      \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,               \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

#define REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(act_type, functor,             \
                                               grad_functor)                  \
  REGISTER_OP_KERNEL(                                                         \
      act_type, MKLDNN, ::paddle::platform::CPUPlace,                         \
      ops::MKLDNNActivationKernel<ops::functor<float>>,                       \
      ops::MKLDNNActivationKernel<ops::functor<paddle::platform::bfloat16>>); \
  REGISTER_OP_KERNEL(                                                         \
      act_type##_grad, MKLDNN, ::paddle::platform::CPUPlace,                  \
      ops::MKLDNNActivationGradKernel<ops::grad_functor<float>>);

#define FOR_EACH_MKLDNN_KERNEL_FUNCTOR(__macro)                     \
  __macro(relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);          \
  __macro(relu6, Relu6MKLDNNFunctor, Relu6MKLDNNGradFunctor);       \
  __macro(leaky_relu, ReluMKLDNNFunctor, ReluMKLDNNGradFunctor);    \
  __macro(swish, SwishMKLDNNFunctor, SwishMKLDNNGradFunctor);       \
  __macro(sigmoid, SigmoidMKLDNNFunctor, SigmoidMKLDNNGradFunctor); \
  __macro(tanh, TanhMKLDNNFunctor, TanhMKLDNNGradFunctor);          \
  __macro(sqrt, SqrtMKLDNNFunctor, SqrtMKLDNNGradFunctor);          \
  __macro(abs, AbsMKLDNNFunctor, AbsMKLDNNGradFunctor);

FOR_EACH_MKLDNN_KERNEL_FUNCTOR(REGISTER_ACTIVATION_MKLDNN_KERNEL);
REGISTER_ACTIVATION_MKLDNN_BF16_KERNEL(gelu, GeluMKLDNNFunctor,
                                       GeluMKLDNNGradFunctor);
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_htm_adu_ctrl.C $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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_htm_adu_ctrl.C
///
/// @brief Provides ADU control functions that help with HTM collection actions.
///
///----------------------------------------------------------------------------
/// *HWP HWP Owner   : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : Nest
/// *HWP Level       : 2
/// *HWP Consumed by : HB
///----------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_htm_adu_ctrl.H>
#include <p9_adu_coherent_utils.H>

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
// Status time-out
const uint32_t P9_HTM_START_MAX_STATUS_POLLS = 100;

///
/// See doxygen in p9_htm_adu_ctrl.H
///
fapi2::ReturnCode aduNHTMControl(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_addr)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;
    uint8_t l_num_attempts = 2;
    bool l_adu_is_dirty = false;
    uint32_t l_num_polls = 0;
    bool l_busy_bit_status = false;
    adu_status_busy_handler l_busy_handling = EXIT_ON_BUSY;

    // validate input action, set ADU operation parameters
    p9_ADU_oper_flag l_adu_oper_flag;

    // Setup ADU operation
    l_adu_oper_flag.setOperationType(p9_ADU_oper_flag::PMISC_OPER);
    l_adu_oper_flag.setTransactionSize(p9_ADU_oper_flag::TSIZE_2);

    // Acquire ADU lock
    l_rc = p9_adu_coherent_manage_lock( i_target,
                                        false,
                                        true,           // Acquire lock
                                        l_num_attempts);

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_manage_lock (acquire all)");
        goto fapi_try_exit;
    }

    // NOTE: lock is now held, if an operation fails from this point
    //       to the end of the procedure.
    // Reset lock
    l_adu_is_dirty = true;
    // Reset ADU
    l_rc = p9_adu_coherent_utils_reset_adu(i_target);

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_utils_reset_adu (acquire all)");
        goto adu_reset_unlock;
    }

    // issue operation
    l_rc = p9_adu_coherent_setup_adu(i_target,
                                     i_addr,
                                     false,      // write
                                     l_adu_oper_flag.setFlag());

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_setup_adu (op)");
        goto adu_reset_unlock;
    }

    // Check status
    // Wait for operation to be completed (busy bit cleared)
    l_busy_bit_status = false;

    while (l_num_polls < P9_HTM_START_MAX_STATUS_POLLS)
    {
        l_rc = p9_adu_coherent_status_check(i_target,
                                            l_busy_handling,
                                            true,
                                            l_busy_bit_status);

        if (l_rc)
        {
            FAPI_ERR("p9_adu_coherent_status_check() returns error");
            goto adu_reset_unlock;
        }

        if (l_busy_bit_status == true)
        {
            l_num_polls++;

            // last try, set handler to expect busy bit clear, if not then
            // p9_adu_coherent_status_check() will log an error so that
            // we don't have to deal with the error separately here.
            if (l_num_polls == (P9_HTM_START_MAX_STATUS_POLLS - 1))
            {
                l_busy_handling = EXPECTED_BUSY_BIT_CLEAR;
            }
        }
        else
        {
            // Operation done, break out
            break;
        }
    }

    // Unlock ADUs
    FAPI_DBG("Operation complete, releasing lock for all ADU units in drawer");
    l_rc = p9_adu_coherent_manage_lock(i_target,
                                       false,
                                       false, // Release lock
                                       l_num_attempts);

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_manage_lock (release all)");
        goto adu_reset_unlock;
    }

    FAPI_DBG("All ADU locks released");
    // no error for entire operation
    l_adu_is_dirty = false;

adu_reset_unlock:

    // if error has occurred and any ADU is dirty,
    // attempt to reset all ADUs and free locks (propogate rc of original fail)
    if (l_rc && l_adu_is_dirty)
    {
        FAPI_INF("Attempting to reset/free lock on all ADUs");
        // Unlock ADUs
        // ignore return codes
        (void) p9_adu_coherent_utils_reset_adu(i_target);
        (void) p9_adu_coherent_manage_lock(i_target,
                                           false, // No lock pick
                                           false, // Lock release
                                           1);    // Attempt 1 time
    }

fapi_try_exit:
    FAPI_DBG("Exiting");
    return l_rc;
}
<commit_msg>L3 update -- p9_htm_setup/pause/start/stop HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_htm_adu_ctrl.C $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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_htm_adu_ctrl.C
///
/// @brief Provides ADU control functions that help with HTM collection actions.
///
///----------------------------------------------------------------------------
/// *HWP HWP Owner   : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : Nest
/// *HWP Level       : 3
/// *HWP Consumed by : HB
///----------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_htm_adu_ctrl.H>
#include <p9_adu_coherent_utils.H>

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
// Status time-out
const uint32_t P9_HTM_START_MAX_STATUS_POLLS = 100;

///
/// See doxygen in p9_htm_adu_ctrl.H
///
fapi2::ReturnCode aduNHTMControl(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint64_t i_addr)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;
    uint8_t l_num_attempts = 2;
    bool l_adu_is_dirty = false;
    uint32_t l_num_polls = 0;
    bool l_busy_bit_status = false;
    adu_status_busy_handler l_busy_handling = EXIT_ON_BUSY;

    // validate input action, set ADU operation parameters
    p9_ADU_oper_flag l_adu_oper_flag;

    // Setup ADU operation
    l_adu_oper_flag.setOperationType(p9_ADU_oper_flag::PMISC_OPER);
    l_adu_oper_flag.setTransactionSize(p9_ADU_oper_flag::TSIZE_2);

    // Acquire ADU lock
    FAPI_TRY(p9_adu_coherent_manage_lock( i_target,
                                          false,
                                          true,           // Acquire lock
                                          l_num_attempts),
             "Error from p9_adu_coherent_manage_lock (acquire all)");

    // NOTE: lock is now held, if an operation fails from this point
    //       to the end of the procedure, need to reset and unlock.
    l_adu_is_dirty = true;

    // Reset ADU
    l_rc = p9_adu_coherent_utils_reset_adu(i_target);

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_utils_reset_adu (acquire all)");
        goto adu_reset_unlock;
    }

    // Issue operation
    l_rc = p9_adu_coherent_setup_adu(i_target,
                                     i_addr,
                                     false,      // write
                                     l_adu_oper_flag.setFlag());

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_setup_adu (op)");
        goto adu_reset_unlock;
    }

    // Check status
    // Wait for operation to be completed (busy bit cleared)
    l_busy_bit_status = false;

    while (l_num_polls < P9_HTM_START_MAX_STATUS_POLLS)
    {
        l_rc = p9_adu_coherent_status_check(i_target,
                                            l_busy_handling,
                                            true,
                                            l_busy_bit_status);

        if (l_rc)
        {
            FAPI_ERR("p9_adu_coherent_status_check() returns error");
            goto adu_reset_unlock;
        }

        if (l_busy_bit_status == true)
        {
            l_num_polls++;

            // last try, set handler to expect busy bit clear, if not then
            // p9_adu_coherent_status_check() will log an error so that
            // we don't have to deal with the error separately here.
            if (l_num_polls == (P9_HTM_START_MAX_STATUS_POLLS - 1))
            {
                l_busy_handling = EXPECTED_BUSY_BIT_CLEAR;
            }
        }
        else
        {
            // Operation done, break out
            break;
        }
    }

    // Unlock ADUs
    FAPI_DBG("Operation complete, releasing lock for all ADU units in drawer");
    l_rc = p9_adu_coherent_manage_lock(i_target,
                                       false,
                                       false, // Release lock
                                       l_num_attempts);

    if (l_rc)
    {
        FAPI_ERR("Error from p9_adu_coherent_manage_lock (release all)");
        goto adu_reset_unlock;
    }

    FAPI_DBG("All ADU locks released");
    // No error for entire operation
    l_adu_is_dirty = false;

adu_reset_unlock:

    // if error has occurred and any ADU is dirty,
    // attempt to reset all ADUs and free locks (propogate rc of original fail)
    if (l_rc && l_adu_is_dirty)
    {
        FAPI_INF("Attempting to reset/free lock on all ADUs");
        // Unlock ADUs
        // ignore return codes
        (void) p9_adu_coherent_utils_reset_adu(i_target);
        (void) p9_adu_coherent_manage_lock(i_target,
                                           false, // No lock pick
                                           false, // Lock release
                                           1);    // Attempt 1 time
    }

fapi_try_exit:
    FAPI_DBG("Exiting");
    return l_rc;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: minterfacemgrimpl.hpp
//
// Desc: Interface manager for Data Mining.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_INTERFACE_MGR_IMPL_HPP__
#define __M_INTERFACE_MGR_IMPL_HPP__

inline MiningInterfaceMgr::MiningInterfaceMgr(u32 id,
			Factory &pFactory, MiningInterface * pDevice)
:m_id(id), m_pDevice(pDevice), m_pFactory(pFactory)
{
	Init();
}
inline MiningInterfaceMgr::~MiningInterfaceMgr()
{
}

inline BOOL MiningInterfaceMgr::Init()
{
	/* Reg the data callback from factory */
	MMReqStream type = MM_STREAM_LAST;
	m_pDevice->GetReqStream( type);
	/* Current we only use sub raw stream */
	if (type & MM_STREAM_SUB_RAW != 0)
	{
		m_pFactory.RegSubRawCallback(m_id,
			(DeviceRawCallbackFunctionPtr)MiningInterfaceMgr::RawHandler,
				(void *)this);
	}

	if (type & MM_STREAM_SEQ != 0)
	{
		m_pFactory.RegSeqCallback(m_id,
			(DeviceSeqCallbackFunctionPtr)MiningInterfaceMgr::SeqHandler,
				(void *)this);
	}
	//TODO add callback RetCallback from process module
	return TRUE;
}

inline void MiningInterfaceMgr::RawHandler1(RawFrame& frame)
{
	m_pDevice->ProcessRaw(frame);
}

inline void MiningInterfaceMgr::RawHandler(RawFrame& frame, void * pParam)
{
    MiningInterfaceMgr *pMgr = static_cast<MiningInterfaceMgr *> (pParam);

    return pMgr->RawHandler1(frame);
}

inline void MiningInterfaceMgr::SeqHandler1(VideoSeqFrame& frame)
{
	m_pDevice->ProcessSeq(frame);
}

inline void MiningInterfaceMgr::SeqHandler(VideoSeqFrame& frame, void * pParam)
{
    MiningInterfaceMgr *pMgr = static_cast<MiningInterfaceMgr *> (pParam);

    return pMgr->SeqHandler1(frame);
}

#endif /* __M_INTERFACE_MGR_IMPL_HPP__ */
<commit_msg>add device status callback<commit_after>//------------------------------------------------------------------------------
// File: minterfacemgrimpl.hpp
//
// Desc: Interface manager for Data Mining.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_INTERFACE_MGR_IMPL_HPP__
#define __M_INTERFACE_MGR_IMPL_HPP__

inline MiningInterfaceMgr::MiningInterfaceMgr(u32 id,
			Factory &pFactory, MiningInterface * pDevice)
:m_id(id), m_pDevice(pDevice), m_pFactory(pFactory),
 m_type(MM_STREAM_LAST)
{
	Init();
}
inline MiningInterfaceMgr::~MiningInterfaceMgr()
{
	Cleanup();
}

inline BOOL MiningInterfaceMgr::Init()
{
	/* Reg the data callback from factory */

	m_pDevice->GetReqStream( m_type);
	/* Current we only use sub raw stream */
	if ((m_type & MM_STREAM_SUB_RAW) != 0)
	{
		m_pFactory.RegSubRawCallback(m_id,
			(DeviceRawCallbackFunctionPtr)MiningInterfaceMgr::RawHandler,
				(void *)this);
	}

	if ((m_type & MM_STREAM_SEQ) != 0)
	{
		m_pFactory.RegSeqCallback(m_id,
			(DeviceSeqCallbackFunctionPtr)MiningInterfaceMgr::SeqHandler,
				(void *)this);
	}
	//TODO add callback RetCallback from process module
	return TRUE;
}

inline BOOL MiningInterfaceMgr::Cleanup()
{
	/* Current we only use sub raw stream */
	if (m_type & MM_STREAM_SUB_RAW != 0)
	{
		m_pFactory.UnRegSubRawCallback(m_id, (void *)this);
	}

	if (m_type & MM_STREAM_SEQ != 0)
	{
		m_pFactory.UnRegSeqCallback(m_id, (void *)this);
	}
	//TODO add callback RetCallback from process module
	return TRUE;
}

inline void MiningInterfaceMgr::RawHandler1(RawFrame& frame)
{
	m_pDevice->ProcessRaw(frame);
}

inline void MiningInterfaceMgr::RawHandler(RawFrame& frame, void * pParam)
{
    MiningInterfaceMgr *pMgr = static_cast<MiningInterfaceMgr *> (pParam);

    return pMgr->RawHandler1(frame);
}

inline void MiningInterfaceMgr::SeqHandler1(VideoSeqFrame& frame)
{
	m_pDevice->ProcessSeq(frame);
}

inline void MiningInterfaceMgr::SeqHandler(VideoSeqFrame& frame, void * pParam)
{
    MiningInterfaceMgr *pMgr = static_cast<MiningInterfaceMgr *> (pParam);

    return pMgr->SeqHandler1(frame);
}

#endif /* __M_INTERFACE_MGR_IMPL_HPP__ */
<|endoftext|>


<commit_before>#ifndef MJOLNIR_GLOBAL_POTENTIAL_BASE
#define MJOLNIR_GLOBAL_POTENTIAL_BASE
#include "ParticleContainer.hpp"

namespace mjolnir
{

template<typename traitsT>
class GlobalPotentialBase
{
  public:
    typedef traitsT traits_type;
    typedef typename traits_type::real_type real_type;

    virtual ~GlobalPotentialBase(){};

    real_type
    potential(const std::size_t i, const std::size_t j, const real_type r) = 0;
    real_type
    derivative(const std::size_t i, const std::size_t j, const real_type r) = 0;

};

} // mjolnir
#endif /* MJOLNIR_GLOBAL_POTENTIAL_BASE */
<commit_msg>add forgotten virtual to GlobalPotentialBase<commit_after>#ifndef MJOLNIR_GLOBAL_POTENTIAL_BASE
#define MJOLNIR_GLOBAL_POTENTIAL_BASE
#include "ParticleContainer.hpp"

namespace mjolnir
{

template<typename traitsT>
class GlobalPotentialBase
{
  public:
    typedef traitsT traits_type;
    typedef typename traits_type::real_type real_type;

    virtual ~GlobalPotentialBase(){};

    virtual real_type
    potential(const std::size_t i, const std::size_t j, const real_type r) = 0;
    virtual real_type
    derivative(const std::size_t i, const std::size_t j, const real_type r) = 0;

};

} // mjolnir
#endif /* MJOLNIR_GLOBAL_POTENTIAL_BASE */
<|endoftext|>


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

#include "dialogs/firstrun.hpp"

#include <QGridLayout>
#include <QGroupBox>
#include <QCheckBox>
#include <QLabel>
#include <QDialogButtonBox>

FirstRun::FirstRun( QWidget *_p, intf_thread_t *_p_intf  )
         : QWidget( _p ), p_intf( _p_intf )
{
    msg_Dbg( p_intf, "Boring first Run Wizard" );
    buildPrivDialog();
    setVisible( true );
}

#define ALBUM_ART_WHEN_ASKED 0
#define ALBUM_ART_ALL 2

void FirstRun::save()
{
    config_PutInt( p_intf,  "album-art", checkbox->isChecked() ? ALBUM_ART_ALL: ALBUM_ART_WHEN_ASKED );
#ifdef UPDATE_CHECK
    config_PutInt( p_intf,  "qt-updates-notif", checkbox2->isChecked() );
#endif
    config_PutInt( p_intf,  "qt-privacy-ask", 0 );

    /* FIXME Should not save here. This will not work as expected if another
     * plugin overwrote items of its own. */
#warning FIXME
    /* We have to save here because the user may not launch Prefs */
    config_SaveConfigFile( p_intf );
    close();
}

void FirstRun::buildPrivDialog()
{
    setWindowTitle( qtr( "Privacy and Network Access Policy" ) );
    setWindowRole( "vlc-privacy" );
    setWindowModality( Qt::ApplicationModal );
    setWindowFlags( Qt::Dialog );
    setAttribute( Qt::WA_DeleteOnClose );

    QGridLayout *gLayout = new QGridLayout( this );

    QGroupBox *blabla = new QGroupBox( qtr( "Privacy and Network Access Policy" ) );
    QGridLayout *blablaLayout = new QGridLayout( blabla );
    QLabel *text = new QLabel( qtr(
        "
In order to protect your privacy, the VLC media player "
        "does not collect personal informations or transmit them, "
        "not even in anonymized form, to anyone."
        "
\n"
        "
Nevertheless, VLC is able to automatically retrieve "
        "informations about the media in your playlist from third party "
        "Internet-based services. These informations include covert arts, "
        "track names, authoring and other meta-data."
        "
\n"
        "That may entail identifying some of your media files to third party "
        "entities. Therefore the VLC developers require your express "
        "consent for the media player to access the Internet automatically."
        "
\n"
        ) );
    text->setWordWrap( true );
    text->setTextFormat( Qt::RichText );

    blablaLayout->addWidget( text, 0, 0 ) ;

    QGroupBox *options = new QGroupBox( qtr( "Network Access Policy" ) );
    QGridLayout *optionsLayout = new QGridLayout( options );

    gLayout->addWidget( blabla, 0, 0, 1, 3 );
    gLayout->addWidget( options, 1, 0, 1, 3 );
    int line = 0;

    checkbox = new QCheckBox( qtr( "Automatically retrieve media infos" ) );
    checkbox->setChecked( true );
    optionsLayout->addWidget( checkbox, line++, 0 );

#ifdef UPDATE_CHECK
    checkbox2 = new QCheckBox( qtr( "Regularly check for VLC updates" ) );
    checkbox2->setChecked( true );
    optionsLayout->addWidget( checkbox2, line++, 0 );
#endif

    QDialogButtonBox *buttonsBox = new QDialogButtonBox( this );
    buttonsBox->addButton( qtr( "Continue" ), QDialogButtonBox::AcceptRole );

    gLayout->addWidget( buttonsBox, 2, 0, 2, 3 );

    CONNECT( buttonsBox, accepted(), this, save() );
    buttonsBox->setFocus();
}
<commit_msg>Qt4: grammar<commit_after>/*****************************************************************************
 * firstrun.cpp : First Run dialogs
 ****************************************************************************
 * Copyright © 2009 VideoLAN
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "dialogs/firstrun.hpp"

#include <QGridLayout>
#include <QGroupBox>
#include <QCheckBox>
#include <QLabel>
#include <QDialogButtonBox>

FirstRun::FirstRun( QWidget *_p, intf_thread_t *_p_intf  )
         : QWidget( _p ), p_intf( _p_intf )
{
    msg_Dbg( p_intf, "Boring first Run Wizard" );
    buildPrivDialog();
    setVisible( true );
}

#define ALBUM_ART_WHEN_ASKED 0
#define ALBUM_ART_ALL 2

void FirstRun::save()
{
    config_PutInt( p_intf,  "album-art", checkbox->isChecked() ? ALBUM_ART_ALL: ALBUM_ART_WHEN_ASKED );
#ifdef UPDATE_CHECK
    config_PutInt( p_intf,  "qt-updates-notif", checkbox2->isChecked() );
#endif
    config_PutInt( p_intf,  "qt-privacy-ask", 0 );

    /* FIXME Should not save here. This will not work as expected if another
     * plugin overwrote items of its own. */
#warning FIXME
    /* We have to save here because the user may not launch Prefs */
    config_SaveConfigFile( p_intf );
    close();
}

void FirstRun::buildPrivDialog()
{
    setWindowTitle( qtr( "Privacy and Network Access Policy" ) );
    setWindowRole( "vlc-privacy" );
    setWindowModality( Qt::ApplicationModal );
    setWindowFlags( Qt::Dialog );
    setAttribute( Qt::WA_DeleteOnClose );

    QGridLayout *gLayout = new QGridLayout( this );

    QGroupBox *blabla = new QGroupBox( qtr( "Privacy and Network Access Policy" ) );
    QGridLayout *blablaLayout = new QGridLayout( blabla );
    QLabel *text = new QLabel( qtr(
        "
In order to protect your privacy, the VLC media player "
        "does not collect personal data or transmit them, "
        "not even in anonymized form, to anyone."
        "
\n"
        "
Nevertheless, VLC is able to automatically retrieve "
        "information about the media in your playlist from third party "
        "Internet-based services. That includes covert arts, track names, "
        "authoring and other meta-data."
        "
\n"
        "That may entail identifying some of your media files to third party "
        "entities. Therefore the VLC developers require your express "
        "consent for the media player to access the Internet automatically."
        "
\n"
        ) );
    text->setWordWrap( true );
    text->setTextFormat( Qt::RichText );

    blablaLayout->addWidget( text, 0, 0 ) ;

    QGroupBox *options = new QGroupBox( qtr( "Network Access Policy" ) );
    QGridLayout *optionsLayout = new QGridLayout( options );

    gLayout->addWidget( blabla, 0, 0, 1, 3 );
    gLayout->addWidget( options, 1, 0, 1, 3 );
    int line = 0;

    checkbox = new QCheckBox( qtr( "Automatically retrieve media infos" ) );
    checkbox->setChecked( true );
    optionsLayout->addWidget( checkbox, line++, 0 );

#ifdef UPDATE_CHECK
    checkbox2 = new QCheckBox( qtr( "Regularly check for VLC updates" ) );
    checkbox2->setChecked( true );
    optionsLayout->addWidget( checkbox2, line++, 0 );
#endif

    QDialogButtonBox *buttonsBox = new QDialogButtonBox( this );
    buttonsBox->addButton( qtr( "Continue" ), QDialogButtonBox::AcceptRole );

    gLayout->addWidget( buttonsBox, 2, 0, 2, 3 );

    CONNECT( buttonsBox, accepted(), this, save() );
    buttonsBox->setFocus();
}
<|endoftext|>


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

#ifndef SEEKSTYLE_HPP
#define SEEKSTYLE_HPP

#include <QProxyStyle>
#include <QStyleOptionSlider>

class SeekStyle : public QProxyStyle
{
    Q_OBJECT
public:
    class SeekStyleOption : public QStyleOptionSlider
    {
    public:
        SeekStyleOption();
        float buffering;
        int length;
        bool animate;
        qreal animationopacity;
        QList<int64_t> points;
    };

public:
    SeekStyle();
    virtual int pixelMetric(PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0) const;
    virtual void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *widget) const;
};

#endif // SEEKSTYLE_HPP
<commit_msg>qt4: fix windows build after 6ea38362e66<commit_after>/*****************************************************************************
 * seekstyle.hpp : Seek slider style
 ****************************************************************************
 * Copyright (C) 2011-2012 VLC authors and VideoLAN
 *
 * Authors: Ludovic Fauvet <etix@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef SEEKSTYLE_HPP
#define SEEKSTYLE_HPP

#include <inttypes.h>
#include <QProxyStyle>
#include <QStyleOptionSlider>

class SeekStyle : public QProxyStyle
{
    Q_OBJECT
public:
    class SeekStyleOption : public QStyleOptionSlider
    {
    public:
        SeekStyleOption();
        float buffering;
        int length;
        bool animate;
        qreal animationopacity;
        QList<int64_t> points;
    };

public:
    SeekStyle();
    virtual int pixelMetric(PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0) const;
    virtual void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *widget) const;
};

#endif // SEEKSTYLE_HPP
<|endoftext|>


<commit_before>/* Cycript - Optimizing JavaScript Compiler/Runtime
 * Copyright (C) 2009-2013  Jay Freeman (saurik)
*/

/* GNU General Public License, Version 3 {{{ */
/*
 * Cycript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Cycript is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cycript.  If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */

#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
#undef __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__
#define __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ __IPHONE_5_0
#endif

#include <dlfcn.h>
#include <pthread.h>
#include <unistd.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <mach/mach_vm.h>

#include <mach/machine/thread_status.h>

#ifdef __arm__
#include "Mach/Memory.hpp"
#endif

#include "Baton.hpp"
#include "Exception.hpp"
#include "Pooling.hpp"
#include "Trampoline.t.hpp"

extern "C" void CYHandleServer(pid_t);

extern "C" void *_dyld_get_all_image_infos();

void InjectLibrary(pid_t pid) {
    Dl_info addr;
    _assert(dladdr(reinterpret_cast<void *>(&CYHandleServer), &addr) != 0);

    size_t flength(strlen(addr.dli_fname));
    char library[flength + 4 + 1];
    memcpy(library, addr.dli_fname, flength);
    library[flength] = '\0';
    _assert(strcmp(library + flength - 6, ".dylib") == 0);
#if !TARGET_OS_IPHONE
    strcpy(library + flength - 6, "-any.dylib");
#endif

    mach_port_t self(mach_task_self()), task;
    _krncall(task_for_pid(self, pid, &task));

    task_dyld_info info;
#ifdef __arm__
    union {
        struct {
            uint32_t all_image_info_addr;
        } info_1;

        struct {
            uint32_t all_image_info_addr;
            uint32_t all_image_info_size;
            int32_t all_image_info_format;
        } info32;

        struct {
            uint64_t all_image_info_addr;
            uint64_t all_image_info_size;
            int32_t all_image_info_format;
        } info64;
    } infoXX;

    mach_msg_type_number_t count(sizeof(infoXX) / sizeof(natural_t));
    _krncall(task_info(task, TASK_DYLD_INFO, reinterpret_cast<task_info_t>(&infoXX), &count));

    bool broken;

    switch (count) {
        case sizeof(infoXX.info_1) / sizeof(natural_t):
            broken = true;
            info.all_image_info_addr = infoXX.info_1.all_image_info_addr;
            info.all_image_info_size = 0;
            info.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_32;
            break;
        case sizeof(infoXX.info32) / sizeof(natural_t):
            broken = true;
            info.all_image_info_addr = infoXX.info32.all_image_info_addr;
            info.all_image_info_size = infoXX.info32.all_image_info_size;
            info.all_image_info_format = infoXX.info32.all_image_info_format;
            break;
        case sizeof(infoXX.info64) / sizeof(natural_t):
            broken = false;
            info.all_image_info_addr = infoXX.info64.all_image_info_addr;
            info.all_image_info_size = infoXX.info64.all_image_info_size;
            info.all_image_info_format = infoXX.info64.all_image_info_format;
            break;
        default:
            _assert(false);
    }
#else
    mach_msg_type_number_t count(TASK_DYLD_INFO_COUNT);
    _krncall(task_info(task, TASK_DYLD_INFO, reinterpret_cast<task_info_t>(&info), &count));
    _assert(count == TASK_DYLD_INFO_COUNT);
#endif
    _assert(info.all_image_info_addr != 0);

    thread_act_t thread;
    _krncall(thread_create(task, &thread));

    thread_state_t bottom;
    thread_state_flavor_t flavor;

#if defined (__i386__) || defined(__x86_64__)
    x86_thread_state_t state;
    memset(&state, 0, sizeof(state));

    bottom = reinterpret_cast<thread_state_t>(&state);
    flavor = MACHINE_THREAD_STATE;
    count = MACHINE_THREAD_STATE_COUNT;
#elif defined(__arm__) || defined(__arm64__)
    arm_unified_thread_state_t state;
    memset(&state, 0, sizeof(state));

    switch (info.all_image_info_format) {
        case TASK_DYLD_ALL_IMAGE_INFO_32:
            bottom = reinterpret_cast<thread_state_t>(&state.ts_32);
            flavor = ARM_THREAD_STATE;
            count = ARM_THREAD_STATE_COUNT;
            state.ash.flavor = ARM_THREAD_STATE32;
            break;
        case TASK_DYLD_ALL_IMAGE_INFO_64:
            bottom = reinterpret_cast<thread_state_t>(&state.ts_64);
            flavor = ARM_THREAD_STATE64;
            count = ARM_THREAD_STATE64_COUNT + 1;
            state.ash.flavor = ARM_THREAD_STATE64;
            break;
        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    mach_msg_type_number_t read(count);
    _krncall(thread_get_state(thread, flavor, bottom, &read));
    _assert(read == count);

    Trampoline *trampoline;
    size_t align;
    size_t push;

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            trampoline = &Trampoline_i386_;
            align = 4;
            push = 5;
            break;
        case x86_THREAD_STATE64:
            trampoline = &Trampoline_x86_64_;
            align = 8;
            push = 2;
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__) || defined(__arm64__)
    switch (state.ash.flavor) {
        case ARM_THREAD_STATE32:
            trampoline = &Trampoline_armv6_;
            align = 4;
            push = 0;
            break;
        case ARM_THREAD_STATE64:
            trampoline = &Trampoline_arm64_;
            align = 8;
            push = 0;
            break;
        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    static const size_t Stack_(8 * 1024);
    size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);
    depth = (depth + align + 1) / align * align;

    CYPool pool;
    uint8_t *local(pool.malloc<uint8_t>(depth));
    Baton *baton(reinterpret_cast<Baton *>(local));

    baton->dyld = info.all_image_info_addr;
    baton->pid = getpid();
    memcpy(baton->library, library, length);

    mach_vm_size_t size(depth + Stack_);
    mach_vm_address_t stack;
    _krncall(mach_vm_allocate(task, &stack, size, true));

    mach_vm_address_t data(stack + Stack_);
    _krncall(mach_vm_write(task, data, reinterpret_cast<mach_vm_address_t>(baton), depth));

    mach_vm_address_t code;
    _krncall(mach_vm_allocate(task, &code, trampoline->size_, true));
    _krncall(mach_vm_write(task, code, reinterpret_cast<vm_offset_t>(trampoline->data_), trampoline->size_));
    _krncall(mach_vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE));

    uint32_t frame[push];
    if (sizeof(frame) != 0)
        memset(frame, 0, sizeof(frame));

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            frame[1] = data;
            state.uts.ts32.__eip = code + trampoline->entry_;
            state.uts.ts32.__esp = stack + Stack_ - sizeof(frame);
            break;
        case x86_THREAD_STATE64:
            state.uts.ts64.__rdi = data;
            state.uts.ts64.__rip = code + trampoline->entry_;
            state.uts.ts64.__rsp = stack + Stack_ - sizeof(frame);
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__) || defined(__arm64__)
    switch (state.ash.flavor) {
        case ARM_THREAD_STATE32:
            state.ts_32.__r[0] = data;
            state.ts_32.__pc = code + trampoline->entry_;
            state.ts_32.__sp = stack + Stack_ - sizeof(frame);

            if ((state.ts_32.__pc & 0x1) != 0) {
                state.ts_32.__pc &= ~0x1;
                state.ts_32.__cpsr |= 0x20;
            }

            break;

        case ARM_THREAD_STATE64:
            state.ts_64.__x[0] = data;
            state.ts_64.__pc = code + trampoline->entry_;
            state.ts_64.__sp = stack + Stack_ - sizeof(frame);
            break;

        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    if (sizeof(frame) != 0)
        _krncall(mach_vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<mach_vm_address_t>(frame), sizeof(frame)));

    _krncall(thread_set_state(thread, flavor, bottom, read));
    _krncall(thread_resume(thread));

    loop: switch (kern_return_t status = thread_get_state(thread, flavor, bottom, &(read = count))) {
        case KERN_SUCCESS:
            usleep(10000);
            goto loop;

        case KERN_TERMINATED:
        case MACH_SEND_INVALID_DEST:
            break;

        default:
            _assert(false);
    }

    _krncall(mach_port_deallocate(self, thread));

    mach_vm_size_t error(sizeof(baton->error));
    _krncall(mach_vm_read_overwrite(task, data + offsetof(Baton, error), sizeof(baton->error), reinterpret_cast<mach_vm_address_t>(&baton->error), &error));
    _assert(error == sizeof(baton->error));
    if (baton->error[0] != '\0')
        CYThrow("%s", baton->error);

    _krncall(mach_vm_deallocate(task, code, trampoline->size_));
    _krncall(mach_vm_deallocate(task, stack, size));

    _krncall(mach_port_deallocate(self, task));
}
<commit_msg>Fix creepy "dump master.passwd to stderr" failure.<commit_after>/* Cycript - Optimizing JavaScript Compiler/Runtime
 * Copyright (C) 2009-2013  Jay Freeman (saurik)
*/

/* GNU General Public License, Version 3 {{{ */
/*
 * Cycript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Cycript is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cycript.  If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */

#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
#undef __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__
#define __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ __IPHONE_5_0
#endif

#include <dlfcn.h>
#include <pthread.h>
#include <unistd.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <mach/mach_vm.h>

#include <mach/machine/thread_status.h>

#ifdef __arm__
#include "Mach/Memory.hpp"
#endif

#include "Baton.hpp"
#include "Exception.hpp"
#include "Pooling.hpp"
#include "Trampoline.t.hpp"

extern "C" void CYHandleServer(pid_t);

extern "C" void *_dyld_get_all_image_infos();

void InjectLibrary(pid_t pid) {
    Dl_info addr;
    _assert(dladdr(reinterpret_cast<void *>(&CYHandleServer), &addr) != 0);

    size_t flength(strlen(addr.dli_fname));
    char library[flength + 4 + 1];
    memcpy(library, addr.dli_fname, flength);
    library[flength] = '\0';
    _assert(strcmp(library + flength - 6, ".dylib") == 0);
#if !TARGET_OS_IPHONE
    strcpy(library + flength - 6, "-any.dylib");
#endif

    mach_port_t self(mach_task_self()), task;
    _krncall(task_for_pid(self, pid, &task));

    task_dyld_info info;
#ifdef __arm__
    union {
        struct {
            uint32_t all_image_info_addr;
        } info_1;

        struct {
            uint32_t all_image_info_addr;
            uint32_t all_image_info_size;
            int32_t all_image_info_format;
        } info32;

        struct {
            uint64_t all_image_info_addr;
            uint64_t all_image_info_size;
            int32_t all_image_info_format;
        } info64;
    } infoXX;

    mach_msg_type_number_t count(sizeof(infoXX) / sizeof(natural_t));
    _krncall(task_info(task, TASK_DYLD_INFO, reinterpret_cast<task_info_t>(&infoXX), &count));

    bool broken;

    switch (count) {
        case sizeof(infoXX.info_1) / sizeof(natural_t):
            broken = true;
            info.all_image_info_addr = infoXX.info_1.all_image_info_addr;
            info.all_image_info_size = 0;
            info.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_32;
            break;
        case sizeof(infoXX.info32) / sizeof(natural_t):
            broken = true;
            info.all_image_info_addr = infoXX.info32.all_image_info_addr;
            info.all_image_info_size = infoXX.info32.all_image_info_size;
            info.all_image_info_format = infoXX.info32.all_image_info_format;
            break;
        case sizeof(infoXX.info64) / sizeof(natural_t):
            broken = false;
            info.all_image_info_addr = infoXX.info64.all_image_info_addr;
            info.all_image_info_size = infoXX.info64.all_image_info_size;
            info.all_image_info_format = infoXX.info64.all_image_info_format;
            break;
        default:
            _assert(false);
    }
#else
    mach_msg_type_number_t count(TASK_DYLD_INFO_COUNT);
    _krncall(task_info(task, TASK_DYLD_INFO, reinterpret_cast<task_info_t>(&info), &count));
    _assert(count == TASK_DYLD_INFO_COUNT);
#endif
    _assert(info.all_image_info_addr != 0);

    thread_act_t thread;
    _krncall(thread_create(task, &thread));

    thread_state_t bottom;
    thread_state_flavor_t flavor;

#if defined (__i386__) || defined(__x86_64__)
    x86_thread_state_t state;
    memset(&state, 0, sizeof(state));

    bottom = reinterpret_cast<thread_state_t>(&state);
    flavor = MACHINE_THREAD_STATE;
    count = MACHINE_THREAD_STATE_COUNT;
#elif defined(__arm__) || defined(__arm64__)
    arm_unified_thread_state_t state;
    memset(&state, 0, sizeof(state));

    switch (info.all_image_info_format) {
        case TASK_DYLD_ALL_IMAGE_INFO_32:
            bottom = reinterpret_cast<thread_state_t>(&state.ts_32);
            flavor = ARM_THREAD_STATE;
            count = ARM_THREAD_STATE_COUNT;
            state.ash.flavor = ARM_THREAD_STATE32;
            break;
        case TASK_DYLD_ALL_IMAGE_INFO_64:
            bottom = reinterpret_cast<thread_state_t>(&state.ts_64);
            flavor = ARM_THREAD_STATE64;
            count = ARM_THREAD_STATE64_COUNT + 1;
            state.ash.flavor = ARM_THREAD_STATE64;
            break;
        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    mach_msg_type_number_t read(count);
    _krncall(thread_get_state(thread, flavor, bottom, &read));
    _assert(read == count);

    Trampoline *trampoline;
    size_t align;
    size_t push;

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            trampoline = &Trampoline_i386_;
            align = 4;
            push = 5;
            break;
        case x86_THREAD_STATE64:
            trampoline = &Trampoline_x86_64_;
            align = 8;
            push = 2;
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__) || defined(__arm64__)
    switch (state.ash.flavor) {
        case ARM_THREAD_STATE32:
            trampoline = &Trampoline_armv6_;
            align = 4;
            push = 0;
            break;
        case ARM_THREAD_STATE64:
            trampoline = &Trampoline_arm64_;
            align = 8;
            push = 0;
            break;
        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    static const size_t Stack_(8 * 1024);
    size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);
    depth = (depth + align + 1) / align * align;

    CYPool pool;
    uint8_t *local(pool.malloc<uint8_t>(depth));
    Baton *baton(reinterpret_cast<Baton *>(local));

    baton->dyld = info.all_image_info_addr;
    baton->pid = getpid();
    memset(baton->error, 0, sizeof(baton->error));
    memcpy(baton->library, library, length);

    mach_vm_size_t size(depth + Stack_);
    mach_vm_address_t stack;
    _krncall(mach_vm_allocate(task, &stack, size, true));

    mach_vm_address_t data(stack + Stack_);
    _krncall(mach_vm_write(task, data, reinterpret_cast<mach_vm_address_t>(baton), depth));

    mach_vm_address_t code;
    _krncall(mach_vm_allocate(task, &code, trampoline->size_, true));
    _krncall(mach_vm_write(task, code, reinterpret_cast<vm_offset_t>(trampoline->data_), trampoline->size_));
    _krncall(mach_vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE));

    uint32_t frame[push];
    if (sizeof(frame) != 0)
        memset(frame, 0, sizeof(frame));

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            frame[1] = data;
            state.uts.ts32.__eip = code + trampoline->entry_;
            state.uts.ts32.__esp = stack + Stack_ - sizeof(frame);
            break;
        case x86_THREAD_STATE64:
            state.uts.ts64.__rdi = data;
            state.uts.ts64.__rip = code + trampoline->entry_;
            state.uts.ts64.__rsp = stack + Stack_ - sizeof(frame);
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__) || defined(__arm64__)
    switch (state.ash.flavor) {
        case ARM_THREAD_STATE32:
            state.ts_32.__r[0] = data;
            state.ts_32.__pc = code + trampoline->entry_;
            state.ts_32.__sp = stack + Stack_ - sizeof(frame);

            if ((state.ts_32.__pc & 0x1) != 0) {
                state.ts_32.__pc &= ~0x1;
                state.ts_32.__cpsr |= 0x20;
            }

            break;

        case ARM_THREAD_STATE64:
            state.ts_64.__x[0] = data;
            state.ts_64.__pc = code + trampoline->entry_;
            state.ts_64.__sp = stack + Stack_ - sizeof(frame);
            break;

        default:
            _assert(false);
    }
#else
    #error XXX: implement
#endif

    if (sizeof(frame) != 0)
        _krncall(mach_vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<mach_vm_address_t>(frame), sizeof(frame)));

    _krncall(thread_set_state(thread, flavor, bottom, read));
    _krncall(thread_resume(thread));

    loop: switch (kern_return_t status = thread_get_state(thread, flavor, bottom, &(read = count))) {
        case KERN_SUCCESS:
            usleep(10000);
            goto loop;

        case KERN_TERMINATED:
        case MACH_SEND_INVALID_DEST:
            break;

        default:
            _assert(false);
    }

    _krncall(mach_port_deallocate(self, thread));

    mach_vm_size_t error(sizeof(baton->error));
    _krncall(mach_vm_read_overwrite(task, data + offsetof(Baton, error), sizeof(baton->error), reinterpret_cast<mach_vm_address_t>(&baton->error), &error));
    _assert(error == sizeof(baton->error));
    if (baton->error[0] != '\0')
        CYThrow("%s", baton->error);

    _krncall(mach_vm_deallocate(task, code, trampoline->size_));
    _krncall(mach_vm_deallocate(task, stack, size));

    _krncall(mach_port_deallocate(self, task));
}
<|endoftext|>


<commit_before>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2019 LibRaw LLC (info@libraw.org)
    Copyright (C) 2020 Roman Lebedev

    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 "decompressors/PanasonicDecompressorV6.h" // for PanasonicDecompre...
#include "common/Array2DRef.h"                     // for Array2DRef
#include "common/Point.h"                          // for iPoint2D
#include "common/RawImage.h"                       // for RawImage, RawImag...
#include "decoders/RawDecoderException.h"          // for ThrowRDE
#include <algorithm>                               // for copy_n
#include <array>
#include <cstdint> // for uint16_t, uint32_t
#include <cstdlib> // for free, malloc

namespace rawspeed {

constexpr int PanasonicDecompressorV6::PixelsPerBlock;
constexpr int PanasonicDecompressorV6::BytesPerBlock;

namespace {
struct pana_cs6_page_decoder {
  std::array<unsigned int, 14> pixelbuffer;
  unsigned char current = 0;

  explicit pana_cs6_page_decoder(const ByteStream& bs) {
    pixelbuffer[0] = (bs.peekByte(15) << 6) | (bs.peekByte(14) >> 2); // 14 bit
    pixelbuffer[1] = (((bs.peekByte(14) & 0x3) << 12) | (bs.peekByte(13) << 4) |
                      (bs.peekByte(12) >> 4)) &
                     0x3fff;
    pixelbuffer[2] = (bs.peekByte(12) >> 2) & 0x3;
    pixelbuffer[3] = ((bs.peekByte(12) & 0x3) << 8) | bs.peekByte(11);
    pixelbuffer[4] = (bs.peekByte(10) << 2) | (bs.peekByte(9) >> 6);
    pixelbuffer[5] = ((bs.peekByte(9) & 0x3f) << 4) | (bs.peekByte(8) >> 4);
    pixelbuffer[6] = (bs.peekByte(8) >> 2) & 0x3;
    pixelbuffer[7] = ((bs.peekByte(8) & 0x3) << 8) | bs.peekByte(7);
    pixelbuffer[8] = ((bs.peekByte(6) << 2) & 0x3fc) | (bs.peekByte(5) >> 6);
    pixelbuffer[9] = ((bs.peekByte(5) << 4) | (bs.peekByte(4) >> 4)) & 0x3ff;
    pixelbuffer[10] = (bs.peekByte(4) >> 2) & 0x3;
    pixelbuffer[11] = ((bs.peekByte(4) & 0x3) << 8) | bs.peekByte(3);
    pixelbuffer[12] =
        (((bs.peekByte(2) << 2) & 0x3fc) | bs.peekByte(1) >> 6) & 0x3ff;
    pixelbuffer[13] = ((bs.peekByte(1) << 4) | (bs.peekByte(0) >> 4)) & 0x3ff;
  }

  unsigned int nextpixel() { return pixelbuffer[current++]; }
};
} // namespace

PanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,
                                                 ByteStream input_)
    : mRaw(img), input(std::move(input_)) {
  if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
      mRaw->getBpp() != sizeof(uint16_t))
    ThrowRDE("Unexpected component count / data type");

  if (!mRaw->dim.hasPositiveArea()) {
    ThrowRDE("Unexpected image dimensions found: (%i; %i)", mRaw->dim.x,
             mRaw->dim.y);
  }

  const int blocksperrow =
      mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
  const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
  const int bytesTotal = bytesPerRow * mRaw->dim.y;
  input = input_.peekStream(bytesTotal);
}

void PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,
                                              int col) const {
  const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());

  pana_cs6_page_decoder page(
      rowInput->getStream(PanasonicDecompressorV6::BytesPerBlock));

  std::array<unsigned int, 2> oddeven = {0, 0};
  std::array<unsigned int, 2> nonzero = {0, 0};
  unsigned pmul = 0;
  unsigned pixel_base = 0;
  for (int pix = 0; pix < PanasonicDecompressorV6::PixelsPerBlock;
       pix++, col++) {
    if (pix % 3 == 2) {
      unsigned base = page.nextpixel();
      if (base > 3)
        ThrowRDE("Invariant failure");
      if (base == 3)
        base = 4;
      pixel_base = 0x200 << base;
      pmul = 1 << base;
    }
    unsigned epixel = page.nextpixel();
    if (oddeven[pix % 2]) {
      epixel *= pmul;
      if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)
        epixel += nonzero[pix % 2] - pixel_base;
      nonzero[pix % 2] = epixel;
    } else {
      oddeven[pix % 2] = epixel;
      if (epixel)
        nonzero[pix % 2] = epixel;
      else
        epixel = nonzero[pix % 2];
    }
    auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);
    if (spix <= 0xffff)
      out(row, col) = spix & 0xffff;
    else {
      epixel = static_cast<signed int>(epixel + 0x7ffffff1) >> 0x1f;
      out(row, col) = epixel & 0x3fff;
    }
  }
}

void PanasonicDecompressorV6::decompressRow(int row) const {
  const int blocksperrow =
      mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
  const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;

  ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);
  for (int rblock = 0, col = 0; rblock < blocksperrow;
       rblock++, col += PanasonicDecompressorV6::PixelsPerBlock)
    decompressBlock(&rowInput, row, col);
}

void PanasonicDecompressorV6::decompress() const {
#ifdef HAVE_OPENMP
#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \
    schedule(static) default(none)
#endif
  for (int row = 0; row < mRaw->dim.y; ++row) {
    try {
      decompressRow(row);
    } catch (RawspeedException& err) {
      // Propagate the exception out of OpenMP magic.
      mRaw->setError(err.what());
    }
  }

  std::string firstErr;
  if (mRaw->isTooManyErrors(1, &firstErr)) {
    ThrowRDE("Too many errors encountered. Giving up. First Error:\n%s",
             firstErr.c_str());
  }
}

} // namespace rawspeed
<commit_msg>PanasonicDecompressorV6: narrow some variables if possible (-6%)<commit_after>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2019 LibRaw LLC (info@libraw.org)
    Copyright (C) 2020 Roman Lebedev

    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 "decompressors/PanasonicDecompressorV6.h" // for PanasonicDecompre...
#include "common/Array2DRef.h"                     // for Array2DRef
#include "common/Point.h"                          // for iPoint2D
#include "common/RawImage.h"                       // for RawImage, RawImag...
#include "decoders/RawDecoderException.h"          // for ThrowRDE
#include <algorithm>                               // for copy_n
#include <array>
#include <cstdint> // for uint16_t, uint32_t
#include <cstdlib> // for free, malloc

namespace rawspeed {

constexpr int PanasonicDecompressorV6::PixelsPerBlock;
constexpr int PanasonicDecompressorV6::BytesPerBlock;

namespace {
struct pana_cs6_page_decoder {
  std::array<uint16_t, 14> pixelbuffer;
  unsigned char current = 0;

  explicit pana_cs6_page_decoder(const ByteStream& bs) {
    pixelbuffer[0] = (bs.peekByte(15) << 6) | (bs.peekByte(14) >> 2); // 14 bit
    pixelbuffer[1] = (((bs.peekByte(14) & 0x3) << 12) | (bs.peekByte(13) << 4) |
                      (bs.peekByte(12) >> 4)) &
                     0x3fff;
    pixelbuffer[2] = (bs.peekByte(12) >> 2) & 0x3;
    pixelbuffer[3] = ((bs.peekByte(12) & 0x3) << 8) | bs.peekByte(11);
    pixelbuffer[4] = (bs.peekByte(10) << 2) | (bs.peekByte(9) >> 6);
    pixelbuffer[5] = ((bs.peekByte(9) & 0x3f) << 4) | (bs.peekByte(8) >> 4);
    pixelbuffer[6] = (bs.peekByte(8) >> 2) & 0x3;
    pixelbuffer[7] = ((bs.peekByte(8) & 0x3) << 8) | bs.peekByte(7);
    pixelbuffer[8] = ((bs.peekByte(6) << 2) & 0x3fc) | (bs.peekByte(5) >> 6);
    pixelbuffer[9] = ((bs.peekByte(5) << 4) | (bs.peekByte(4) >> 4)) & 0x3ff;
    pixelbuffer[10] = (bs.peekByte(4) >> 2) & 0x3;
    pixelbuffer[11] = ((bs.peekByte(4) & 0x3) << 8) | bs.peekByte(3);
    pixelbuffer[12] =
        (((bs.peekByte(2) << 2) & 0x3fc) | bs.peekByte(1) >> 6) & 0x3ff;
    pixelbuffer[13] = ((bs.peekByte(1) << 4) | (bs.peekByte(0) >> 4)) & 0x3ff;
  }

  uint16_t nextpixel() { return pixelbuffer[current++]; }
};
} // namespace

PanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,
                                                 ByteStream input_)
    : mRaw(img), input(std::move(input_)) {
  if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
      mRaw->getBpp() != sizeof(uint16_t))
    ThrowRDE("Unexpected component count / data type");

  if (!mRaw->dim.hasPositiveArea()) {
    ThrowRDE("Unexpected image dimensions found: (%i; %i)", mRaw->dim.x,
             mRaw->dim.y);
  }

  const int blocksperrow =
      mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
  const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
  const int bytesTotal = bytesPerRow * mRaw->dim.y;
  input = input_.peekStream(bytesTotal);
}

void PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,
                                              int col) const {
  const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());

  pana_cs6_page_decoder page(
      rowInput->getStream(PanasonicDecompressorV6::BytesPerBlock));

  std::array<unsigned, 2> oddeven = {0, 0};
  std::array<unsigned, 2> nonzero = {0, 0};
  unsigned pmul = 0;
  unsigned pixel_base = 0;
  for (int pix = 0; pix < PanasonicDecompressorV6::PixelsPerBlock;
       pix++, col++) {
    if (pix % 3 == 2) {
      uint16_t base = page.nextpixel();
      if (base > 3)
        ThrowRDE("Invariant failure");
      if (base == 3)
        base = 4;
      pixel_base = 0x200 << base;
      pmul = 1 << base;
    }
    uint16_t epixel = page.nextpixel();
    if (oddeven[pix % 2]) {
      epixel *= pmul;
      if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)
        epixel += nonzero[pix % 2] - pixel_base;
      nonzero[pix % 2] = epixel;
    } else {
      oddeven[pix % 2] = epixel;
      if (epixel)
        nonzero[pix % 2] = epixel;
      else
        epixel = nonzero[pix % 2];
    }
    auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);
    if (spix <= 0xffff)
      out(row, col) = spix & 0xffff;
    else {
      epixel = static_cast<int>(epixel + 0x7ffffff1) >> 0x1f;
      out(row, col) = epixel & 0x3fff;
    }
  }
}

void PanasonicDecompressorV6::decompressRow(int row) const {
  const int blocksperrow =
      mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
  const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;

  ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);
  for (int rblock = 0, col = 0; rblock < blocksperrow;
       rblock++, col += PanasonicDecompressorV6::PixelsPerBlock)
    decompressBlock(&rowInput, row, col);
}

void PanasonicDecompressorV6::decompress() const {
#ifdef HAVE_OPENMP
#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \
    schedule(static) default(none)
#endif
  for (int row = 0; row < mRaw->dim.y; ++row) {
    try {
      decompressRow(row);
    } catch (RawspeedException& err) {
      // Propagate the exception out of OpenMP magic.
      mRaw->setError(err.what());
    }
  }

  std::string firstErr;
  if (mRaw->isTooManyErrors(1, &firstErr)) {
    ThrowRDE("Too many errors encountered. Giving up. First Error:\n%s",
             firstErr.c_str());
  }
}

} // namespace rawspeed
<|endoftext|>