<commit_before>/*************************************************************************
 *
 *  $RCSfile: dlgepgm.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-09-09 11:27:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef GCC
#pragma hdrstop
#endif

#include <tools/ref.hxx>
#include <svtools/FilterConfigItem.hxx>
#include <vcl/msgbox.hxx>
#include "dlgepgm.hxx"
#include "dlgepgm.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEPGM::DlgExportEPGM( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_EPGM, rPara.pResMgr ) ),
                aGrpFormat          ( this, ResId( GRP_FORMAT ) ),
                aRBRaw              ( this, ResId( RB_RAW ) ),
                aRBASCII            ( this, ResId( RB_ASCII ) ),
                aBtnOK              ( this, ResId( BTN_OK ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
                aBtnHelp            ( this, ResId( BTN_HELP ) ),
                pMgr                ( rPara.pResMgr ),
                rFltCallPara        ( rPara )
{
    FreeResource();

    // Config-Parameter lesen

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/PGM" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );
    sal_Int32   nFormat = pConfigItem->ReadInt32( String( ResId( KEY_FORMAT, pMgr ) ), 0 );

    BOOL bCheck = FALSE;
    if ( !nFormat )
        bCheck ^= TRUE;
    aRBRaw.Check( bCheck );
    bCheck ^= TRUE;
    aRBASCII.Check( bCheck );

    aBtnOK.SetClickHdl( LINK( this, DlgExportEPGM, OK ) );
}

DlgExportEPGM::~DlgExportEPGM()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEPGM, OK, void *, EMPTYARG )
{
    // Config-Parameter schreiben
    sal_Int32 nFormat = 0;
    if ( aRBASCII.IsChecked() )
        nFormat++;
    pConfigItem->WriteInt32( String( ResId( KEY_FORMAT, pMgr ) ), nFormat );
    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.84); FILE MERGED 2005/09/05 15:12:17 rt 1.4.84.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgepgm.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:37:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef GCC
#pragma hdrstop
#endif

#include <tools/ref.hxx>
#include <svtools/FilterConfigItem.hxx>
#include <vcl/msgbox.hxx>
#include "dlgepgm.hxx"
#include "dlgepgm.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEPGM::DlgExportEPGM( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_EPGM, rPara.pResMgr ) ),
                aGrpFormat          ( this, ResId( GRP_FORMAT ) ),
                aRBRaw              ( this, ResId( RB_RAW ) ),
                aRBASCII            ( this, ResId( RB_ASCII ) ),
                aBtnOK              ( this, ResId( BTN_OK ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
                aBtnHelp            ( this, ResId( BTN_HELP ) ),
                pMgr                ( rPara.pResMgr ),
                rFltCallPara        ( rPara )
{
    FreeResource();

    // Config-Parameter lesen

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/PGM" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );
    sal_Int32   nFormat = pConfigItem->ReadInt32( String( ResId( KEY_FORMAT, pMgr ) ), 0 );

    BOOL bCheck = FALSE;
    if ( !nFormat )
        bCheck ^= TRUE;
    aRBRaw.Check( bCheck );
    bCheck ^= TRUE;
    aRBASCII.Check( bCheck );

    aBtnOK.SetClickHdl( LINK( this, DlgExportEPGM, OK ) );
}

DlgExportEPGM::~DlgExportEPGM()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEPGM, OK, void *, EMPTYARG )
{
    // Config-Parameter schreiben
    sal_Int32 nFormat = 0;
    if ( aRBASCII.IsChecked() )
        nFormat++;
    pConfigItem->WriteInt32( String( ResId( KEY_FORMAT, pMgr ) ), nFormat );
    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}
<|endoftext|>


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

#include "../client/query_tracker.h"

#if !defined(__native_client__)
  #include "base/atomicops.h"
#endif
#include "../client/cmd_buffer_helper.h"
#include "../client/mapped_memory.h"

namespace gpu {
namespace gles2 {

QuerySyncManager::QuerySyncManager(MappedMemoryManager* manager)
    : mapped_memory_(manager) {
  GPU_DCHECK(manager);
}

QuerySyncManager::~QuerySyncManager() {
  while (!buckets_.empty()) {
    mapped_memory_->Free(buckets_.front());
    buckets_.pop();
  }
}

bool QuerySyncManager::Alloc(QuerySyncManager::QueryInfo* info) {
  GPU_DCHECK(info);
  if (free_queries_.empty()) {
    int32 shm_id;
    unsigned int shm_offset;
    void* mem = mapped_memory_->Alloc(
        kSyncsPerBucket * sizeof(QuerySync), &shm_id, &shm_offset);
    if (!mem) {
      return false;
    }
    QuerySync* syncs = static_cast<QuerySync*>(mem);
    buckets_.push(syncs);
    for (size_t ii = 0; ii < kSyncsPerBucket; ++ii) {
      free_queries_.push(QueryInfo(shm_id, shm_offset, syncs));
      ++syncs;
      shm_offset += sizeof(*syncs);
    }
  }
  *info = free_queries_.front();
  info->sync->Reset();
  free_queries_.pop();
  return true;
}

void QuerySyncManager::Free(const QuerySyncManager::QueryInfo& info) {
  free_queries_.push(info);
}

bool QueryTracker::Query::CheckResultsAvailable(
    CommandBufferHelper* helper) {
  if (Pending()) {
    if (info_.sync->process_count == submit_count_) {
      // Need a MemoryBarrier here so that sync->result read after
      // sync->process_count.
      #if defined(__native_client__)
        __sync_synchronize();
      #else
        base::subtle::MemoryBarrier();
      #endif
      result_ = info_.sync->result;
      state_ = kComplete;
    } else {
      if (!flushed_) {
        // TODO(gman): We could reduce the number of flushes by having a
        // flush count, recording that count at the time we insert the
        // EndQuery command and then only flushing here if we've have not
        // passed that count yet.
        flushed_ = true;
        helper->Flush();
      }
    }
  }
  return state_ == kComplete;
}

uint32 QueryTracker::Query::GetResult() const {
  GPU_DCHECK(state_ == kComplete || state_ == kUninitialized);
  return result_;
}

QueryTracker::QueryTracker(MappedMemoryManager* manager)
    : query_sync_manager_(manager) {
}

QueryTracker::~QueryTracker() {
  queries_.clear();
}

QueryTracker::Query* QueryTracker::CreateQuery(GLuint id, GLenum target) {
  GPU_DCHECK_NE(0u, id);
  QuerySyncManager::QueryInfo info;
  if (!query_sync_manager_.Alloc(&info)) {
    return NULL;
  }
  Query* query = new Query(id, target, info);
  std::pair<QueryMap::iterator, bool> result =
      queries_.insert(std::make_pair(id, query));
  GPU_DCHECK(result.second);
  return query;
}

QueryTracker::Query* QueryTracker::GetQuery(
    GLuint client_id) {
  QueryMap::iterator it = queries_.find(client_id);
  return it != queries_.end() ? it->second : NULL;
}

void QueryTracker::RemoveQuery(GLuint client_id) {
  QueryMap::iterator it = queries_.find(client_id);
  if (it != queries_.end()) {
    Query* query = it->second;
    GPU_DCHECK(!query->Pending());
    query_sync_manager_.Free(query->info_);
    queries_.erase(it);
    delete query;
  }
}

}  // namespace gles2
}  // namespace gpu

<commit_msg>Insert No-ops into the command buffer when glQueryObjectuiv is called.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "../client/query_tracker.h"

#if !defined(__native_client__)
  #include "base/atomicops.h"
#endif
#include "../client/cmd_buffer_helper.h"
#include "../client/mapped_memory.h"

namespace gpu {
namespace gles2 {

QuerySyncManager::QuerySyncManager(MappedMemoryManager* manager)
    : mapped_memory_(manager) {
  GPU_DCHECK(manager);
}

QuerySyncManager::~QuerySyncManager() {
  while (!buckets_.empty()) {
    mapped_memory_->Free(buckets_.front());
    buckets_.pop();
  }
}

bool QuerySyncManager::Alloc(QuerySyncManager::QueryInfo* info) {
  GPU_DCHECK(info);
  if (free_queries_.empty()) {
    int32 shm_id;
    unsigned int shm_offset;
    void* mem = mapped_memory_->Alloc(
        kSyncsPerBucket * sizeof(QuerySync), &shm_id, &shm_offset);
    if (!mem) {
      return false;
    }
    QuerySync* syncs = static_cast<QuerySync*>(mem);
    buckets_.push(syncs);
    for (size_t ii = 0; ii < kSyncsPerBucket; ++ii) {
      free_queries_.push(QueryInfo(shm_id, shm_offset, syncs));
      ++syncs;
      shm_offset += sizeof(*syncs);
    }
  }
  *info = free_queries_.front();
  info->sync->Reset();
  free_queries_.pop();
  return true;
}

void QuerySyncManager::Free(const QuerySyncManager::QueryInfo& info) {
  free_queries_.push(info);
}

bool QueryTracker::Query::CheckResultsAvailable(
    CommandBufferHelper* helper) {
  if (Pending()) {
    if (info_.sync->process_count == submit_count_) {
      // Need a MemoryBarrier here so that sync->result read after
      // sync->process_count.
      #if defined(__native_client__)
        __sync_synchronize();
      #else
        base::subtle::MemoryBarrier();
      #endif
      result_ = info_.sync->result;
      state_ = kComplete;
    } else {
      if (!flushed_) {
        // TODO(gman): We could reduce the number of flushes by having a
        // flush count, recording that count at the time we insert the
        // EndQuery command and then only flushing here if we've have not
        // passed that count yet.
        flushed_ = true;
        helper->Flush();
      } else {
        // Insert no-ops so that eventually the GPU process will see more work.
        helper->Noop(1);
      }
    }
  }
  return state_ == kComplete;
}

uint32 QueryTracker::Query::GetResult() const {
  GPU_DCHECK(state_ == kComplete || state_ == kUninitialized);
  return result_;
}

QueryTracker::QueryTracker(MappedMemoryManager* manager)
    : query_sync_manager_(manager) {
}

QueryTracker::~QueryTracker() {
  queries_.clear();
}

QueryTracker::Query* QueryTracker::CreateQuery(GLuint id, GLenum target) {
  GPU_DCHECK_NE(0u, id);
  QuerySyncManager::QueryInfo info;
  if (!query_sync_manager_.Alloc(&info)) {
    return NULL;
  }
  Query* query = new Query(id, target, info);
  std::pair<QueryMap::iterator, bool> result =
      queries_.insert(std::make_pair(id, query));
  GPU_DCHECK(result.second);
  return query;
}

QueryTracker::Query* QueryTracker::GetQuery(
    GLuint client_id) {
  QueryMap::iterator it = queries_.find(client_id);
  return it != queries_.end() ? it->second : NULL;
}

void QueryTracker::RemoveQuery(GLuint client_id) {
  QueryMap::iterator it = queries_.find(client_id);
  if (it != queries_.end()) {
    Query* query = it->second;
    GPU_DCHECK(!query->Pending());
    query_sync_manager_.Free(query->info_);
    queries_.erase(it);
    delete query;
  }
}

}  // namespace gles2
}  // namespace gpu

<|endoftext|>


<commit_before>#define DEBUG 0
/**
 * File    : H.cpp
 * Author  : Kazune Takahashi
 * Created : 2019/12/30 18:11:35
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- PrimeNums -----

class PrimeNums
{
  static constexpr ll MAX_SIZE{1000010LL};
  ll N;
  vector<bool> isprime;
  vector<int> prime_nums;

public:
  PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{}
  {
    isprime[0] = isprime[1] = false;
    for (auto i = 2; i < N; i++)
    {
      if (isprime[i])
      {
        prime_nums.push_back(i);
        for (auto j = 2 * i; j < N; j += i)
        {
          isprime[j] = false;
        }
      }
    }
  }

  bool is_prime(long long x)
  { // 2 \leq x \leq MAX_SIZE^2
    if (x < N)
    {
      return isprime[x];
    }
    for (auto e : prime_nums)
    {
      if (x % e == 0)
        return false;
    }
    return true;
  }

  vector<int> const &primes() const
  {
    return prime_nums;
  }
};

// ----- main() -----
class Solve
{
  int H, W;
  vector<string> S;
  PrimeNums pn;

public:
  Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {}

  int calc()
  {
    int ans{0};
    for (auto i = 0; i < H; i++)
    {
      ans += calc(S[i]);
    }
    return ans;
  };

private:
  int calc(string const &T)
  {
    if (is_zero(T))
    {
      return 0;
    }
    auto V{make_vec(T)};
    if (is_one(V))
    {
      return 1;
    }
    if (is_two(V))
    {
      return 2;
    }
    return 3;
  }

  bool is_zero(string const &T)
  {
    for (auto x : T)
    {
      if (x == '.')
      {
        return false;
      }
    }
    return true;
  }

  vector<int> make_vec(string const &T)
  {
    int first{-1};
    vector<int> V;
    for (auto i = 0; i < W; i++)
    {
      if (T[i] == '.')
      {
        if (first == -1)
        {
          first = i;
        }
        V.push_back(i - first);
      }
    }
    return V;
  }

  bool is_one(vector<int> const &V)
  {
    if (V.size() < size_t{2})
    {
      return true;
    }
    assert(V[0] == 0);
    int g{V[1]};
    for (auto it = V.begin() + 1; it != V.end(); it++)
    {
      g = gcd(g, *it);
    }
    for (auto i = 0; i < 20; i++)
    {
      if (g == 1 << i)
      {
        return false;
      }
    }
    return true;
  }

  bool is_two(vector<int> const &V)
  {
    int X{static_cast<int>(V.size())};
    if (X <= 1)
    {
      assert(false);
      return false;
    }
    if (X == 2)
    {
      return true;
    }
    for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++)
    {
      int p{static_cast<int>(*it)};
      if (W / p + 1 < X / 2)
      {
        return false;
      }
      vector<set<int>> E(p);
      for (auto x : V)
      {
        E[x % p].insert(x);
      }
      for (auto k = 0; k < p; k++)
      {
        if (static_cast<int>(E[k].size()) < X / 2)
        {
          continue;
        }
        int first{-1};
        vector<int> W;
        for (auto x : V)
        {
          if (E[k].find(x) != E[k].end())
          {
            continue;
          }
          if (first == -1)
          {
            first = x;
          }
          W.push_back(x - first);
        }
        if (is_one(W))
        {
          return true;
        }
      }
    }
    return false;
  }
};

int main()
{
  int H, W;
  cin >> H >> W;
  vector<string> S(H);
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  Solve solve(H, W, S);
  cout << solve.calc() << endl;
}
<commit_msg>submit H.cpp to 'H - Stamps 3' (xmascon19) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 0
/**
 * File    : H.cpp
 * Author  : Kazune Takahashi
 * Created : 2019/12/30 18:11:35
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- PrimeNums -----

class PrimeNums
{
  static constexpr ll MAX_SIZE{1000010LL};
  ll N;
  vector<bool> isprime;
  vector<int> prime_nums;

public:
  PrimeNums(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{}
  {
    isprime[0] = isprime[1] = false;
    for (auto i = 2; i < N; i++)
    {
      if (isprime[i])
      {
        prime_nums.push_back(i);
        for (auto j = 2 * i; j < N; j += i)
        {
          isprime[j] = false;
        }
      }
    }
  }

  bool is_prime(long long x)
  { // 2 \leq x \leq MAX_SIZE^2
    if (x < N)
    {
      return isprime[x];
    }
    for (auto e : prime_nums)
    {
      if (x % e == 0)
        return false;
    }
    return true;
  }

  vector<int> const &primes() const
  {
    return prime_nums;
  }
};

// ----- main() -----
class Solve
{
  int H, W;
  vector<string> S;
  PrimeNums pn;

public:
  Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), pn{} {}

  int calc()
  {
    int ans{0};
    for (auto i = 0; i < H; i++)
    {
      ans += calc(S[i]);
    }
    return ans;
  };

private:
  int calc(string const &T)
  {
    if (is_zero(T))
    {
      return 0;
    }
    auto V{make_vec(T)};
    if (is_one(V))
    {
      return 1;
    }
    if (is_two(V))
    {
      return 2;
    }
    return 3;
  }

  bool is_zero(string const &T)
  {
    for (auto x : T)
    {
      if (x == '.')
      {
        return false;
      }
    }
    return true;
  }

  vector<int> make_vec(string const &T)
  {
    int first{-1};
    vector<int> V;
    for (auto i = 0; i < W; i++)
    {
      if (T[i] == '.')
      {
        if (first == -1)
        {
          first = i;
        }
        V.push_back(i - first);
      }
    }
    return V;
  }

  bool is_one(vector<int> const &V)
  {
    if (V.size() < size_t{2})
    {
      return true;
    }
    assert(V[0] == 0);
    int g{V[1]};
    for (auto it = V.begin() + 1; it != V.end(); it++)
    {
      g = gcd(g, *it);
    }
    for (auto i = 0; i < 20; i++)
    {
      if (g == 1 << i)
      {
        return false;
      }
    }
    return true;
  }

  bool is_two(vector<int> const &V)
  {
    int X{static_cast<int>(V.size())};
    if (X <= 1)
    {
      assert(false);
      return false;
    }
    if (X == 2)
    {
      return true;
    }
    for (auto it = pn.primes().begin() + 1; it != pn.primes().end(); it++)
    {
      int p{static_cast<int>(*it)};
      if ((W + p - 1) / p < X / 2)
      {
        return false;
      }
      vector<set<int>> E(p);
      for (auto x : V)
      {
        E[x % p].insert(x);
      }
      for (auto k = 0; k < p; k++)
      {
        if (static_cast<int>(E[k].size()) < X / 2)
        {
          continue;
        }
        int first{-1};
        vector<int> W;
        for (auto x : V)
        {
          if (E[k].find(x) != E[k].end())
          {
            continue;
          }
          if (first == -1)
          {
            first = x;
          }
          W.push_back(x - first);
        }
        if (is_one(W))
        {
          return true;
        }
      }
    }
    return false;
  }
};

int main()
{
  int H, W;
  cin >> H >> W;
  vector<string> S(H);
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  Solve solve(H, W, S);
  cout << solve.calc() << endl;
}
<|endoftext|>


<commit_before>/**
* Copyright (c) 2016 SQLines
*
* 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 "report.h"
#include "str.h"

// Constructor
Report::Report()
{
    _tpl_path = SQLEXEC_REPORT_TEMPLATE;
    _report_path = SQLEXEC_REPORT_FILE;
    _summary = "";
}

// Create a report file by template
void Report::CreateReport(Stats *stats, const char *summary)
{
    if(stats == NULL)
        return;

    _summary = summary;

    FILE *tpl_file = fopen(_tpl_path, "r");

    if(tpl_file == NULL)
    {
        printf("\n\nError: Cannot open report template file %s", _tpl_path);
        return;
    }

    FILE *file = fopen(_report_path, "w+");

    if(file == NULL)
    {
        printf("\n\nError: Cannot create report file %s", _report_path);
        return;
    }

    int c = 0;

    while((c = fgetc(tpl_file)) != EOF)
    {
        // Check for <?macro?> replacement macro
        if((char)c == '<')
        {
            int c2 = fgetc(tpl_file);

            if((char)c2 == '?')
            {
                std::string macro;
                std::string data;

                while(true)
                {
                    c = fgetc(tpl_file);
                    if(c == EOF || (char)c == '?')
                        break;

                    macro += (char)c;
                }

                GetReportSection(stats, macro, data);
                fprintf(file, "%s", data.c_str());

                // Consume closing >
                if(c != EOF)
                    fgetc(tpl_file);
            }
            // Forward character to the report file as is
            else
            {
                fputc(c, file);
                if((char)c2 != EOF)
                    fputc(c2, file);
                else
                    break;
            }
        }
        else
            fputc(c, file);
    }

    fclose(tpl_file);
    fclose(file);
}

// Fill the specified report section
void Report::GetReportSection(Stats *stats, std::string &macro, std::string &data)
{
    char num[12];

    int distinct = 0;
    int occurrences = 0;

    // Table of all data types
    if(_stricmp(macro.c_str(), "datatypes_table") == 0)
    {
        data += "

	Data Type	Occurrences
";

        GetReportSectionRows(stats->_data_types, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct data types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined and derived data types
    if(_stricmp(macro.c_str(), "udt_datatypes_table") == 0)
    {
        data += "

	Type	Occurrences
";

        GetReportSectionRows(stats->_udt_data_types, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined and derived data type details
    if(_stricmp(macro.c_str(), "udt_datatype_dtl_table") == 0)
    {
        data += "

	Type	Occurrences
";

        GetReportSectionRows(stats->_udt_data_types_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of data type details
    if(_stricmp(macro.c_str(), "datatype_dtl_table") == 0)
    {
        data += "

	Data Type	Occurrences
";

        GetReportSectionRows(stats->_data_types_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct data type specifications, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all built-in functions
    if(_stricmp(macro.c_str(), "builtin_func_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_builtin_func, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct functions, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all built-in functions details
    if(_stricmp(macro.c_str(), "builtin_func_dtl_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_builtin_func_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " function specifications, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined functions
    if(_stricmp(macro.c_str(), "udf_func_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_udf_func, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct functions, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all system procedures
    if(_stricmp(macro.c_str(), "system_proc_table") == 0)
    {
        data += "

	Procedure	Occurrences
";

        GetReportSectionRows(stats->_system_proc, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct procedures, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all system procedures details
    if(_stricmp(macro.c_str(), "system_proc_dtl_table") == 0)
    {
        data += "

	Procedure	Occurrences
";

        GetReportSectionRows(stats->_system_proc_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct procedures, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all statements
    if(_stricmp(macro.c_str(), "statements_table") == 0)
    {
        data += "

	Statement	Occurrences
";

        GetReportSectionRows(stats->_statements, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct statements, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of CREATE TABLE statements details
    if(_stricmp(macro.c_str(), "crtab_stmt_table") == 0)
    {
        data += "

	Details	Occurrences
";

        GetReportSectionRows(stats->_crtab_statements, data, &distinct, &occurrences);

        data += "
";
    }
    else
    // Table of ALTER TABLE statements details
    if(_stricmp(macro.c_str(), "alttab_stmt_table") == 0)
    {
        data += "

	Details	Occurrences
";

        GetReportSectionRows(stats->_alttab_statements, data, &distinct, &occurrences);

        data += "
";
    }
    else
    // Table of all procedural statements
    if(_stricmp(macro.c_str(), "pl_statements_table") == 0)
    {
        data += "

	Statement	Occurrences
";

        GetReportSectionRows(stats->_pl_statements, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct statements, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all double quoted identifiers
    if(_stricmp(macro.c_str(), "quoted_idents_table") == 0)
    {
        data += "

	Identifier	Occurrences
";

        GetReportSectionRows(stats->_quoted_idents, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct quoted identifiers, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all single quoted string literals
    if(_stricmp(macro.c_str(), "strings_table") == 0)
    {
        data += "

	String Literal	Occurrences
";

        GetReportSectionRows(stats->_strings, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct string literals, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all numeric literals
    if(_stricmp(macro.c_str(), "numbers_table") == 0)
    {
        data += "

	Numeric Literal	Occurrences
";

        GetReportSectionRows(stats->_numbers, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct numeric literals, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all words
    if(_stricmp(macro.c_str(), "words_table") == 0)
    {
        data += "

	Words	Occurrences
";

        GetReportSectionRows(stats->_words, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct words, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all delimiters
    if(_stricmp(macro.c_str(), "delimiters_table") == 0)
    {
        data += "

	Delimiters	Occurrences
";

        GetReportSectionRows(stats->_delimiters, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct delimiters, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Summary
    if(_stricmp(macro.c_str(), "summary") == 0)
        data += _summary;
}

void Report::GetReportSectionRows(std::map<std::string, int> &values, std::string &data,
                                  int *distinct, int *occurrences)
{
    char num[12];

    int row = 1;
    int dist = 0;
    int occur = 0;

    for(std::map<std::string, int>::iterator i = values.begin(); i != values.end(); i++, row++)
    {
        data += "
";
        sprintf(num, "%d", row);
        data += num;
        data += "	";
        sprintf(num, "%d", (*i).second);
        data += (*i).first;
        data += "	";
        data += num;
        data += "
";

        dist++;
        occur += (*i).second;
    }

    if(distinct != NULL)
        *distinct = dist;

    if(occurrences != NULL)
        *occurrences = occur;
}<commit_msg>report.cpp compiled for Linux<commit_after>/**
* Copyright (c) 2016 SQLines
*
* 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 "report.h"
#include "str.h"

// Constructor
Report::Report()
{
    _tpl_path = SQLEXEC_REPORT_TEMPLATE;
    _report_path = SQLEXEC_REPORT_FILE;
    _summary = "";
}

// Create a report file by template
void Report::CreateReport(Stats *stats, const char *summary)
{
    if(stats == NULL)
        return;

    _summary = summary;

    FILE *tpl_file = fopen(_tpl_path, "r");

    if(tpl_file == NULL)
    {
        printf("\n\nError: Cannot open report template file %s", _tpl_path);
        return;
    }

    FILE *file = fopen(_report_path, "w+");

    if(file == NULL)
    {
        printf("\n\nError: Cannot create report file %s", _report_path);
        return;
    }

    int c = 0;

    while((c = fgetc(tpl_file)) != EOF)
    {
        // Check for <?macro?> replacement macro
        if((char)c == '<')
        {
            int c2 = fgetc(tpl_file);

            if((char)c2 == '?')
            {
                std::string macro;
                std::string data;

                while(true)
                {
                    c = fgetc(tpl_file);
                    if(c == EOF || (char)c == '?')
                        break;

                    macro += (char)c;
                }

                GetReportSection(stats, macro, data);
                fprintf(file, "%s", data.c_str());

                // Consume closing >
                if(c != EOF)
                    fgetc(tpl_file);
            }
            // Forward character to the report file as is
            else
            {
                fputc(c, file);
                if((char)c2 != EOF)
                    fputc(c2, file);
                else
                    break;
            }
        }
        else
            fputc(c, file);
    }

    fclose(tpl_file);
    fclose(file);
}

// Fill the specified report section
void Report::GetReportSection(Stats *stats, std::string &macro, std::string &data)
{
    char num[12];

    int distinct = 0;
    int occurrences = 0;

    // Table of all data types
    if(_stricmp(macro.c_str(), "datatypes_table") == 0)
    {
        data += "

	Data Type	Occurrences
";

        GetReportSectionRows(stats->_data_types, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct data types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined and derived data types
    if(_stricmp(macro.c_str(), "udt_datatypes_table") == 0)
    {
        data += "

	Type	Occurrences
";

        GetReportSectionRows(stats->_udt_data_types, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined and derived data type details
    if(_stricmp(macro.c_str(), "udt_datatype_dtl_table") == 0)
    {
        data += "

	Type	Occurrences
";

        GetReportSectionRows(stats->_udt_data_types_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " types, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of data type details
    if(_stricmp(macro.c_str(), "datatype_dtl_table") == 0)
    {
        data += "

	Data Type	Occurrences
";

        GetReportSectionRows(stats->_data_types_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct data type specifications, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all built-in functions
    if(_stricmp(macro.c_str(), "builtin_func_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_builtin_func, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct functions, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all built-in functions details
    if(_stricmp(macro.c_str(), "builtin_func_dtl_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_builtin_func_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " function specifications, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all user-defined functions
    if(_stricmp(macro.c_str(), "udf_func_table") == 0)
    {
        data += "

	Function	Occurrences
";

        GetReportSectionRows(stats->_udf_func, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct functions, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all system procedures
    if(_stricmp(macro.c_str(), "system_proc_table") == 0)
    {
        data += "

	Procedure	Occurrences
";

        GetReportSectionRows(stats->_system_proc, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct procedures, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all system procedures details
    if(_stricmp(macro.c_str(), "system_proc_dtl_table") == 0)
    {
        data += "

	Procedure	Occurrences
";

        GetReportSectionRows(stats->_system_proc_dtl, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct procedures, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all statements
    if(_stricmp(macro.c_str(), "statements_table") == 0)
    {
        data += "

	Statement	Occurrences
";

        GetReportSectionRows(stats->_statements, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct statements, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of CREATE TABLE statements details
    if(_stricmp(macro.c_str(), "crtab_stmt_table") == 0)
    {
        data += "

	Details	Occurrences
";

        GetReportSectionRows(stats->_crtab_statements, data, &distinct, &occurrences);

        data += "
";
    }
    else
    // Table of ALTER TABLE statements details
    if(_stricmp(macro.c_str(), "alttab_stmt_table") == 0)
    {
        data += "

	Details	Occurrences
";

        GetReportSectionRows(stats->_alttab_statements, data, &distinct, &occurrences);

        data += "
";
    }
    else
    // Table of all procedural statements
    if(_stricmp(macro.c_str(), "pl_statements_table") == 0)
    {
        data += "

	Statement	Occurrences
";

        GetReportSectionRows(stats->_pl_statements, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct statements, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all double quoted identifiers
    if(_stricmp(macro.c_str(), "quoted_idents_table") == 0)
    {
        data += "

	Identifier	Occurrences
";

        GetReportSectionRows(stats->_quoted_idents, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct quoted identifiers, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all single quoted string literals
    if(_stricmp(macro.c_str(), "strings_table") == 0)
    {
        data += "

	String Literal	Occurrences
";

        GetReportSectionRows(stats->_strings, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct string literals, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all numeric literals
    if(_stricmp(macro.c_str(), "numbers_table") == 0)
    {
        data += "

	Numeric Literal	Occurrences
";

        GetReportSectionRows(stats->_numbers, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct numeric literals, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all words
    if(_stricmp(macro.c_str(), "words_table") == 0)
    {
        data += "

	Words	Occurrences
";

        GetReportSectionRows(stats->_words, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct words, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Table of all delimiters
    if(_stricmp(macro.c_str(), "delimiters_table") == 0)
    {
        data += "

	Delimiters	Occurrences
";

        GetReportSectionRows(stats->_delimiters, data, &distinct, &occurrences);

        data += "
";
        data += "
Total: ";
        sprintf(num, "%d", distinct);
        data += num;
        data += " distinct delimiters, ";
        sprintf(num, "%d", occurrences);
        data += num;
        data += " occurrences.
";
    }
    else
    // Summary
    if(_stricmp(macro.c_str(), "summary") == 0)
        data += _summary;
}

void Report::GetReportSectionRows(std::map<std::string, int> &values, std::string &data,
                                  int *distinct, int *occurrences)
{
    char num[12];

    int row = 1;
    int dist = 0;
    int occur = 0;

    for(std::map<std::string, int>::iterator i = values.begin(); i != values.end(); i++, row++)
    {
        data += "
";
        sprintf(num, "%d", row);
        data += num;
        data += "	";
        sprintf(num, "%d", (*i).second);
        data += (*i).first;
        data += "	";
        data += num;
        data += "
";

        dist++;
        occur += (*i).second;
    }

    if(distinct != NULL)
        *distinct = dist;

    if(occurrences != NULL)
        *occurrences = occur;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "itemreadervisitorstate.h"

#include "asttools.h"
#include "filecontext.h"
#include "itemreaderastvisitor.h"

#include <logging/translator.h>
#include <parser/qmljsengine_p.h>
#include <parser/qmljslexer_p.h>
#include <parser/qmljsparser_p.h>
#include <tools/error.h>

#include <QtCore/qshareddata.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qshareddata.h>
#include <QtCore/qtextstream.h>

namespace qbs {
namespace Internal {

class ASTCacheValueData : public QSharedData
{
    Q_DISABLE_COPY(ASTCacheValueData)
public:
    ASTCacheValueData()
        : ast(nullptr)
        , processing(false)
    {
    }

    QString code;
    QbsQmlJS::Engine engine;
    QbsQmlJS::AST::UiProgram *ast;
    bool processing;
};

class ASTCacheValue
{
public:
    ASTCacheValue()
        : d(new ASTCacheValueData)
    {
    }

    ASTCacheValue(const ASTCacheValue &other) = default;

    void setProcessingFlag(bool b) { d->processing = b; }
    bool isProcessing() const { return d->processing; }

    void setCode(const QString &code) { d->code = code; }
    QString code() const { return d->code; }

    QbsQmlJS::Engine *engine() const { return &d->engine; }

    void setAst(QbsQmlJS::AST::UiProgram *ast) { d->ast = ast; }
    QbsQmlJS::AST::UiProgram *ast() const { return d->ast; }
    bool isValid() const { return d->ast; }

private:
    QExplicitlySharedDataPointer<ASTCacheValueData> d;
};

class ItemReaderVisitorState::ASTCache : public QHash<QString, ASTCacheValue> {};

ItemReaderVisitorState::ItemReaderVisitorState(Logger &logger)
    : m_logger(logger)
    , m_astCache(std::make_unique<ASTCache>())
{

}

ItemReaderVisitorState::~ItemReaderVisitorState() = default;

Item *ItemReaderVisitorState::readFile(const QString &filePath, const QStringList &searchPaths,
                                  ItemPool *itemPool)
{
    ASTCacheValue &cacheValue = (*m_astCache)[filePath];
    if (cacheValue.isValid()) {
        if (Q_UNLIKELY(cacheValue.isProcessing()))
            throw ErrorInfo(Tr::tr("Loop detected when importing '%1'.").arg(filePath));
    } else {
        QFile file(filePath);
        if (Q_UNLIKELY(!file.open(QFile::ReadOnly)))
            throw ErrorInfo(Tr::tr("Cannot open '%1'.").arg(filePath));

        m_filesRead.insert(filePath);
        QTextStream stream(&file);
        setupDefaultCodec(stream);
        const QString &code = stream.readAll();
        QbsQmlJS::Lexer lexer(cacheValue.engine());
        lexer.setCode(code, 1);
        QbsQmlJS::Parser parser(cacheValue.engine());

        file.close();
        if (!parser.parse()) {
            const QList<QbsQmlJS::DiagnosticMessage> &parserMessages = parser.diagnosticMessages();
            if (Q_UNLIKELY(!parserMessages.empty())) {
                ErrorInfo err;
                for (const QbsQmlJS::DiagnosticMessage &msg : parserMessages)
                    err.append(msg.message, toCodeLocation(filePath, msg.loc));
                throw err;
            }
        }

        cacheValue.setCode(code);
        cacheValue.setAst(parser.ast());
    }

    const FileContextPtr file = FileContext::create();
    file->setFilePath(QFileInfo(filePath).absoluteFilePath());
    file->setContent(cacheValue.code());
    file->setSearchPaths(searchPaths);

    ItemReaderASTVisitor astVisitor(*this, file, itemPool, m_logger);
    {
        class ProcessingFlagManager {
        public:
            ProcessingFlagManager(ASTCacheValue &v) : m_cacheValue(v) { v.setProcessingFlag(true); }
            ~ProcessingFlagManager() { m_cacheValue.setProcessingFlag(false); }
        private:
            ASTCacheValue &m_cacheValue;
        } processingFlagManager(cacheValue);
        cacheValue.ast()->accept(&astVisitor);
    }
    astVisitor.checkItemTypes();
    return astVisitor.rootItem();
}

void ItemReaderVisitorState::cacheDirectoryEntries(const QString &dirPath, const QStringList &entries)
{
    m_directoryEntries.insert(dirPath, entries);
}

bool ItemReaderVisitorState::findDirectoryEntries(const QString &dirPath, QStringList *entries) const
{
    const auto it = m_directoryEntries.constFind(dirPath);
    if (it == m_directoryEntries.constEnd())
        return false;
    *entries = it.value();
    return true;
}

Item *ItemReaderVisitorState::mostDerivingItem() const
{
    return m_mostDerivingItem;
}

void ItemReaderVisitorState::setMostDerivingItem(Item *item)
{
    m_mostDerivingItem = item;
}

} // namespace Internal
} // namespace qbs
<commit_msg>qt6: fix crash in ItemReaderVisitorState::readFile<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "itemreadervisitorstate.h"

#include "asttools.h"
#include "filecontext.h"
#include "itemreaderastvisitor.h"

#include <logging/translator.h>
#include <parser/qmljsengine_p.h>
#include <parser/qmljslexer_p.h>
#include <parser/qmljsparser_p.h>
#include <tools/error.h>

#include <QtCore/qshareddata.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qshareddata.h>
#include <QtCore/qtextstream.h>

namespace qbs {
namespace Internal {

class ASTCacheValueData : public QSharedData
{
    Q_DISABLE_COPY(ASTCacheValueData)
public:
    ASTCacheValueData()
        : ast(nullptr)
        , processing(false)
    {
    }

    QString code;
    QbsQmlJS::Engine engine;
    QbsQmlJS::AST::UiProgram *ast;
    bool processing;
};

class ASTCacheValue
{
public:
    ASTCacheValue()
        : d(new ASTCacheValueData)
    {
    }

    ASTCacheValue(const ASTCacheValue &other) = default;

    void setProcessingFlag(bool b) { d->processing = b; }
    bool isProcessing() const { return d->processing; }

    void setCode(const QString &code) { d->code = code; }
    QString code() const { return d->code; }

    QbsQmlJS::Engine *engine() const { return &d->engine; }

    void setAst(QbsQmlJS::AST::UiProgram *ast) { d->ast = ast; }
    QbsQmlJS::AST::UiProgram *ast() const { return d->ast; }
    bool isValid() const { return d->ast; }

private:
    QExplicitlySharedDataPointer<ASTCacheValueData> d;
};

class ItemReaderVisitorState::ASTCache : public std::unordered_map<QString, ASTCacheValue> {};

ItemReaderVisitorState::ItemReaderVisitorState(Logger &logger)
    : m_logger(logger)
    , m_astCache(std::make_unique<ASTCache>())
{

}

ItemReaderVisitorState::~ItemReaderVisitorState() = default;

Item *ItemReaderVisitorState::readFile(const QString &filePath, const QStringList &searchPaths,
                                  ItemPool *itemPool)
{
    ASTCacheValue &cacheValue = (*m_astCache)[filePath];
    if (cacheValue.isValid()) {
        if (Q_UNLIKELY(cacheValue.isProcessing()))
            throw ErrorInfo(Tr::tr("Loop detected when importing '%1'.").arg(filePath));
    } else {
        QFile file(filePath);
        if (Q_UNLIKELY(!file.open(QFile::ReadOnly)))
            throw ErrorInfo(Tr::tr("Cannot open '%1'.").arg(filePath));

        m_filesRead.insert(filePath);
        QTextStream stream(&file);
        setupDefaultCodec(stream);
        const QString &code = stream.readAll();
        QbsQmlJS::Lexer lexer(cacheValue.engine());
        lexer.setCode(code, 1);
        QbsQmlJS::Parser parser(cacheValue.engine());

        file.close();
        if (!parser.parse()) {
            const QList<QbsQmlJS::DiagnosticMessage> &parserMessages = parser.diagnosticMessages();
            if (Q_UNLIKELY(!parserMessages.empty())) {
                ErrorInfo err;
                for (const QbsQmlJS::DiagnosticMessage &msg : parserMessages)
                    err.append(msg.message, toCodeLocation(filePath, msg.loc));
                throw err;
            }
        }

        cacheValue.setCode(code);
        cacheValue.setAst(parser.ast());
    }

    const FileContextPtr file = FileContext::create();
    file->setFilePath(QFileInfo(filePath).absoluteFilePath());
    file->setContent(cacheValue.code());
    file->setSearchPaths(searchPaths);

    ItemReaderASTVisitor astVisitor(*this, file, itemPool, m_logger);
    {
        class ProcessingFlagManager {
        public:
            ProcessingFlagManager(ASTCacheValue &v) : m_cacheValue(v) { v.setProcessingFlag(true); }
            ~ProcessingFlagManager() { m_cacheValue.setProcessingFlag(false); }
        private:
            ASTCacheValue &m_cacheValue;
        } processingFlagManager(cacheValue);
        cacheValue.ast()->accept(&astVisitor);
    }
    astVisitor.checkItemTypes();
    return astVisitor.rootItem();
}

void ItemReaderVisitorState::cacheDirectoryEntries(const QString &dirPath, const QStringList &entries)
{
    m_directoryEntries.insert(dirPath, entries);
}

bool ItemReaderVisitorState::findDirectoryEntries(const QString &dirPath, QStringList *entries) const
{
    const auto it = m_directoryEntries.constFind(dirPath);
    if (it == m_directoryEntries.constEnd())
        return false;
    *entries = it.value();
    return true;
}

Item *ItemReaderVisitorState::mostDerivingItem() const
{
    return m_mostDerivingItem;
}

void ItemReaderVisitorState::setMostDerivingItem(Item *item)
{
    m_mostDerivingItem = item;
}

} // namespace Internal
} // namespace qbs
<|endoftext|>


<commit_before>#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/errqueue.h>
#include <linux/icmp.h>
#include <sys/socket.h>
#include <sys/time.h>

#include "udpping.h"

namespace
{
    bool getAddress(const QString &address, sockaddr_any *addr)
    {
        struct addrinfo hints;
        struct addrinfo *rp = NULL, *result = NULL;

        memset(&hints, 0, sizeof(hints));
        hints.ai_family = PF_UNSPEC;

        if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result))
        {
            return false;
        }

        for (rp = result; rp && rp->ai_family != AF_INET &&
             rp->ai_family != AF_INET6;
             rp = rp->ai_next)
        {
        }

        if (!rp)
        {
            freeaddrinfo(result);
            return false;
        }

        memcpy(addr, rp->ai_addr, rp->ai_addrlen);

        freeaddrinfo(result);

        return true;
    }

    void randomizePayload(char *payload, const quint32 size)
    {
        char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        for (quint32 i = 0; i < size; i++)
        {
            payload[i] = chars[qrand() % strlen(chars)];
        }

        if (size > 15)
        {
            // ignore terminating null character
            strncpy(&payload[size - 15], " measure-it.net", 15);
        }
    }
}

UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress()
, m_payload(NULL)
{
}

UdpPing::~UdpPing()
{
}

Measurement::Status UdpPing::status() const
{
    return currentStatus;
}

void UdpPing::setStatus(Status status)
{
    if (currentStatus != status)
    {
        currentStatus = status;
        emit statusChanged(status);
    }
}

bool UdpPing::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition)
{
    Q_UNUSED(networkManager);

    definition = measurementDefinition.dynamicCast<UdpPingDefinition>();

    if (definition->payload > 1400)
    {
        emit error("payload is too large (> 1400 bytes)");
        return false;
    }

    if (definition->receiveTimeout > 60000)
    {
        emit error("receive timeout is too large (> 60 s)");
        return false;
    }

    memset(&m_destAddress, 0, sizeof(m_destAddress));

    // resolve
    if (!getAddress(definition->url, &m_destAddress))
    {
        return false;
    }

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        m_destAddress.sin6.sin6_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
    }

    return true;
}

bool UdpPing::start()
{
    PingProbe probe;

    // include null-character
    m_payload = new char[definition->payload + 1];
    memset(m_payload, 0, definition->payload + 1);

    setStartDateTime(QDateTime::currentDateTime());

    setStatus(UdpPing::Running);

    memset(&probe, 0, sizeof(probe));
    probe.sock = initSocket();

    if (probe.sock < 0)
    {
        emit error(QString("socket: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        delete[] m_payload;
        return false;
    }

    for (quint32 i = 0; i < definition->count; i++)
    {
        ping(&probe);
        m_pingProbes.append(probe);
    }

    close(probe.sock);

    setStatus(UdpPing::Finished);
    delete[] m_payload;
    emit finished();

    return true;
}

bool UdpPing::stop()
{
    return true;
}

ResultPtr UdpPing::result() const
{
    QVariantList res;

    foreach (const PingProbe &probe, m_pingProbes)
    {
        if (probe.sendTime > 0 && probe.recvTime > 0)
        {
            res << probe.recvTime - probe.sendTime;
        }
    }

    return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant()));
}

int UdpPing::initSocket()
{
    int n = 0;
    int sock = 0;
    int ttl = definition->ttl ? definition->ttl : 64;
    sockaddr_any src_addr;

    memset(&src_addr, 0, sizeof(src_addr));

    sock = socket(m_destAddress.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);

    if (sock < 0)
    {
        emit error(QString("socket: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        return -1;
    }

    src_addr.sa.sa_family = m_destAddress.sa.sa_family;

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        src_addr.sin.sin_port = htons(definition->sourcePort);
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        src_addr.sin6.sin6_port = htons(definition->sourcePort);
    }

    if (src_addr.sa.sa_family == AF_INET)
    {
        n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin));
    }
    else if (src_addr.sa.sa_family == AF_INET6)
    {
        n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin6));
    }

    if (n < 0)
    {
        emit error(QString("bind: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    n = 1;

    if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0)
    {
        emit error(QString("setsockopt SOL_TIMESTAMP: %1").arg(
                       QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    // set TTL
    if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
    {
        emit error(QString("setsockopt IP_TTL: %1").arg(
                       QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    // use RECVRR
    n = 1;

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0)
        {
            emit error(QString("setsockopt IP_RECVERR: %1").arg(
                           QString::fromLocal8Bit(strerror(errno))));
            goto cleanup;
        }
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &n, sizeof(n)) < 0)
        {
            emit error(QString("setsockopt IPV6_RECVERR: %1").arg(
                           QString::fromLocal8Bit(strerror(errno))));
            goto cleanup;
        }
    }

    return sock;

cleanup:
    close(sock);
    return -1;
}

bool UdpPing::sendData(PingProbe *probe)
{
    int n = 0;
    struct timeval tv;

    memset(&tv, 0, sizeof(tv));
    gettimeofday(&tv, NULL);
    probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec;

    // randomize payload to prevent caching
    randomizePayload(m_payload, definition->payload);

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        n = sendto(probe->sock, m_payload, definition->payload, 0,
                   (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin));
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        n = sendto(probe->sock, m_payload, definition->payload, 0,
                   (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin6));
    }

    if (n < 0)
    {
        emit error(QString("send: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        return false;
    }

    return true;
}

void UdpPing::receiveData(PingProbe *probe)
{
    struct msghdr msg;
    sockaddr_any from;
    struct iovec iov;
    char buf[1280];
    char control[1024];
    struct cmsghdr *cm;
    struct sock_extended_err *ee = NULL;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = &from;
    msg.msg_namelen = sizeof(from);
    msg.msg_control = control;
    msg.msg_controllen = sizeof(control);
    iov.iov_base = buf;
    iov.iov_len = sizeof(buf);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    // poll here
    struct pollfd pfd;
    memset(&pfd, 0, sizeof(pfd));
    pfd.fd = probe->sock;
    pfd.events = POLLIN | POLLERR;

    if (poll(&pfd, 1, definition->receiveTimeout) < 0)
    {
        emit error(QString("poll: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    if (!pfd.revents)
    {
        emit timeout(*probe);
        goto cleanup;
    }

    if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0)
    {
        emit error(QString("recvmsg: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm))
    {
        void *ptr = CMSG_DATA(cm);

        if (cm->cmsg_level == SOL_SOCKET)
        {

            if (cm->cmsg_type == SO_TIMESTAMP)
            {
                struct timeval *tv = (struct timeval *) ptr;
                probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec;
            }
        }
        else if (cm->cmsg_level == SOL_IP)
        {
            if (cm->cmsg_type == IP_RECVERR)
            {
                ee = (struct sock_extended_err *) ptr;

                if (ee->ee_origin != SO_EE_ORIGIN_ICMP)
                {
                    ee = NULL;
                    continue;
                }

                if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT)
                {
                    goto cleanup;
                }
            }
        }
    }

    if (ee)
    {
        memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source));

        if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL)
        {
            emit ttlExceeded(*probe);
        }
        else if (ee->ee_type == ICMP_DEST_UNREACH)
        {
            emit destinationUnreachable(*probe);
        }
    }

cleanup:
    return;
}

void UdpPing::ping(PingProbe *probe)
{
    // send
    if (sendData(probe))
    {
        receiveData(probe);
    }
}

// vim: set sts=4 sw=4 et:
<commit_msg>udpping: handle UDP responses<commit_after>#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/errqueue.h>
#include <linux/icmp.h>
#include <sys/socket.h>
#include <sys/time.h>

#include "udpping.h"

namespace
{
    bool getAddress(const QString &address, sockaddr_any *addr)
    {
        struct addrinfo hints;
        struct addrinfo *rp = NULL, *result = NULL;

        memset(&hints, 0, sizeof(hints));
        hints.ai_family = PF_UNSPEC;

        if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result))
        {
            return false;
        }

        for (rp = result; rp && rp->ai_family != AF_INET &&
             rp->ai_family != AF_INET6;
             rp = rp->ai_next)
        {
        }

        if (!rp)
        {
            freeaddrinfo(result);
            return false;
        }

        memcpy(addr, rp->ai_addr, rp->ai_addrlen);

        freeaddrinfo(result);

        return true;
    }

    void randomizePayload(char *payload, const quint32 size)
    {
        char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        for (quint32 i = 0; i < size; i++)
        {
            payload[i] = chars[qrand() % strlen(chars)];
        }

        if (size > 15)
        {
            // ignore terminating null character
            strncpy(&payload[size - 15], " measure-it.net", 15);
        }
    }
}

UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress()
, m_payload(NULL)
{
}

UdpPing::~UdpPing()
{
}

Measurement::Status UdpPing::status() const
{
    return currentStatus;
}

void UdpPing::setStatus(Status status)
{
    if (currentStatus != status)
    {
        currentStatus = status;
        emit statusChanged(status);
    }
}

bool UdpPing::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition)
{
    Q_UNUSED(networkManager);

    definition = measurementDefinition.dynamicCast<UdpPingDefinition>();

    if (definition->payload > 1400)
    {
        emit error("payload is too large (> 1400 bytes)");
        return false;
    }

    if (definition->receiveTimeout > 60000)
    {
        emit error("receive timeout is too large (> 60 s)");
        return false;
    }

    memset(&m_destAddress, 0, sizeof(m_destAddress));

    // resolve
    if (!getAddress(definition->url, &m_destAddress))
    {
        return false;
    }

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        m_destAddress.sin6.sin6_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
    }

    return true;
}

bool UdpPing::start()
{
    PingProbe probe;

    // include null-character
    m_payload = new char[definition->payload + 1];
    memset(m_payload, 0, definition->payload + 1);

    setStartDateTime(QDateTime::currentDateTime());

    setStatus(UdpPing::Running);

    memset(&probe, 0, sizeof(probe));
    probe.sock = initSocket();

    if (probe.sock < 0)
    {
        emit error(QString("socket: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        delete[] m_payload;
        return false;
    }

    for (quint32 i = 0; i < definition->count; i++)
    {
        ping(&probe);
        m_pingProbes.append(probe);
    }

    close(probe.sock);

    setStatus(UdpPing::Finished);
    delete[] m_payload;
    emit finished();

    return true;
}

bool UdpPing::stop()
{
    return true;
}

ResultPtr UdpPing::result() const
{
    QVariantList res;

    foreach (const PingProbe &probe, m_pingProbes)
    {
        if (probe.sendTime > 0 && probe.recvTime > 0)
        {
            res << probe.recvTime - probe.sendTime;
        }
    }

    return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant()));
}

int UdpPing::initSocket()
{
    int n = 0;
    int sock = 0;
    int ttl = definition->ttl ? definition->ttl : 64;
    sockaddr_any src_addr;

    memset(&src_addr, 0, sizeof(src_addr));

    sock = socket(m_destAddress.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);

    if (sock < 0)
    {
        emit error(QString("socket: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        return -1;
    }

    src_addr.sa.sa_family = m_destAddress.sa.sa_family;

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        src_addr.sin.sin_port = htons(definition->sourcePort);
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        src_addr.sin6.sin6_port = htons(definition->sourcePort);
    }

    if (src_addr.sa.sa_family == AF_INET)
    {
        n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin));
    }
    else if (src_addr.sa.sa_family == AF_INET6)
    {
        n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin6));
    }

    if (n < 0)
    {
        emit error(QString("bind: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    n = 1;

    if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0)
    {
        emit error(QString("setsockopt SOL_TIMESTAMP: %1").arg(
                       QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    // set TTL
    if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
    {
        emit error(QString("setsockopt IP_TTL: %1").arg(
                       QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    // use RECVRR
    n = 1;

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0)
        {
            emit error(QString("setsockopt IP_RECVERR: %1").arg(
                           QString::fromLocal8Bit(strerror(errno))));
            goto cleanup;
        }
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &n, sizeof(n)) < 0)
        {
            emit error(QString("setsockopt IPV6_RECVERR: %1").arg(
                           QString::fromLocal8Bit(strerror(errno))));
            goto cleanup;
        }
    }

    return sock;

cleanup:
    close(sock);
    return -1;
}

bool UdpPing::sendData(PingProbe *probe)
{
    int n = 0;
    struct timeval tv;

    memset(&tv, 0, sizeof(tv));
    gettimeofday(&tv, NULL);
    probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec;

    // randomize payload to prevent caching
    randomizePayload(m_payload, definition->payload);

    if (m_destAddress.sa.sa_family == AF_INET)
    {
        n = sendto(probe->sock, m_payload, definition->payload, 0,
                   (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin));
    }
    else if (m_destAddress.sa.sa_family == AF_INET6)
    {
        n = sendto(probe->sock, m_payload, definition->payload, 0,
                   (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin6));
    }

    if (n < 0)
    {
        emit error(QString("send: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        return false;
    }

    return true;
}

void UdpPing::receiveData(PingProbe *probe)
{
    struct msghdr msg;
    sockaddr_any from;
    struct iovec iov;
    char buf[1500];
    char control[CMSG_SPACE(sizeof(probe->sock))];
    struct cmsghdr *cm;
    struct sock_extended_err *ee = NULL;
    struct timeval *tv;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = &from;
    msg.msg_namelen = sizeof(from);
    msg.msg_control = control;
    msg.msg_controllen = sizeof(control);
    iov.iov_base = buf;
    iov.iov_len = sizeof(buf);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    // poll here
    struct pollfd pfd;
    memset(&pfd, 0, sizeof(pfd));
    pfd.fd = probe->sock;
    pfd.events = POLLIN | POLLERR;

    if (poll(&pfd, 1, definition->receiveTimeout) < 0)
    {
        emit error(QString("poll: %1").arg(QString::fromLocal8Bit(strerror(errno))));
        goto cleanup;
    }

    if (!pfd.revents)
    {
        emit timeout(*probe);
        goto cleanup;
    }

    if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0)
    {
        // receive UDP packet
        if (recvmsg(probe->sock, &msg, 0) < 0)
        {
            emit error(QString("recvmsg: %1").arg(QString::fromLocal8Bit(strerror(errno))));
            goto cleanup;
        }

        // msg_name provides the source address if the initial request packet
        // was successful
        memcpy(&probe->source, &from, sizeof(sockaddr_any));
    }

    for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm))
    {
        void *ptr = CMSG_DATA(cm);

        switch (cm->cmsg_level)
        {
        case SOL_SOCKET:
            switch (cm->cmsg_type)
            {
            case SO_TIMESTAMP:
                tv = (struct timeval *) ptr;
                probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec;
                break;
            }

            break;

        case SOL_IP:
            switch (cm->cmsg_type)
            {
            case IP_RECVERR:
                ee = (struct sock_extended_err *) ptr;

                if (ee->ee_origin != SO_EE_ORIGIN_ICMP)
                {
                    ee = NULL;
                    continue;
                }

                if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT)
                {
                    goto cleanup;
                }

                break;

            default:
                break;
            }

            break;

        default:
            break;
        }
    }

    if (ee)
    {
        memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source));

        if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL)
        {
            emit ttlExceeded(*probe);
        }
        else if (ee->ee_type == ICMP_DEST_UNREACH)
        {
            emit destinationUnreachable(*probe);
        }
    }

cleanup:
    return;
}

void UdpPing::ping(PingProbe *probe)
{
    // send
    if (sendData(probe))
    {
        receiveData(probe);
    }
}

// vim: set sts=4 sw=4 et:
<|endoftext|>


<commit_before>#include "PcapDevice.h"
#include "PcapFilter.h"
#include "Logger.h"
#include "TimespecTimeval.h"
#include <pcap.h>

namespace pcpp
{

IPcapDevice::~IPcapDevice()
{
}

bool IPcapDevice::setFilter(std::string filterAsString)
{
	LOG_DEBUG("Filter to be set: '%s'", filterAsString.c_str());
	if (!m_DeviceOpened)
	{
		LOG_ERROR("Device not Opened!! cannot set filter");
		return false;
	}

	struct bpf_program prog;
	LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
	if (pcap_compile(m_PcapDescriptor, &prog, filterAsString.c_str(), 1, 0) < 0)
	{
		/*
		* Print out appropriate text, followed by the error message
		* generated by the packet capture library.
		*/
		LOG_ERROR("Error compiling filter. Error message is: %s", pcap_geterr(m_PcapDescriptor));
		pcap_freecode(&prog);
		return false;
	}

	LOG_DEBUG("Setting the compiled filter");
	if (pcap_setfilter(m_PcapDescriptor, &prog) < 0)
	{
		/*
		 * Print out error. The format will be the prefix string,
		 * created above, followed by the error message that the packet
		 * capture library generates.
		 */
		LOG_ERROR("Error setting a compiled filter. Error message is: %s", pcap_geterr(m_PcapDescriptor));
		pcap_freecode(&prog);
		return false;
	}

	LOG_DEBUG("Filter set successfully");

	pcap_freecode(&prog);

	return true;
}

bool IPcapDevice::clearFilter()
{
	return setFilter("");
}

bool IPcapDevice::verifyFilter(std::string filterAsString)
{
	struct bpf_program prog;
	LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
	if (pcap_compile_nopcap(9000, pcpp::LINKTYPE_ETHERNET, &prog, filterAsString.c_str(), 1, 0) < 0)
	{
		return false;
	}
	pcap_freecode(&prog);
	return true;
}

bool IPcapDevice::matchPacketWithFilter(std::string filterAsString, RawPacket* rawPacket)
{
	static std::string curFilter = "";
	static struct bpf_program prog;
	if ( (curFilter != filterAsString) || (prog.bf_insns == nullptr) )
	{
		LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
		pcap_freecode(&prog);
		if (pcap_compile_nopcap(9000, pcpp::LINKTYPE_ETHERNET, &prog, filterAsString.c_str(), 1, 0) < 0)
		{
			return false;
		}
		curFilter = filterAsString;
	}

	struct pcap_pkthdr pktHdr;
	pktHdr.caplen = rawPacket->getRawDataLen();
	pktHdr.len = rawPacket->getRawDataLen();
	timespec ts = rawPacket->getPacketTimeStamp();
	TIMESPEC_TO_TIMEVAL(&pktHdr.ts, &ts);

	return (pcap_offline_filter(&prog, &pktHdr, rawPacket->getRawData()) != 0);
}

bool IPcapDevice::matchPacketWithFilter(GeneralFilter& filter, RawPacket* rawPacket)
{
	return filter.matchPacketWithFilter(rawPacket);
}

std::string IPcapDevice::getPcapLibVersionInfo()
{
	return std::string(pcap_lib_version());
}

} // namespace pcpp
<commit_msg>matchPacketWithFilter, change nullptr to NULL.<commit_after>#include "PcapDevice.h"
#include "PcapFilter.h"
#include "Logger.h"
#include "TimespecTimeval.h"
#include <pcap.h>

namespace pcpp
{

IPcapDevice::~IPcapDevice()
{
}

bool IPcapDevice::setFilter(std::string filterAsString)
{
	LOG_DEBUG("Filter to be set: '%s'", filterAsString.c_str());
	if (!m_DeviceOpened)
	{
		LOG_ERROR("Device not Opened!! cannot set filter");
		return false;
	}

	struct bpf_program prog;
	LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
	if (pcap_compile(m_PcapDescriptor, &prog, filterAsString.c_str(), 1, 0) < 0)
	{
		/*
		* Print out appropriate text, followed by the error message
		* generated by the packet capture library.
		*/
		LOG_ERROR("Error compiling filter. Error message is: %s", pcap_geterr(m_PcapDescriptor));
		pcap_freecode(&prog);
		return false;
	}

	LOG_DEBUG("Setting the compiled filter");
	if (pcap_setfilter(m_PcapDescriptor, &prog) < 0)
	{
		/*
		 * Print out error. The format will be the prefix string,
		 * created above, followed by the error message that the packet
		 * capture library generates.
		 */
		LOG_ERROR("Error setting a compiled filter. Error message is: %s", pcap_geterr(m_PcapDescriptor));
		pcap_freecode(&prog);
		return false;
	}

	LOG_DEBUG("Filter set successfully");

	pcap_freecode(&prog);

	return true;
}

bool IPcapDevice::clearFilter()
{
	return setFilter("");
}

bool IPcapDevice::verifyFilter(std::string filterAsString)
{
	struct bpf_program prog;
	LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
	if (pcap_compile_nopcap(9000, pcpp::LINKTYPE_ETHERNET, &prog, filterAsString.c_str(), 1, 0) < 0)
	{
		return false;
	}
	pcap_freecode(&prog);
	return true;
}

bool IPcapDevice::matchPacketWithFilter(std::string filterAsString, RawPacket* rawPacket)
{
	static std::string curFilter = "";
	static struct bpf_program prog;
	if ( (curFilter != filterAsString) || (prog.bf_insns == NULL) )
	{
		LOG_DEBUG("Compiling the filter '%s'", filterAsString.c_str());
		pcap_freecode(&prog);
		if (pcap_compile_nopcap(9000, pcpp::LINKTYPE_ETHERNET, &prog, filterAsString.c_str(), 1, 0) < 0)
		{
			return false;
		}
		curFilter = filterAsString;
	}

	struct pcap_pkthdr pktHdr;
	pktHdr.caplen = rawPacket->getRawDataLen();
	pktHdr.len = rawPacket->getRawDataLen();
	timespec ts = rawPacket->getPacketTimeStamp();
	TIMESPEC_TO_TIMEVAL(&pktHdr.ts, &ts);

	return (pcap_offline_filter(&prog, &pktHdr, rawPacket->getRawData()) != 0);
}

bool IPcapDevice::matchPacketWithFilter(GeneralFilter& filter, RawPacket* rawPacket)
{
	return filter.matchPacketWithFilter(rawPacket);
}

std::string IPcapDevice::getPcapLibVersionInfo()
{
	return std::string(pcap_lib_version());
}

} // namespace pcpp
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <locale>

// template <> class ctype<char>

// ~ctype();

#include <locale>
#include <cassert>
#include <new>

unsigned delete_called = 0;

void operator delete[](void* p) throw()
{
    operator delete(p);
    ++delete_called;
}

int main()
{
    {
        delete_called = 0;
        std::locale l(std::locale::classic(), new std::ctype<char>);
        assert(delete_called == 0);
    }
    assert(delete_called == 0);
    {
        std::ctype<char>::mask table[256];
        delete_called = 0;
        std::locale l(std::locale::classic(), new std::ctype<char>(table));
        assert(delete_called == 0);
    }
    assert(delete_called == 0);
    {
        delete_called = 0;
        std::locale l(std::locale::classic(),
            new std::ctype<char>(new std::ctype<char>::mask[256], true));
        assert(delete_called == 0);
    }
    assert(delete_called == 1);
}
<commit_msg>Add operator new[] to test.  Partial fix for valgrind warning in http://llvm.org/bugs/show_bug.cgi?id=16703.<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <locale>

// template <> class ctype<char>

// ~ctype();

#include <locale>
#include <cassert>
#include <new>

unsigned delete_called = 0;

void* operator new[](size_t sz)
{
    return operator new(sz);
}

void operator delete[](void* p) throw()
{
    operator delete(p);
    ++delete_called;
}

int main()
{
    {
        delete_called = 0;
        std::locale l(std::locale::classic(), new std::ctype<char>);
        assert(delete_called == 0);
    }
    assert(delete_called == 0);
    {
        std::ctype<char>::mask table[256];
        delete_called = 0;
        std::locale l(std::locale::classic(), new std::ctype<char>(table));
        assert(delete_called == 0);
    }
    assert(delete_called == 0);
    {
        delete_called = 0;
        std::locale l(std::locale::classic(),
            new std::ctype<char>(new std::ctype<char>::mask[256], true));
        assert(delete_called == 0);
    }
    assert(delete_called == 1);
}
<|endoftext|>


<commit_before>#include "test_helper.h"
#include "base64.c"
#include "helpers/load_language.h"
#include "helpers/tree_helpers.h"
#include "helpers/record_alloc.h"

START_TEST

vector<pair<string, string>> examples({
  // {
  //   "javascript",
  //   "Bi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLXGK0i0vLS0tLS0tLS0tLS0tLS0tLS0tLS0tLXGK0i0vLS0tLS0tLS0tLS0tLS0xLS0tLTYtLfpZAA=="
  // },
});

describe("examples found via fuzzing", [&]() {
  before_each([&]() {
    record_alloc::start();
  });

  after_each([&]() {
    AssertThat(record_alloc::outstanding_allocation_indices(), IsEmpty());
  });

  for (unsigned i = 0, n = examples.size(); i < n; i++) {

    it(("parses example number " + to_string(i)).c_str(), [&]() {
      TSDocument *document = ts_document_new();
      // ts_document_print_debugging_graphs(document, true);

      const string &language_name = examples[i].first;
      ts_document_set_language(document, load_real_language(language_name));

      string input;
      const string &base64_input = examples[i].second;
      input.resize(base64_input.size());
      input.resize(base64_decode(
        reinterpret_cast<const unsigned char *>(base64_input.c_str()),
        reinterpret_cast<unsigned char *>(&input[0]),
        base64_input.size()
      ));

      ts_document_set_input_string_with_length(
        document,
        input.c_str(),
        input.size()
      );

      ts_document_parse(document);

      TSNode node = ts_document_root_node(document);
      assert_consistent_tree_sizes(node);

      ts_document_free(document);
    });

  }
});

END_TEST
<commit_msg>Add testcase for parser__advance assertion failure<commit_after>#include "test_helper.h"
#include "base64.c"
#include "helpers/load_language.h"
#include "helpers/tree_helpers.h"
#include "helpers/record_alloc.h"

START_TEST

vector<pair<string, string>> examples({
  // {
  //   "javascript",
  //   "Bi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLXGK0i0vLS0tLS0tLS0tLS0tLS0tLS0tLS0tLXGK0i0vLS0tLS0tLS0tLS0tLS0xLS0tLTYtLfpZAA=="
  // },
  {
    "python",
    "NWNvbogsKTMsLCwsY29uiCwqLDo1Y29uLA=="
  },
});

describe("examples found via fuzzing", [&]() {
  before_each([&]() {
    record_alloc::start();
  });

  after_each([&]() {
    AssertThat(record_alloc::outstanding_allocation_indices(), IsEmpty());
  });

  for (unsigned i = 0, n = examples.size(); i < n; i++) {

    it(("parses example number " + to_string(i)).c_str(), [&]() {
      TSDocument *document = ts_document_new();
      // ts_document_print_debugging_graphs(document, true);

      const string &language_name = examples[i].first;
      ts_document_set_language(document, load_real_language(language_name));

      string input;
      const string &base64_input = examples[i].second;
      input.resize(base64_input.size());
      input.resize(base64_decode(
        reinterpret_cast<const unsigned char *>(base64_input.c_str()),
        reinterpret_cast<unsigned char *>(&input[0]),
        base64_input.size()
      ));

      ts_document_set_input_string_with_length(
        document,
        input.c_str(),
        input.size()
      );

      ts_document_parse(document);

      TSNode node = ts_document_root_node(document);
      assert_consistent_tree_sizes(node);

      ts_document_free(document);
    });

  }
});

END_TEST
<|endoftext|>