<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_BLOCK_HH
#define DUNE_GDT_SPACES_BLOCK_HH

#include <dune/stuff/common/exceptions.hh>

#include <dune/grid/multiscale/default.hh>

#include <dune/gdt/playground/mapper/block.hh>

#include "../../spaces/interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

template <class LocalSpaceImp>
class Block;

namespace internal {

template <class LocalSpaceType>
class BlockTraits
{
  static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value,
                "LocalSpaceType has to be derived from SpaceInterface!");
  typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType;

public:
  typedef Block<LocalSpaceType> derived_type;
  static const int polOrder = LocalSpaceType::polOrder;
  typedef typename LocalSpaceType::BackendType BackendType;
  typedef Mapper::Block<LocalSpaceType> MapperType;
  typedef typename LocalSpaceType::BaseFunctionSetType BaseFunctionSetType;
  typedef typename LocalSpaceType::CommunicatorType CommunicatorType;
  typedef typename MsGridType::GlobalGridViewType GridViewType;
  typedef typename LocalSpaceType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange     = LocalSpaceType::dimRange;
  static const unsigned int dimRangeCols = LocalSpaceType::dimRangeCols;

  static const Stuff::Grid::ChoosePartView part_view_type = LocalSpaceType::part_view_type;

  static const bool needs_grid_view = LocalSpaceType::needs_grid_view;
}; // class BlockTraits

} // namespace internal

template <class LocalSpaceImp>
class Block : public SpaceInterface<internal::BlockTraits<LocalSpaceImp>>
{
  typedef SpaceInterface<internal::BlockTraits<LocalSpaceImp>> BaseType;

public:
  typedef internal::BlockTraits<LocalSpaceImp> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef LocalSpaceImp LocalSpaceType;

  typedef typename BaseType::PatternType PatternType;
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::EntityType EntityType;

  typedef grid::Multiscale::Default<typename GridViewType::Grid> MsGridType;

  Block(const std::shared_ptr<const MsGridType> ms_grid,
        const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces)
    : ms_grid_(ms_grid)
    , local_spaces_(local_spaces)
    , mapper_(std::make_shared<MapperType>(ms_grid_, local_spaces_))
  {
    if (local_spaces_.size() != ms_grid_->size())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match,
                            "You have to provide a local space for each subdomain of the multiscale grid!\n"
                                << "  Size of the given multiscale grid: "
                                << ms_grid_->size()
                                << "\n"
                                << "  Number of local spaces given: "
                                << local_spaces_.size());
  } // Block(...)

  const std::shared_ptr<const MsGridType>& ms_grid() const
  {
    return ms_grid_;
  }

  const std::vector<std::shared_ptr<const LocalSpaceType>>& local_spaces() const
  {
    return local_spaces_;
  }

  const std::shared_ptr<const GridViewType>& grid_view() const
  {
    return ms_grid_->globalGridView();
  }

  const BackendType& backend() const
  {
    return local_spaces_[0]->backend();
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    const size_t block = find_block_of_(entity);
    return local_spaces_[block]->base_function_set(entity);
  }

  template <class ConstraintsType>
  void local_constraints(const EntityType& /*entity*/, ConstraintsType& /*ret*/) const
  {
    DUNE_THROW_COLORFULLY(NotImplemented, "I am not sure yet how to implement this!");
  }

  template <class G, class S>
  PatternType compute_pattern(const GridView<G>& /*local_grid_view*/, const SpaceInterface<S>& /*ansatz_space*/) const
  {
    DUNE_THROW_COLORFULLY(NotImplemented, "I am not sure yet how to implement this!");
  }

private:
  template <class EntityType>
  size_t find_block_of_(const EntityType& entity) const
  {
    const auto global_entity_index = ms_grid_->globalGridView()->indexSet().index(entity);
    const auto result              = ms_grid_->entityToSubdomainMap()->find(global_entity_index);
#ifndef NDEBUG
    if (result == ms_grid_->entityToSubdomainMap()->end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "Entity " << global_entity_index
                                      << " of the global grid view was not found in the multiscale grid!");
#endif // NDEBUG
    const size_t subdomain = result->second;
#ifndef NDEBUG
    if (subdomain >= ms_grid_->size())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index
                                                                                << " to be in subdomain "
                                                                                << subdomain
                                                                                << " while only having "
                                                                                << ms_grid_->size()
                                                                                << " subdomains!");
#endif // NDEBUG
    assert(subdomain < local_spaces_.size());
    return subdomain;
  } // ... find_block_of_(...)

  std::shared_ptr<const MsGridType> ms_grid_;
  std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_;
  std::shared_ptr<const MapperType> mapper_;
}; // class Block

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_BLOCK_HH
<commit_msg>[playground.spaces.block] guard against missing dune-grid-multiscale<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_BLOCK_HH
#define DUNE_GDT_SPACES_BLOCK_HH

#include <dune/common/static_assert.hh>

#include <dune/stuff/common/exceptions.hh>

#if HAVE_DUNE_GRID_MULTISCALE
#include <dune/grid/multiscale/default.hh>
#endif

#include <dune/gdt/playground/mapper/block.hh>

#include "../../spaces/interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

#if HAVE_DUNE_GRID_MULTISCALE

template <class LocalSpaceImp>
class Block;

namespace internal {

template <class LocalSpaceType>
class BlockTraits
{
  static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value,
                "LocalSpaceType has to be derived from SpaceInterface!");
  typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType;

public:
  typedef Block<LocalSpaceType> derived_type;
  static const int polOrder = LocalSpaceType::polOrder;
  typedef typename LocalSpaceType::BackendType BackendType;
  typedef Mapper::Block<LocalSpaceType> MapperType;
  typedef typename LocalSpaceType::BaseFunctionSetType BaseFunctionSetType;
  typedef typename LocalSpaceType::CommunicatorType CommunicatorType;
  typedef typename MsGridType::GlobalGridViewType GridViewType;
  typedef typename LocalSpaceType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange     = LocalSpaceType::dimRange;
  static const unsigned int dimRangeCols = LocalSpaceType::dimRangeCols;

  static const Stuff::Grid::ChoosePartView part_view_type = LocalSpaceType::part_view_type;

  static const bool needs_grid_view = LocalSpaceType::needs_grid_view;
}; // class BlockTraits

} // namespace internal

template <class LocalSpaceImp>
class Block : public SpaceInterface<internal::BlockTraits<LocalSpaceImp>>
{
  typedef SpaceInterface<internal::BlockTraits<LocalSpaceImp>> BaseType;

public:
  typedef internal::BlockTraits<LocalSpaceImp> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef LocalSpaceImp LocalSpaceType;

  typedef typename BaseType::PatternType PatternType;
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::EntityType EntityType;

  typedef grid::Multiscale::Default<typename GridViewType::Grid> MsGridType;

  Block(const std::shared_ptr<const MsGridType> ms_grid,
        const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces)
    : ms_grid_(ms_grid)
    , local_spaces_(local_spaces)
    , mapper_(std::make_shared<MapperType>(ms_grid_, local_spaces_))
  {
    if (local_spaces_.size() != ms_grid_->size())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match,
                            "You have to provide a local space for each subdomain of the multiscale grid!\n"
                                << "  Size of the given multiscale grid: "
                                << ms_grid_->size()
                                << "\n"
                                << "  Number of local spaces given: "
                                << local_spaces_.size());
  } // Block(...)

  const std::shared_ptr<const MsGridType>& ms_grid() const
  {
    return ms_grid_;
  }

  const std::vector<std::shared_ptr<const LocalSpaceType>>& local_spaces() const
  {
    return local_spaces_;
  }

  const std::shared_ptr<const GridViewType>& grid_view() const
  {
    return ms_grid_->globalGridView();
  }

  const BackendType& backend() const
  {
    return local_spaces_[0]->backend();
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    const size_t block = find_block_of_(entity);
    return local_spaces_[block]->base_function_set(entity);
  }

  template <class ConstraintsType>
  void local_constraints(const EntityType& /*entity*/, ConstraintsType& /*ret*/) const
  {
    DUNE_THROW_COLORFULLY(NotImplemented, "I am not sure yet how to implement this!");
  }

  template <class G, class S>
  PatternType compute_pattern(const GridView<G>& /*local_grid_view*/, const SpaceInterface<S>& /*ansatz_space*/) const
  {
    DUNE_THROW_COLORFULLY(NotImplemented, "I am not sure yet how to implement this!");
  }

private:
  template <class EntityType>
  size_t find_block_of_(const EntityType& entity) const
  {
    const auto global_entity_index = ms_grid_->globalGridView()->indexSet().index(entity);
    const auto result              = ms_grid_->entityToSubdomainMap()->find(global_entity_index);
#ifndef NDEBUG
    if (result == ms_grid_->entityToSubdomainMap()->end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "Entity " << global_entity_index
                                      << " of the global grid view was not found in the multiscale grid!");
#endif // NDEBUG
    const size_t subdomain = result->second;
#ifndef NDEBUG
    if (subdomain >= ms_grid_->size())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index
                                                                                << " to be in subdomain "
                                                                                << subdomain
                                                                                << " while only having "
                                                                                << ms_grid_->size()
                                                                                << " subdomains!");
#endif // NDEBUG
    assert(subdomain < local_spaces_.size());
    return subdomain;
  } // ... find_block_of_(...)

  std::shared_ptr<const MsGridType> ms_grid_;
  std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_;
  std::shared_ptr<const MapperType> mapper_;
}; // class Block

#else // HAVE_DUNE_GRID_MULTISCALE

template <class LocalSpaceImp>
class Block
{
  static_assert(Dune::AlwaysFalse<LocalSpaceImp>::value, "You are missing dune-grid-multiscale!");
};

#endif // HAVE_DUNE_GRID_MULTISCALE

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_BLOCK_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swwrtshitem.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:16:15 $
 *
 *  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
 *
 ************************************************************************/
#include "swwrtshitem.hxx"
TYPEINIT1(SwWrtShellItem,SfxPoolItem);
SwWrtShellItem::SwWrtShellItem( USHORT nWhich, SwWrtShell* pSh )
    : SfxPoolItem( nWhich ), pWrtSh( pSh )
{

}
SwWrtShellItem::SwWrtShellItem( const SwWrtShellItem& rItem) :
    SfxPoolItem( rItem.Which() ),
    pWrtSh( rItem.pWrtSh )
{
}

int SwWrtShellItem::operator==( const SfxPoolItem& rItem) const
{
    return ((SwWrtShellItem&)rItem).pWrtSh == pWrtSh;
}

SfxPoolItem* SwWrtShellItem::Clone( SfxItemPool *pPool ) const
{
    return new SwWrtShellItem( *this );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.474); FILE MERGED 2006/09/01 17:53:01 kaib 1.5.474.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swwrtshitem.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 22:50:52 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "swwrtshitem.hxx"
TYPEINIT1(SwWrtShellItem,SfxPoolItem);
SwWrtShellItem::SwWrtShellItem( USHORT nWhich, SwWrtShell* pSh )
    : SfxPoolItem( nWhich ), pWrtSh( pSh )
{

}
SwWrtShellItem::SwWrtShellItem( const SwWrtShellItem& rItem) :
    SfxPoolItem( rItem.Which() ),
    pWrtSh( rItem.pWrtSh )
{
}

int SwWrtShellItem::operator==( const SfxPoolItem& rItem) const
{
    return ((SwWrtShellItem&)rItem).pWrtSh == pWrtSh;
}

SfxPoolItem* SwWrtShellItem::Clone( SfxItemPool *pPool ) const
{
    return new SwWrtShellItem( *this );
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "restrictions/token_restriction.hh"
#include "token_relation.hh"
#include "column_identifier.hh"
#include "term.hh"
#include "to_string.hh"

std::vector<const column_definition*> cql3::token_relation::get_column_definitions(schema_ptr s) {
    std::vector<const column_definition*> res;
    std::transform(_entities.begin(), _entities.end(), std::back_inserter(res),
            [this, s](auto& cr) {
                return &this->to_column_definition(s, cr);
            });
    return res;
}

std::vector<::shared_ptr<cql3::column_specification>> cql3::token_relation::to_receivers(
        schema_ptr schema,
        const std::vector<const column_definition*>& column_defs) {
    auto pk = schema->partition_key_columns();
    if (!std::equal(column_defs.begin(), column_defs.end(), pk.begin(),
            pk.end(), [](auto* c1, auto& c2) {
                return c1 == &c2; // same, not "equal".
        })) {
#if 0
        checkTrue(columnDefs.containsAll(cfm.partitionKeyColumns()),
                "The token() function must be applied to all partition key components or none of them");

        checkContainsNoDuplicates(columnDefs, "The token() function contains duplicate partition key components");

        checkContainsOnly(columnDefs, cfm.partitionKeyColumns(), "The token() function must contains only partition key components");
#endif
        throw exceptions::invalid_request_exception(
                sprint(
                        "The token function arguments must be in the partition key order: %s",
                        ::to_string(column_defs)));
    }
    //auto* c = column_defs.front();
    return {::make_shared<column_specification>(schema->ks_name(), schema->cf_name(),
                ::make_shared<column_identifier>("partition key token", true),
                 // TODO: dht::global_partitioner().get_token_validator()
                 bytes_type)};
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_EQ_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names) {
    auto column_defs = get_column_definitions(schema);
    auto term = to_term(to_receivers(schema, column_defs), _value, db,
            schema->ks_name(), bound_names);
    return ::make_shared<restrictions::token_restriction::EQ>(column_defs, term);
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_IN_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names) {
    throw exceptions::invalid_request_exception(
            sprint("%s cannot be used with the token function",
                    get_operator()));
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_slice_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names,
        statements::bound bound,
        bool inclusive) {
    auto column_defs = get_column_definitions(schema);
    auto term = to_term(to_receivers(schema, column_defs), _value, db,
            schema->ks_name(), bound_names);
    return ::make_shared<restrictions::token_restriction::slice>(column_defs,
            bound, inclusive, term);
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_contains_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names, bool isKey) {
    throw exceptions::invalid_request_exception(
            sprint("%s cannot be used with the token function",
                    get_operator()));
}

sstring cql3::token_relation::to_string() const {
    return sprint("token(%s) %s %s", join(", ", _entities), get_operator(), _value);
}

::shared_ptr<cql3::term> cql3::token_relation::to_term(
        const std::vector<::shared_ptr<column_specification>>& receivers,
        ::shared_ptr<term::raw> raw, database& db, const sstring& keyspace,
        ::shared_ptr<variable_specifications> bound_names) {
    auto term = raw->prepare(db, keyspace, receivers.front());
    term->collect_marker_specification(bound_names);
    return term;
}
<commit_msg>cql3: use proper token type in token relations<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "restrictions/token_restriction.hh"
#include "token_relation.hh"
#include "column_identifier.hh"
#include "term.hh"
#include "to_string.hh"

std::vector<const column_definition*> cql3::token_relation::get_column_definitions(schema_ptr s) {
    std::vector<const column_definition*> res;
    std::transform(_entities.begin(), _entities.end(), std::back_inserter(res),
            [this, s](auto& cr) {
                return &this->to_column_definition(s, cr);
            });
    return res;
}

std::vector<::shared_ptr<cql3::column_specification>> cql3::token_relation::to_receivers(
        schema_ptr schema,
        const std::vector<const column_definition*>& column_defs) {
    auto pk = schema->partition_key_columns();
    if (!std::equal(column_defs.begin(), column_defs.end(), pk.begin(),
            pk.end(), [](auto* c1, auto& c2) {
                return c1 == &c2; // same, not "equal".
        })) {
#if 0
        checkTrue(columnDefs.containsAll(cfm.partitionKeyColumns()),
                "The token() function must be applied to all partition key components or none of them");

        checkContainsNoDuplicates(columnDefs, "The token() function contains duplicate partition key components");

        checkContainsOnly(columnDefs, cfm.partitionKeyColumns(), "The token() function must contains only partition key components");
#endif
        throw exceptions::invalid_request_exception(
                sprint(
                        "The token function arguments must be in the partition key order: %s",
                        ::to_string(column_defs)));
    }
    //auto* c = column_defs.front();
    return {::make_shared<column_specification>(schema->ks_name(), schema->cf_name(),
                ::make_shared<column_identifier>("partition key token", true),
                dht::global_partitioner().get_token_validator())};
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_EQ_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names) {
    auto column_defs = get_column_definitions(schema);
    auto term = to_term(to_receivers(schema, column_defs), _value, db,
            schema->ks_name(), bound_names);
    return ::make_shared<restrictions::token_restriction::EQ>(column_defs, term);
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_IN_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names) {
    throw exceptions::invalid_request_exception(
            sprint("%s cannot be used with the token function",
                    get_operator()));
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_slice_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names,
        statements::bound bound,
        bool inclusive) {
    auto column_defs = get_column_definitions(schema);
    auto term = to_term(to_receivers(schema, column_defs), _value, db,
            schema->ks_name(), bound_names);
    return ::make_shared<restrictions::token_restriction::slice>(column_defs,
            bound, inclusive, term);
}

::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_contains_restriction(
        database& db, schema_ptr schema,
        ::shared_ptr<variable_specifications> bound_names, bool isKey) {
    throw exceptions::invalid_request_exception(
            sprint("%s cannot be used with the token function",
                    get_operator()));
}

sstring cql3::token_relation::to_string() const {
    return sprint("token(%s) %s %s", join(", ", _entities), get_operator(), _value);
}

::shared_ptr<cql3::term> cql3::token_relation::to_term(
        const std::vector<::shared_ptr<column_specification>>& receivers,
        ::shared_ptr<term::raw> raw, database& db, const sstring& keyspace,
        ::shared_ptr<variable_specifications> bound_names) {
    auto term = raw->prepare(db, keyspace, receivers.front());
    term->collect_marker_specification(bound_names);
    return term;
}
<|endoftext|>


<commit_before><commit_msg>WaE: -Werror=unused-variable<commit_after><|endoftext|>


<commit_before><commit_msg>fix memory leak<commit_after><|endoftext|>


<commit_before>

#include <iostream>
#include <cstdlib>
#include "RigidBodyManipulator.h"

using namespace std;

int main(int argc, char* argv[])
{
	if (argc<2) {
		cerr << "Usage: urdfKinTest urdf_filename" << endl;
		exit(-1);
	}
  RigidBodyManipulator* model = new RigidBodyManipulator(argv[1]);
  if (!model) {
  	cerr << "ERROR: Failed to load model from " << argv[1] << endl;
  	return -1;
  }

  // run kinematics with second derivatives 100 times
  VectorXd q = VectorXd::Zero(model->num_positions);
  int i;

  if (argc>=2+model->num_positions) {
  	for (i=0; i<model->num_positions; i++)
  		sscanf(argv[2+i],"%lf",&q(i));
  }

// for (i=0; i<model->num_dof; i++)
// 	 q(i)=(double)rand() / RAND_MAX;
    model->doKinematics(q,false);
//  }

//  const Vector4d zero(0,0,0,1);
  Vector3d zero = Vector3d::Zero();
  Matrix<double,6,1> pt;

  for (i=0; i<model->num_bodies; i++) {
//    model->forwardKinNew(i,zero,1,pt);
		auto pt = model->forwardKinNew(zero, i, 0, 1, 0);
//    cout << i << ": forward kin: " << model->bodies[i].linkname << " is at " << pt.transpose() << endl;
    cout << model->bodies[i]->linkname << " ";
		cout << pt.value().transpose() << endl;
//    for (int j=0; j<pt.size(); j++)
//    	cout << pt(j) << " ";
  }

  delete model;
  return 0;
}
<commit_msg>call doKinematicsNew<commit_after>

#include <iostream>
#include <cstdlib>
#include "RigidBodyManipulator.h"

using namespace std;

int main(int argc, char* argv[])
{
	if (argc<2) {
		cerr << "Usage: urdfKinTest urdf_filename" << endl;
		exit(-1);
	}
  RigidBodyManipulator* model = new RigidBodyManipulator(argv[1]);
  if (!model) {
  	cerr << "ERROR: Failed to load model from " << argv[1] << endl;
  	return -1;
  }

  // run kinematics with second derivatives 100 times
  VectorXd q = VectorXd::Zero(model->num_positions);
  VectorXd v = VectorXd::Zero(model->num_velocities);
  int i;

  if (argc>=2+model->num_positions) {
  	for (i=0; i<model->num_positions; i++)
  		sscanf(argv[2+i],"%lf",&q(i));
  }

// for (i=0; i<model->num_dof; i++)
// 	 q(i)=(double)rand() / RAND_MAX;
    model->doKinematicsNew(q,v);
//  }

//  const Vector4d zero(0,0,0,1);
  Vector3d zero = Vector3d::Zero();
  Matrix<double,6,1> pt;

  for (i=0; i<model->num_bodies; i++) {
//    model->forwardKinNew(i,zero,1,pt);
		auto pt = model->forwardKinNew(zero, i, 0, 1, 0);
//    cout << i << ": forward kin: " << model->bodies[i].linkname << " is at " << pt.transpose() << endl;
    cout << model->bodies[i]->linkname << " ";
		cout << pt.value().transpose() << endl;
//    for (int j=0; j<pt.size(); j++)
//    	cout << pt(j) << " ";
  }

  delete model;
  return 0;
}
<|endoftext|>


<commit_before>/*
	main.cpp
	the entrence of the app
*/

#include <basic\common.h>
#include <basic\command_line.h>
#include <basic\stop_watch.h>
#include <mesh\mesh.h>
#include <mesh\mesh_io.h>
#include <cuda\cuda_common.h>
#include <cuda\cuda_rvd.h>

int main(int argc, char** argv){
	using namespace Gpu_Rvd;

	StopWatch S("total task");
	Cmd::Mode mode = Cmd::Host_Device;
	std::vector<std::string> filenames;
	if (!Cmd::parse_argu(argc, argv, filenames, mode)){
		fprintf(stderr, "failed to parse the argument!");
		return 1;
	}

	std::string mesh_filename = filenames[0];
	std::string points_filename = filenames[0];
	std::string output_filename;
	if (filenames.size() >= 2) {
		points_filename = filenames[1];
	}
	output_filename = (filenames.size() == 3) ? filenames[2] : "out.eobj";

	Mesh M_in;
	Points Points_in;

	if (!mesh_load_obj(mesh_filename, M_in)){
		fprintf(stderr, "cannot load the mesh from the %s path", mesh_filename);
		return 1;
	}

	if (!points_load_obj(points_filename, Points_in)){
		fprintf(stderr, "cannot load the points from the %s path", points_filename);
		return 1;
	}

#ifdef KNN

#else
	// do not use Knn algorigthm, find the Nearest Neighbors by comparing the distance in CPU.
	//Points_in.search_nn(Points_in.v_ptr(), 3, Points_in.get_vertex_nb(), 20);

	index_t* points_nn = (index_t*)malloc(sizeof(index_t) * Points_in.get_vertex_nb() * 20);
	index_t* facets_nn = (index_t*)malloc(sizeof(index_t) * M_in.get_facet_nb());

	freopen("..//test//right//S2_points.txt", "r", stdin);
	for (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){
		scanf("%d ", &points_nn[t]);
	}
	freopen("..//test//right//S2_facets.txt", "r", stdin);
	for (index_t t = 0; t < M_in.get_facet_nb(); ++t){
		scanf("%d ", &facets_nn[t]);
	}
	freopen("CON", "r", stdin);
	/*freopen("..//test//S2_points_nn", "w", stdout);
	for (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){
		printf("%d ", points_nn[t]);
		if (t % 20 == 19) printf("\n");
	}
	printf("\n");
	for (int i = 0; i < 1000; ++i){
		printf("%d ", i);
	}
	freopen("..//test//S2_facets_nn", "w", stdout);
	for (index_t t = 0; t < M_in.get_facet_nb(); ++t){
		printf("%d %d\n",t, facets_nn[t]);
	}
	printf("\n");
	for (int i = 0; i < 1000; ++i){
		printf("%d ", i);
	}*/
#endif
	CudaRestrictedVoronoiDiagram RVD(
		M_in.v_ptr(),			M_in.get_vertex_nb(),
		Points_in.v_ptr(),		Points_in.get_vertex_nb(),
		M_in.f_ptr(),			M_in.get_facet_nb(),
		points_nn,				20,
		facets_nn,				Points_in.dimension()
		);

	RVD.compute_Rvd();

	S.print_elaspsed_time(std::cout);
	getchar();
	return 0;
}<commit_msg>modify<commit_after>/*
	main.cpp
	the entrence of the app
*/

#include <basic\common.h>
#include <basic\command_line.h>
#include <basic\stop_watch.h>
#include <mesh\mesh.h>
#include <mesh\mesh_io.h>
#include <cuda\cuda_common.h>
#include <cuda\cuda_rvd.h>

int main(int argc, char** argv){
	using namespace Gpu_Rvd;

	StopWatch S("total task");
	Cmd::Mode mode = Cmd::Host_Device;
	std::vector<std::string> filenames;
	if (!Cmd::parse_argu(argc, argv, filenames, mode)){
		fprintf(stderr, "failed to parse the argument!");
		return 1;
	}

	std::string mesh_filename = filenames[0];
	std::string points_filename = filenames[0];
	std::string output_filename;
	if (filenames.size() >= 2) {
		points_filename = filenames[1];
	}
	output_filename = (filenames.size() == 3) ? filenames[2] : "out.eobj";

	Mesh M_in;
	Points Points_in;

	if (!mesh_load_obj(mesh_filename, M_in)){
		fprintf(stderr, "cannot load the mesh from the %s path", mesh_filename);
		return 1;
	}

	if (!points_load_obj(points_filename, Points_in)){
		fprintf(stderr, "cannot load the points from the %s path", points_filename);
		return 1;
	}

#ifdef KNN

#else
	// do not use Knn algorigthm, find the Nearest Neighbors by comparing the distance in CPU.
	//Points_in.search_nn(Points_in.v_ptr(), 3, Points_in.get_vertex_nb(), 20);

	index_t* points_nn = (index_t*)malloc(sizeof(index_t) * Points_in.get_vertex_nb() * 20);
	index_t* facets_nn = (index_t*)malloc(sizeof(index_t) * M_in.get_facet_nb());

	freopen("..//test//right//bunny_points_nn.txt", "r", stdin);
	for (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){
		scanf("%d ", &points_nn[t]);
	}
	freopen("..//test//right//bunny_facets_nn.txt", "r", stdin);
	for (index_t t = 0; t < M_in.get_facet_nb(); ++t){
		scanf("%d ", &facets_nn[t]);
	}
	freopen("CON", "r", stdin);
	/*freopen("..//test//S2_points_nn", "w", stdout);
	for (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){
		printf("%d ", points_nn[t]);
		if (t % 20 == 19) printf("\n");
	}
	printf("\n");
	for (int i = 0; i < 1000; ++i){
		printf("%d ", i);
	}
	freopen("..//test//S2_facets_nn", "w", stdout);
	for (index_t t = 0; t < M_in.get_facet_nb(); ++t){
		printf("%d %d\n",t, facets_nn[t]);
	}
	printf("\n");
	for (int i = 0; i < 1000; ++i){
		printf("%d ", i);
	}*/
#endif
	CudaRestrictedVoronoiDiagram RVD(
		M_in.v_ptr(),			M_in.get_vertex_nb(),
		Points_in.v_ptr(),		Points_in.get_vertex_nb(),
		M_in.f_ptr(),			M_in.get_facet_nb(),
		points_nn,				20,
		facets_nn,				Points_in.dimension()
		);

	RVD.compute_Rvd();

	S.print_elaspsed_time(std::cout);
	getchar();
	return 0;
}<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkExtractEdges.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
  if(ret)
    {
    return (vtkExtractEdges*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkExtractEdges;
}

// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
  this->Locator = NULL;
}

vtkExtractEdges::~vtkExtractEdges()
{
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
  vtkDataSet *input= this->GetInput();
  vtkPolyData *output= this->GetOutput();
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkIdType numCells, cellNum, numPts, newId;
  int edgeNum, numEdgePts, numCellEdges;
  int i;
  vtkIdType pts[2];
  vtkIdType pt1 = 0, pt2;
  float *x;
  vtkEdgeTable *edgeTable;
  vtkCell *cell, *edge;
  vtkPointData *pd, *outPD;
  vtkCellData *cd, *outCD;

  vtkDebugMacro(<<"Executing edge extractor");

  //  Check input
  //
  numPts=input->GetNumberOfPoints();
  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
    {
    vtkErrorMacro(<<"No input data!");
    return;
    }

  // Set up processing
  //
  edgeTable = vtkEdgeTable::New();
  edgeTable->InitEdgeInsertion(numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->EstimateSize(numPts*4,2);

  pd = input->GetPointData();
  outPD = output->GetPointData();
  outPD->CopyAllocate(pd,numPts);

  cd = input->GetCellData();
  outCD = output->GetCellData();
  outCD->CopyAllocate(cd,numCells);

  // Get our locator for merging points
  //
  if ( this->Locator == NULL )
    {
    this->CreateDefaultLocator();
    }
  this->Locator->InitPointInsertion (newPts, input->GetBounds());

  // Loop over all cells, extracting non-visited edges.
  //
  for (cellNum=0; cellNum < numCells; cellNum++ )
    {
    if ( ! (cellNum % 10000) ) //manage progress reports / early abort
      {
      this->UpdateProgress ((float)cellNum / numCells);
      if ( this->GetAbortExecute() )
        {
        break;
        }
      }

    cell = input->GetCell(cellNum);
    numCellEdges = cell->GetNumberOfEdges();
    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
      {
      edge = cell->GetEdge(edgeNum);
      numEdgePts = edge->GetNumberOfPoints();

      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
        {
        pt2 = edge->PointIds->GetId(i);
	x = input->GetPoint(pt2);
        if ( this->Locator->InsertUniquePoint(x, pts[1]) )
	  {
	  outPD->CopyData (pd,pt2,pts[1]);
	  }
        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
          {
          edgeTable->InsertEdge(pt1, pt2);
          newId = newLines->InsertNextCell(2,pts);
          outCD->CopyData(cd, cellNum, newId);
          }
        }
      }//for all edges of cell
    }//for all cells

  vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");

  //
  //  Update ourselves.
  //
  edgeTable->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  output->Squeeze();
}

// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
  if ( this->Locator == locator )
    {
    return;
    }
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
  if ( locator )
    {
    locator->Register(this);
    }
  this->Locator = locator;
  this->Modified();
}

void vtkExtractEdges::CreateDefaultLocator()
{
  if ( this->Locator == NULL )
    {
    this->Locator = vtkMergePoints::New();
    }
}

void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  if ( this->Locator )
    {
    os << indent << "Locator: " << this->Locator << "\n";
    }
  else
    {
    os << indent << "Locator: (none)\n";
    }
}

unsigned long int vtkExtractEdges::GetMTime()
{
  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
  unsigned long time;

  if ( this->Locator != NULL )
    {
    time = this->Locator->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }
  return mTime;
}

<commit_msg>ENH:Stupid formatting changes<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractEdges.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"

//-------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
  if(ret)
    {
    return (vtkExtractEdges*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkExtractEdges;
}

// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
  this->Locator = NULL;
}

vtkExtractEdges::~vtkExtractEdges()
{
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
  vtkDataSet *input= this->GetInput();
  vtkPolyData *output= this->GetOutput();
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkIdType numCells, cellNum, numPts, newId;
  int edgeNum, numEdgePts, numCellEdges;
  int i;
  vtkIdType pts[2];
  vtkIdType pt1 = 0, pt2;
  float *x;
  vtkEdgeTable *edgeTable;
  vtkCell *cell, *edge;
  vtkPointData *pd, *outPD;
  vtkCellData *cd, *outCD;

  vtkDebugMacro(<<"Executing edge extractor");

  //  Check input
  //
  numPts=input->GetNumberOfPoints();
  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
    {
    vtkErrorMacro(<<"No input data!");
    return;
    }

  // Set up processing
  //
  edgeTable = vtkEdgeTable::New();
  edgeTable->InitEdgeInsertion(numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->EstimateSize(numPts*4,2);

  pd = input->GetPointData();
  outPD = output->GetPointData();
  outPD->CopyAllocate(pd,numPts);

  cd = input->GetCellData();
  outCD = output->GetCellData();
  outCD->CopyAllocate(cd,numCells);

  // Get our locator for merging points
  //
  if ( this->Locator == NULL )
    {
    this->CreateDefaultLocator();
    }
  this->Locator->InitPointInsertion (newPts, input->GetBounds());

  // Loop over all cells, extracting non-visited edges.
  //
  for (cellNum=0; cellNum < numCells; cellNum++ )
    {
    if ( ! (cellNum % 10000) ) //manage progress reports / early abort
      {
      this->UpdateProgress ((float)cellNum / numCells);
      if ( this->GetAbortExecute() )
        {
        break;
        }
      }

    cell = input->GetCell(cellNum);
    numCellEdges = cell->GetNumberOfEdges();
    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
      {
      edge = cell->GetEdge(edgeNum);
      numEdgePts = edge->GetNumberOfPoints();

      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
        {
        pt2 = edge->PointIds->GetId(i);
	x = input->GetPoint(pt2);
        if ( this->Locator->InsertUniquePoint(x, pts[1]) )
	  {
	  outPD->CopyData (pd,pt2,pts[1]);
	  }
        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
          {
          edgeTable->InsertEdge(pt1, pt2);
          newId = newLines->InsertNextCell(2,pts);
          outCD->CopyData(cd, cellNum, newId);
          }
        }
      }//for all edges of cell
    }//for all cells

  vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");

  //  Update ourselves.
  //
  edgeTable->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  output->Squeeze();
}

// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
  if ( this->Locator == locator )
    {
    return;
    }
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
  if ( locator )
    {
    locator->Register(this);
    }
  this->Locator = locator;
  this->Modified();
}

void vtkExtractEdges::CreateDefaultLocator()
{
  if ( this->Locator == NULL )
    {
    this->Locator = vtkMergePoints::New();
    }
}

void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  if ( this->Locator )
    {
    os << indent << "Locator: " << this->Locator << "\n";
    }
  else
    {
    os << indent << "Locator: (none)\n";
    }
}

unsigned long int vtkExtractEdges::GetMTime()
{
  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
  unsigned long time;

  if ( this->Locator != NULL )
    {
    time = this->Locator->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }
  return mTime;
}

<|endoftext|>


<commit_before>// $Id$
/**
 * @file hltout-collect-esd.C
 * @brief Example for the AliHLTEsdCollectorComponent
 *
 * Example macro to run a small chain with the AliHLTOUTPublisherComponent
 * and the AliHLTEsdCollectorComponent. The AliHLTOUTPublisherComponent
 * is configured to publish all ESD objects from the HLTOUT data, the
 * AliHLTEsdCollectorComponent writes the files using the AliHLTEsdManager.
 *
 * Usage: aliroot -b -q \
 *             hltout-collect-esd.C'("raw.root","local://$ALICE_ROOT/OCDB",0,5)' | tee hltout-collect-esd.log
 * or
 *
 *    aliroot -b -l -q \
 *                hltout-collect-esd.C'("alien:///alice/data/2010/LHC10b/000115322/raw/10000115322040.80.root","raw://",0,5)'  | tee hltout-collect-esd.log
 *
 *
 * The macro asumes HLTOUT raw data ddl files in order to open an
 * AliRawReaderFile, e.g. simulated using the default AliSimulation with
 * at least SetWriteRawData("HLT") enabled.
 *
 * \b Note: The example disables a few steps in the AliReconstruction,
 * mainly because of crashes in various parts of AliRoot. This does not
 * have any impact to the HLT features to be presented.
 *
 * @author Matthias.Richter@ift.uib.no
 * @ingroup alihlt_tutorial
 */
void hltout_collect_esd(const char *filename,
                        const char *cdbURI,
                        int minEvent=-1,
                        int maxEvent=-1)
{

  // connect to the GRID if we use a file or OCDB from the GRID
  TString struri=cdbURI;
  TString strfile=filename;
  if (struri.BeginsWith("raw://") ||
      strfile.Contains("://") && !strfile.Contains("local://")) {
    TGrid::Connect("alien");
  }

  // Set the CDB storage location
  AliCDBManager * man = AliCDBManager::Instance();
  man->SetDefaultStorage(cdbURI);
  if (struri.BeginsWith("local://")) {
    // set specific storage for GRP entry
    // search in the working directory and one level above, the latter
    // follows the standard simulation setup like e.g. in test/ppbench
    if (!gSystem->AccessPathName("GRP/GRP/Data")) {
      man->SetSpecificStorage("GRP/GRP/Data", "local://$PWD");
    } else if (!gSystem->AccessPathName("../GRP/GRP/Data")) {
      man->SetSpecificStorage("GRP/GRP/Data", "local://$PWD/..");
    }
  }
  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // setup of the HLT system
  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();
  if (!pHLT) {
    cerr << "fatal error: can not get HLT instance" << endl;
  }

  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // the configuration chain
  TString arg;

  // the publisher configuration
  arg.Form("-typeid ESD_TREE -typeid ALIESDV0");
  AliHLTConfiguration publisher("hltout-publisher", "AliHLTOUTPublisher" , NULL, arg.Data());

  // the writer configuration
  arg.Form("");
  AliHLTConfiguration collector("sink1", "EsdCollector"   , "hltout-publisher", arg.Data());

  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // setup of the reconstruction
  AliReconstruction rec;

  if (minEvent>=0 || maxEvent>minEvent) {
    if (minEvent<0) minEvent=0;
    if (maxEvent<minEvent) maxEvent=minEvent;
    rec.SetEventRange(minEvent,maxEvent);
  }

  rec.SetInput(filename);
  rec.SetRunLocalReconstruction("HLT");
  rec.SetRunTracking("");
  rec.SetFillESD("");
  rec.SetRunQA(":");
  rec.SetFillTriggerESD(kFALSE);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetOption("HLT", "libAliHLTUtil.so loglevel=0x7c chains=sink1");
  rec.Run();
}
<commit_msg>- removed obsolete argument for the HLTOUT publisher<commit_after>// $Id$
/**
 * @file hltout-collect-esd.C
 * @brief Example for the AliHLTEsdCollectorComponent
 *
 * Example macro to run a small chain with the AliHLTOUTPublisherComponent
 * and the AliHLTEsdCollectorComponent. The AliHLTOUTPublisherComponent
 * is configured to publish all ESD objects from the HLTOUT data, the
 * AliHLTEsdCollectorComponent writes the files using the AliHLTEsdManager.
 *
 * Usage: aliroot -b -q \
 *             hltout-collect-esd.C'("raw.root","local://$ALICE_ROOT/OCDB",0,5)' | tee hltout-collect-esd.log
 * or
 *
 *    aliroot -b -l -q \
 *                hltout-collect-esd.C'("alien:///alice/data/2010/LHC10b/000115322/raw/10000115322040.80.root","raw://",0,5)'  | tee hltout-collect-esd.log
 *
 *
 * The macro asumes HLTOUT raw data ddl files in order to open an
 * AliRawReaderFile, e.g. simulated using the default AliSimulation with
 * at least SetWriteRawData("HLT") enabled.
 *
 * \b Note: The example disables a few steps in the AliReconstruction,
 * mainly because of crashes in various parts of AliRoot. This does not
 * have any impact to the HLT features to be presented.
 *
 * @author Matthias.Richter@ift.uib.no
 * @ingroup alihlt_tutorial
 */
void hltout_collect_esd(const char *filename,
                        const char *cdbURI,
                        int minEvent=-1,
                        int maxEvent=-1)
{

  // connect to the GRID if we use a file or OCDB from the GRID
  TString struri=cdbURI;
  TString strfile=filename;
  if (struri.BeginsWith("raw://") ||
      strfile.Contains("://") && !strfile.Contains("local://")) {
    TGrid::Connect("alien");
  }

  // Set the CDB storage location
  AliCDBManager * man = AliCDBManager::Instance();
  man->SetDefaultStorage(cdbURI);
  if (struri.BeginsWith("local://")) {
    // set specific storage for GRP entry
    // search in the working directory and one level above, the latter
    // follows the standard simulation setup like e.g. in test/ppbench
    if (!gSystem->AccessPathName("GRP/GRP/Data")) {
      man->SetSpecificStorage("GRP/GRP/Data", "local://$PWD");
    } else if (!gSystem->AccessPathName("../GRP/GRP/Data")) {
      man->SetSpecificStorage("GRP/GRP/Data", "local://$PWD/..");
    }
  }
  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // setup of the HLT system
  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();
  if (!pHLT) {
    cerr << "fatal error: can not get HLT instance" << endl;
  }

  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // the configuration chain
  TString arg;

  // the publisher configuration
  arg.Form("-typeid ALIESDV0");
  AliHLTConfiguration publisher("hltout-publisher", "AliHLTOUTPublisher" , NULL, arg.Data());

  // the writer configuration
  arg.Form("");
  AliHLTConfiguration collector("sink1", "EsdCollector"   , "hltout-publisher", arg.Data());

  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  // setup of the reconstruction
  AliReconstruction rec;

  if (minEvent>=0 || maxEvent>minEvent) {
    if (minEvent<0) minEvent=0;
    if (maxEvent<minEvent) maxEvent=minEvent;
    rec.SetEventRange(minEvent,maxEvent);
  }

  rec.SetInput(filename);
  rec.SetRunLocalReconstruction("HLT");
  rec.SetRunTracking("");
  rec.SetFillESD("");
  rec.SetRunQA(":");
  rec.SetFillTriggerESD(kFALSE);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetOption("HLT", "libAliHLTUtil.so loglevel=0x7c chains=sink1");
  rec.Run();
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <unistd.h>
#include <xen/xen.h>
#include <xen/event_channel.h> // kernel interface
#include <xen/sys/evtchn.h>    // userspace interface

#include "core/reactor.hh"
#include "core/semaphore.hh"
#include "core/future-util.hh"
#include "evtchn.hh"
#include "osv_xen.hh"

semaphore *evtchn::init_port(int port) {
    _promises.emplace(port, semaphore(0));
    return port_to_sem(port);
}

void evtchn::make_ready_port(int port) {
    auto sem = port_to_sem(port);
    sem->signal();
}

future<> evtchn::pending(int port) {
    auto sem = port_to_sem(port);
    return sem->wait();
}

port::port(int p)
    : _port(p), _evtchn(evtchn::instance()) {
}

future<> port::pending() {
    return _evtchn->pending(_port);
}

void port::notify() {
    _evtchn->notify(_port);
}

class userspace_evtchn: public evtchn {
    pollable_fd _evtchn;
    void umask(int *port, unsigned count);
public:
    userspace_evtchn(unsigned otherend);
    virtual port *bind() override;
    virtual void notify(int port) override;
};

userspace_evtchn::userspace_evtchn(unsigned otherend)
    : evtchn(otherend)
    , _evtchn(pollable_fd(file_desc::open("/dev/xen/evtchn", O_RDWR | O_NONBLOCK)))
{
    keep_doing([this] {
        int ports[2];
        return _evtchn.read_some(reinterpret_cast<char *>(&ports), sizeof(ports)).then([this, &ports] (size_t s)
        {
            auto count = s / sizeof(ports[0]);
            umask(ports, count);
            for (unsigned i = 0; i < count; ++i) {
                make_ready_port(ports[i]);
            }
            make_ready_future<>();
        });
    });
}

port *userspace_evtchn::bind()
{
    struct ioctl_evtchn_bind_unbound_port bind = { _otherend };

    auto ret = _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_bind_unbound_port>(IOCTL_EVTCHN_BIND_UNBOUND_PORT, bind);
    auto p = new port(ret);
    init_port(*p);
    return p;
}

void userspace_evtchn::notify(int port)
{
    struct ioctl_evtchn_notify notify;
    notify.port = port;

    _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_notify>(IOCTL_EVTCHN_NOTIFY, notify);
}

void userspace_evtchn::umask(int *port, unsigned count)
{
    _evtchn.get_file_desc().write(port, count * sizeof(port));
}

#ifdef HAVE_OSV
class kernel_evtchn: public evtchn {
    static void make_ready(void *arg);
    static void process_interrupts(readable_eventfd* fd, semaphore* sem);
public:
    kernel_evtchn(unsigned otherend) : evtchn(otherend) {}
    virtual port *bind() override;
    virtual void notify(int port) override;
};

void kernel_evtchn::make_ready(void *arg) {
    int fd = reinterpret_cast<uintptr_t>(arg);
    uint64_t one = 1;
    ::write(fd, &one, sizeof(one));
}

port *kernel_evtchn::bind() {

    unsigned int irq;

    int newp;
    irq = bind_listening_port_to_irq(_otherend, &newp);
    // We need to convert extra-seastar events to intra-seastar events
    // (in this case, the semaphore interface of evtchn).  The only
    // way to do that currently is via eventfd.
    semaphore* sem = init_port(newp);
    auto fd = new readable_eventfd;
    auto wfd = fd->get_write_fd();
    intr_add_handler("", irq, NULL, make_ready, reinterpret_cast<void*>(uintptr_t(wfd)), 0, 0);
    unmask_evtchn(newp);
    process_interrupts(fd, sem);
    return new port(evtchn_from_irq(irq));
}

void kernel_evtchn::process_interrupts(readable_eventfd* fd, semaphore* sem) {
    fd->wait().then([fd, sem] (size_t ignore) {
        sem->signal();
        process_interrupts(fd, sem);
    });
}

void kernel_evtchn::notify(int port) {
    notify_remote_via_evtchn(port);
}
#endif

evtchn *evtchn::_instance = nullptr;

evtchn *evtchn::instance()
{
    if (!_instance) {
        throw std::runtime_error("Acquiring evtchn instance without specifying otherend: invalid context");
    }

    return _instance;
}

evtchn *evtchn::instance(bool userspace, unsigned otherend)
{
    if (!_instance) {
#ifdef HAVE_OSV
        if (!userspace) {
            _instance = new kernel_evtchn(otherend);
        } else
#endif
            _instance = new userspace_evtchn(otherend);
    }
    return _instance;
}
<commit_msg>xen: change process_interrupts to take a port, rather than a semaphore<commit_after>#include <stdint.h>
#include <unistd.h>
#include <xen/xen.h>
#include <xen/event_channel.h> // kernel interface
#include <xen/sys/evtchn.h>    // userspace interface

#include "core/reactor.hh"
#include "core/semaphore.hh"
#include "core/future-util.hh"
#include "evtchn.hh"
#include "osv_xen.hh"

semaphore *evtchn::init_port(int port) {
    _promises.emplace(port, semaphore(0));
    return port_to_sem(port);
}

void evtchn::make_ready_port(int port) {
    auto sem = port_to_sem(port);
    sem->signal();
}

future<> evtchn::pending(int port) {
    auto sem = port_to_sem(port);
    return sem->wait();
}

port::port(int p)
    : _port(p), _evtchn(evtchn::instance()) {
}

future<> port::pending() {
    return _evtchn->pending(_port);
}

void port::notify() {
    _evtchn->notify(_port);
}

class userspace_evtchn: public evtchn {
    pollable_fd _evtchn;
    void umask(int *port, unsigned count);
public:
    userspace_evtchn(unsigned otherend);
    virtual port *bind() override;
    virtual void notify(int port) override;
};

userspace_evtchn::userspace_evtchn(unsigned otherend)
    : evtchn(otherend)
    , _evtchn(pollable_fd(file_desc::open("/dev/xen/evtchn", O_RDWR | O_NONBLOCK)))
{
    keep_doing([this] {
        int ports[2];
        return _evtchn.read_some(reinterpret_cast<char *>(&ports), sizeof(ports)).then([this, &ports] (size_t s)
        {
            auto count = s / sizeof(ports[0]);
            umask(ports, count);
            for (unsigned i = 0; i < count; ++i) {
                make_ready_port(ports[i]);
            }
            make_ready_future<>();
        });
    });
}

port *userspace_evtchn::bind()
{
    struct ioctl_evtchn_bind_unbound_port bind = { _otherend };

    auto ret = _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_bind_unbound_port>(IOCTL_EVTCHN_BIND_UNBOUND_PORT, bind);
    auto p = new port(ret);
    init_port(*p);
    return p;
}

void userspace_evtchn::notify(int port)
{
    struct ioctl_evtchn_notify notify;
    notify.port = port;

    _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_notify>(IOCTL_EVTCHN_NOTIFY, notify);
}

void userspace_evtchn::umask(int *port, unsigned count)
{
    _evtchn.get_file_desc().write(port, count * sizeof(port));
}

#ifdef HAVE_OSV
class kernel_evtchn: public evtchn {
    static void make_ready(void *arg);
    void process_interrupts(readable_eventfd* fd, int port);
public:
    kernel_evtchn(unsigned otherend) : evtchn(otherend) {}
    virtual port *bind() override;
    virtual void notify(int port) override;
};

void kernel_evtchn::make_ready(void *arg) {
    int fd = reinterpret_cast<uintptr_t>(arg);
    uint64_t one = 1;
    ::write(fd, &one, sizeof(one));
}

port *kernel_evtchn::bind() {

    unsigned int irq;

    int newp;
    irq = bind_listening_port_to_irq(_otherend, &newp);
    // We need to convert extra-seastar events to intra-seastar events
    // (in this case, the semaphore interface of evtchn).  The only
    // way to do that currently is via eventfd.
    init_port(newp);
    auto fd = new readable_eventfd;
    auto wfd = fd->get_write_fd();
    intr_add_handler("", irq, NULL, make_ready, reinterpret_cast<void*>(uintptr_t(wfd)), 0, 0);
    unmask_evtchn(newp);
    process_interrupts(fd, newp);
    return new port(evtchn_from_irq(irq));
}

void kernel_evtchn::process_interrupts(readable_eventfd* fd, int port) {
    fd->wait().then([this, fd, port] (size_t ignore) {
        make_ready_port(port);
        process_interrupts(fd, port);
    });
}

void kernel_evtchn::notify(int port) {
    notify_remote_via_evtchn(port);
}
#endif

evtchn *evtchn::_instance = nullptr;

evtchn *evtchn::instance()
{
    if (!_instance) {
        throw std::runtime_error("Acquiring evtchn instance without specifying otherend: invalid context");
    }

    return _instance;
}

evtchn *evtchn::instance(bool userspace, unsigned otherend)
{
    if (!_instance) {
#ifdef HAVE_OSV
        if (!userspace) {
            _instance = new kernel_evtchn(otherend);
        } else
#endif
            _instance = new userspace_evtchn(otherend);
    }
    return _instance;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <atomic>
#include <mutex>
#include <stdexcept>
#include <unordered_map>
#include <cxxabi.h>
#include <unwind.h>
#include <cassert>

#include <lyra/lyra_exceptions.h>

namespace facebook {
namespace lyra {

using namespace detail;

namespace {
std::atomic<bool> enableBacktraces{true};

const ExceptionTraceHolder* getExceptionTraceHolderInException(
    std::exception_ptr ptr) {
  try {
    std::rethrow_exception(ptr);
  } catch (const ExceptionTraceHolder& holder) {
    return &holder;
  } catch (...) {
    return nullptr;
  }
}
} // namespace

void enableCxaThrowHookBacktraces(bool enable) {
  enableBacktraces.store(enable, std::memory_order_relaxed);
}

[[gnu::noreturn]] void (*original_cxa_throw)(void*, const std::type_info*, void (*) (void *));

#if defined(_LIBCPP_VERSION)

// We want to attach stack traces to C++ exceptions. Our API contract is that
// calling lyra::getExceptionTrace on the exception_ptr for an exception should
// return the stack trace for that exception.
//
// We accomplish this by providing a hook for __cxa_throw, which creates an
// ExceptionTraceHolder object (which captures the stack trace for the
// exception), and creates a mapping from the pointer to the exception object
// (which is a parameter to __cxa_throw) to its ExceptionTraceHolder object.
// This mapping can then be queried by lyra::getExceptionTrace to get the stack
// trace for the exception. We have a custom exception destructor to destroy the
// trace object and call the original destructor for the exception object, and
// our __cxa_throw hook calls the original __cxa_throw to perform the actual
// exception throwing and passes this custom destructor.
//
// This works because __cxa_throw is only called when creating a new exception
// object (that has been freshly allocated via __cxa_allocate_exception), so at
// that point, we're able to capture the original stack trace for the exception.
// Even if that exception is later rethrown, we'll still maintain its original
// stack trace, assuming that std::current_exception creates a reference to the
// current exception instead of copying it (which is true for both libstdc++ and
// libc++), such that we can still look up the exception object via pointer.
//
// We don't have to worry about any pointer adjustments for the exception object
// (e.g. for converting to or from a base class subobject pointer), because a
// std::exception_ptr will always capture the pointer to the exception object
// itself and not any subobjects.
//
// Our map must be global, since exceptions can be transferred across threads.
// Consequently, we must use a mutex to guard all map operations.

typedef void (*destructor_type)(void*);

namespace {
struct ExceptionState {
  ExceptionTraceHolder trace;
  destructor_type destructor;
};

// We create our map and mutex as function statics and leak them intentionally,
// to ensure they've been initialized before any global constructors and are
// also available to use inside any global destructors.
std::unordered_map<void*, ExceptionState>* get_exception_state_map() {
  static auto* exception_state_map =
      new std::unordered_map<void*, ExceptionState>();
  return exception_state_map;
}

std::mutex* get_exception_state_map_mutex() {
  static auto* exception_state_map_mutex = new std::mutex();
  return exception_state_map_mutex;
}

void trace_destructor(void* exception_obj) {
  destructor_type original_destructor = nullptr;

  {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    auto* exception_state_map = get_exception_state_map();
    auto it = exception_state_map->find(exception_obj);
    if (it == exception_state_map->end()) {
      // This really shouldn't happen, but if it does, just leaking the trace
      // and exception object seems better than crashing.
      return;
    }

    original_destructor = it->second.destructor;
    exception_state_map->erase(it);
  }

  if (original_destructor) {
    original_destructor(exception_obj);
  }
}
} // namespace

[[noreturn]] void
cxa_throw(void* obj, const std::type_info* type, destructor_type destructor) {
  if (enableBacktraces.load(std::memory_order_relaxed)) {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    get_exception_state_map()->emplace(
        obj, ExceptionState{ExceptionTraceHolder(), destructor});
  }

  original_cxa_throw(obj, type, trace_destructor);
}

const ExceptionTraceHolder* detail::getExceptionTraceHolder(
    std::exception_ptr ptr) {
  {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    // The exception object pointer isn't a public member of std::exception_ptr,
    // and there isn't any public method to get it. However, for both libstdc++
    // and libc++, it's the first pointer inside the exception_ptr, and we can
    // rely on the ABI of those libraries to remain stable, so we can just
    // access it directly.
    void* exception_obj = *reinterpret_cast<void**>(&ptr);
    auto* exception_state_map = get_exception_state_map();
    auto it = exception_state_map->find(exception_obj);
    if (it != exception_state_map->end()) {
      return &it->second.trace;
    }
  }

  // Fall back to attempting to retrieve the ExceptionTraceHolder directly from
  // the exception (to support e.g. fbthrow).
  return getExceptionTraceHolderInException(ptr);
}
#else

namespace {

const auto traceHolderType =
  static_cast<const abi::__class_type_info*>(&typeid(ExceptionTraceHolder));

// lyra's __cxa_throw attaches stack trace information to thrown exceptions. It basically does:
//   1. capture stack trace
//   2. construct a new type_info struct that:
//     a. holds the ExceptionTraceHolder
//     b. supports upcasting to lyra::ExceptionTraceHolder* (by just returning the holder member)
//     c. acts like the original exception type_info otherwise
//   3. call original __cxa_throw() with original exception pointer, the
//      HijackedExceptionTypeInfo, and HijackedExceptionTypeInfo::destructor
//      (which will both delete the constructed type info and call the original
//      destructor).
struct HijackedExceptionTypeInfo : public abi::__class_type_info {
  HijackedExceptionTypeInfo(void* obj, const std::type_info* base, void(*destructor)(void*))
      : abi::__class_type_info{base->name()}, base_{base}, orig_dest_{destructor} {
  }

  bool __is_pointer_p() const override {
    return base_->__is_pointer_p();
  }

  bool __is_function_p() const override {
    return base_->__is_function_p();
  }

  bool __do_catch(const type_info *__thr_type, void **__thr_obj, unsigned __outer) const override {
    return base_->__do_catch(__thr_type, __thr_obj, __outer);
  }

  bool __do_upcast(const abi::__class_type_info *__target, void **__obj_ptr) const override {
    if (__target == traceHolderType) {
      *__obj_ptr = (void*)&stack_;
      return true;
    }
    return base_->__do_upcast(__target, __obj_ptr);
  }

  static void destructor(void* obj) {
    auto exc_ptr = reinterpret_cast<std::exception_ptr*>(&obj);
    auto info = reinterpret_cast<const::std::type_info*>(exc_ptr->__cxa_exception_type());
    auto mutable_info = static_cast<HijackedExceptionTypeInfo*>(const_cast<std::type_info*>(info));
    mutable_info->orig_dest_(obj);
    delete mutable_info;
  }

 private:
  const std::type_info* base_;
  void (*orig_dest_)(void*);
  ExceptionTraceHolder stack_;
};

} // namespace

[[noreturn]] void cxa_throw(void* obj, const std::type_info* type, void (*destructor) (void *)) {
  if (enableBacktraces.load(std::memory_order_relaxed)) {
    if (!type->__do_upcast(traceHolderType, &obj)) {
      type = new HijackedExceptionTypeInfo(obj, type, destructor);
      destructor = HijackedExceptionTypeInfo::destructor;
    }
  }
  original_cxa_throw(obj, type, destructor);
}

const ExceptionTraceHolder* detail::getExceptionTraceHolder(
    std::exception_ptr ptr) {
  return getExceptionTraceHolderInException(ptr);
}

#endif // libc++

} // namespace lyra
} // namespace facebook
<commit_msg>Reorder some includes<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <atomic>
#include <mutex>
#include <stdexcept>
#include <unordered_map>
#include <cassert>
#include <unwind.h>
#include <cxxabi.h>

#include <lyra/lyra_exceptions.h>

namespace facebook {
namespace lyra {

using namespace detail;

namespace {
std::atomic<bool> enableBacktraces{true};

const ExceptionTraceHolder* getExceptionTraceHolderInException(
    std::exception_ptr ptr) {
  try {
    std::rethrow_exception(ptr);
  } catch (const ExceptionTraceHolder& holder) {
    return &holder;
  } catch (...) {
    return nullptr;
  }
}
} // namespace

void enableCxaThrowHookBacktraces(bool enable) {
  enableBacktraces.store(enable, std::memory_order_relaxed);
}

[[gnu::noreturn]] void (*original_cxa_throw)(void*, const std::type_info*, void (*) (void *));

#if defined(_LIBCPP_VERSION)

// We want to attach stack traces to C++ exceptions. Our API contract is that
// calling lyra::getExceptionTrace on the exception_ptr for an exception should
// return the stack trace for that exception.
//
// We accomplish this by providing a hook for __cxa_throw, which creates an
// ExceptionTraceHolder object (which captures the stack trace for the
// exception), and creates a mapping from the pointer to the exception object
// (which is a parameter to __cxa_throw) to its ExceptionTraceHolder object.
// This mapping can then be queried by lyra::getExceptionTrace to get the stack
// trace for the exception. We have a custom exception destructor to destroy the
// trace object and call the original destructor for the exception object, and
// our __cxa_throw hook calls the original __cxa_throw to perform the actual
// exception throwing and passes this custom destructor.
//
// This works because __cxa_throw is only called when creating a new exception
// object (that has been freshly allocated via __cxa_allocate_exception), so at
// that point, we're able to capture the original stack trace for the exception.
// Even if that exception is later rethrown, we'll still maintain its original
// stack trace, assuming that std::current_exception creates a reference to the
// current exception instead of copying it (which is true for both libstdc++ and
// libc++), such that we can still look up the exception object via pointer.
//
// We don't have to worry about any pointer adjustments for the exception object
// (e.g. for converting to or from a base class subobject pointer), because a
// std::exception_ptr will always capture the pointer to the exception object
// itself and not any subobjects.
//
// Our map must be global, since exceptions can be transferred across threads.
// Consequently, we must use a mutex to guard all map operations.

typedef void (*destructor_type)(void*);

namespace {
struct ExceptionState {
  ExceptionTraceHolder trace;
  destructor_type destructor;
};

// We create our map and mutex as function statics and leak them intentionally,
// to ensure they've been initialized before any global constructors and are
// also available to use inside any global destructors.
std::unordered_map<void*, ExceptionState>* get_exception_state_map() {
  static auto* exception_state_map =
      new std::unordered_map<void*, ExceptionState>();
  return exception_state_map;
}

std::mutex* get_exception_state_map_mutex() {
  static auto* exception_state_map_mutex = new std::mutex();
  return exception_state_map_mutex;
}

void trace_destructor(void* exception_obj) {
  destructor_type original_destructor = nullptr;

  {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    auto* exception_state_map = get_exception_state_map();
    auto it = exception_state_map->find(exception_obj);
    if (it == exception_state_map->end()) {
      // This really shouldn't happen, but if it does, just leaking the trace
      // and exception object seems better than crashing.
      return;
    }

    original_destructor = it->second.destructor;
    exception_state_map->erase(it);
  }

  if (original_destructor) {
    original_destructor(exception_obj);
  }
}
} // namespace

[[noreturn]] void
cxa_throw(void* obj, const std::type_info* type, destructor_type destructor) {
  if (enableBacktraces.load(std::memory_order_relaxed)) {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    get_exception_state_map()->emplace(
        obj, ExceptionState{ExceptionTraceHolder(), destructor});
  }

  original_cxa_throw(obj, type, trace_destructor);
}

const ExceptionTraceHolder* detail::getExceptionTraceHolder(
    std::exception_ptr ptr) {
  {
    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());
    // The exception object pointer isn't a public member of std::exception_ptr,
    // and there isn't any public method to get it. However, for both libstdc++
    // and libc++, it's the first pointer inside the exception_ptr, and we can
    // rely on the ABI of those libraries to remain stable, so we can just
    // access it directly.
    void* exception_obj = *reinterpret_cast<void**>(&ptr);
    auto* exception_state_map = get_exception_state_map();
    auto it = exception_state_map->find(exception_obj);
    if (it != exception_state_map->end()) {
      return &it->second.trace;
    }
  }

  // Fall back to attempting to retrieve the ExceptionTraceHolder directly from
  // the exception (to support e.g. fbthrow).
  return getExceptionTraceHolderInException(ptr);
}
#else

namespace {

const auto traceHolderType =
  static_cast<const abi::__class_type_info*>(&typeid(ExceptionTraceHolder));

// lyra's __cxa_throw attaches stack trace information to thrown exceptions. It basically does:
//   1. capture stack trace
//   2. construct a new type_info struct that:
//     a. holds the ExceptionTraceHolder
//     b. supports upcasting to lyra::ExceptionTraceHolder* (by just returning the holder member)
//     c. acts like the original exception type_info otherwise
//   3. call original __cxa_throw() with original exception pointer, the
//      HijackedExceptionTypeInfo, and HijackedExceptionTypeInfo::destructor
//      (which will both delete the constructed type info and call the original
//      destructor).
struct HijackedExceptionTypeInfo : public abi::__class_type_info {
  HijackedExceptionTypeInfo(void* obj, const std::type_info* base, void(*destructor)(void*))
      : abi::__class_type_info{base->name()}, base_{base}, orig_dest_{destructor} {
  }

  bool __is_pointer_p() const override {
    return base_->__is_pointer_p();
  }

  bool __is_function_p() const override {
    return base_->__is_function_p();
  }

  bool __do_catch(const type_info *__thr_type, void **__thr_obj, unsigned __outer) const override {
    return base_->__do_catch(__thr_type, __thr_obj, __outer);
  }

  bool __do_upcast(const abi::__class_type_info *__target, void **__obj_ptr) const override {
    if (__target == traceHolderType) {
      *__obj_ptr = (void*)&stack_;
      return true;
    }
    return base_->__do_upcast(__target, __obj_ptr);
  }

  static void destructor(void* obj) {
    auto exc_ptr = reinterpret_cast<std::exception_ptr*>(&obj);
    auto info = reinterpret_cast<const::std::type_info*>(exc_ptr->__cxa_exception_type());
    auto mutable_info = static_cast<HijackedExceptionTypeInfo*>(const_cast<std::type_info*>(info));
    mutable_info->orig_dest_(obj);
    delete mutable_info;
  }

 private:
  const std::type_info* base_;
  void (*orig_dest_)(void*);
  ExceptionTraceHolder stack_;
};

} // namespace

[[noreturn]] void cxa_throw(void* obj, const std::type_info* type, void (*destructor) (void *)) {
  if (enableBacktraces.load(std::memory_order_relaxed)) {
    if (!type->__do_upcast(traceHolderType, &obj)) {
      type = new HijackedExceptionTypeInfo(obj, type, destructor);
      destructor = HijackedExceptionTypeInfo::destructor;
    }
  }
  original_cxa_throw(obj, type, destructor);
}

const ExceptionTraceHolder* detail::getExceptionTraceHolder(
    std::exception_ptr ptr) {
  return getExceptionTraceHolderInException(ptr);
}

#endif // libc++

} // namespace lyra
} // namespace facebook
<|endoftext|>


<commit_before>/*
 * Copyright 2008, 2009 Google Inc.
 * Copyright 2007 Nintendo Co., Ltd.
 *
 * 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 "esidl.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>

namespace
{
    std::string baseFilename;
    std::string filename;
}

const std::string getBaseFilename()
{
    return baseFilename;
}

void setBaseFilename(const char* name)
{
    baseFilename = name;
    if (baseFilename[0] == '"')
    {
        baseFilename = baseFilename.substr(1, baseFilename.length() - 2);
    }
    setFilename(name);
}

const std::string getFilename()
{
    return filename;
}

void setFilename(const char* name)
{
    filename = name;
    if (filename == "\"<stdin>\"")
    {
        filename = getBaseFilename();
    }
    else if (filename[0] == '"')
    {
        filename = filename.substr(1, filename.length() - 2);
    }
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        return EXIT_FAILURE;
    }

    // Construct cpp options
    const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2)));
    if (!argCpp)
    {
        return EXIT_FAILURE;
    }

    int optCpp = 0;
    argCpp[optCpp++] = "cpp";
    argCpp[optCpp++] = "-C";  // Use -C for cpp by default.

    bool skeleton = false;
    bool generic = false;
    bool isystem = false;
    bool useExceptions = true;
    const char* stringTypeName = "char*";   // C++ string type name to be used
    const char* indent = "es";

    for (int i = 1; i < argc; ++i)
    {
        if (argv[i][0] == '-')
        {
            if (argv[i][1] == 'I')
            {
                argCpp[optCpp++] = argv[i];
                if (argv[i][2] == '\0')
                {
                    ++i;
                    argCpp[optCpp++] = argv[i];
                    setIncludePath(argv[i]);
                }
                else
                {
                    setIncludePath(&argv[i][2]);
                }
            }
            else if (strcmp(argv[i], "-fexceptions") == 0)
            {
                useExceptions = true;
            }
            else if (strcmp(argv[i], "-fno-exceptions") == 0)
            {
                useExceptions = false;
            }
            else if (strcmp(argv[i], "-include") == 0)
            {
                argCpp[optCpp++] = argv[i];
                ++i;
                argCpp[optCpp++] = argv[i];
            }
            else if (strcmp(argv[i], "-isystem") == 0)
            {
                argCpp[optCpp++] = argv[i];
                ++i;
                argCpp[optCpp++] = argv[i];
                setIncludePath(argv[i]);
                isystem = true;
            }
            else if (strcmp(argv[i], "-namespace") == 0)
            {
                ++i;
                Node::setFlatNamespace(argv[i]);
            }
            else if (strcmp(argv[i], "-object") == 0)
            {
                ++i;
                Node::setBaseObjectName(argv[i]);
            }
            else if (strcmp(argv[i], "-template") == 0)
            {
                generic = true;
            }
            else if (strcmp(argv[i], "-skeleton") == 0)
            {
                skeleton = true;
            }
            else if (strcmp(argv[i], "-string") == 0)
            {
                ++i;
                stringTypeName = argv[i];
            }
            else if (strcmp(argv[i], "-indent") == 0)
            {
                ++i;
                indent = argv[i];
            }
        }
    }
    argCpp[optCpp] = 0;

    // Set up the global module
    Module* node = new Module("");
    setSpecification(node);
    setCurrent(node);

    if (strcmp(Node::getBaseObjectName(), "::Object") == 0)
    {
        // Manually install 'Object' interface forward declaration.
        Interface* object = new Interface("Object", 0, true);
        object->setRank(2);
        getCurrent()->add(object);
    }

    if (Node::getFlatNamespace())
    {
        Module* module = new Module(Node::getFlatNamespace());
        getCurrent()->add(module);
        setCurrent(module);
    }

    // Load every IDL file at once
    int result = EXIT_SUCCESS;
    int cppStream[2];
    pipe(cppStream);
    pid_t id = fork();
    if (id == 0)
    {
        // Child process
        int catStream[2];
        pipe(catStream);
        pid_t id = fork();
        if (id == 0)
        {
            // cat every IDL file
            close(catStream[0]);
            FILE* out = fdopen(catStream[1], "w");
            for (int i = 1; i < argc; ++i)
            {
                if (argv[i][0] == '-')
                {
                    if (strcmp(argv[i], "-I") == 0 ||
                        strcmp(argv[i], "-include") == 0 ||
                        strcmp(argv[i], "-isystem") == 0 ||
                        strcmp(argv[i], "-namespace") == 0 ||
                        strcmp(argv[i], "-object") == 0 ||
                        strcmp(argv[i], "-string") == 0 ||
                        strcmp(argv[i], "-indent") == 0)
                    {
                        ++i;
                    }
                    continue;
                }

                FILE* in = fopen(argv[i], "r");
                if (!in)
                {
                    return EXIT_FAILURE;
                }

                fprintf(out, "#pragma source \"%s\"\n", argv[i]);
                int ch;
                while ((ch = fgetc(in)) != EOF)
                {
                    putc(ch, out);
                }
                fclose(in);
            }
            fclose(out);
            return EXIT_SUCCESS;
        }
        else if (0 < id)
        {
            // execute cpp
            close(0);
            dup(catStream[0]);
            close(catStream[0]);
            close(catStream[1]);
            close(1);
            dup(cppStream[1]);
            close(cppStream[0]);
            close(cppStream[1]);
            execvp(argCpp[0], const_cast<char**>(argCpp));
            return EXIT_FAILURE;
        }
        else
        {
            return EXIT_FAILURE;
        }
    }
    else if (0 < id)
    {
        // Parent process - process an IDL file
        close(cppStream[1]);
        if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS)
        {
            return EXIT_FAILURE;
        }
        close(cppStream[0]);

        int status;
        while (wait(&status) != id)
        {
        }
        if (result == EXIT_SUCCESS)
        {
            if (!WIFEXITED(status))
            {
                result = EXIT_FAILURE;
            }
            else
            {
                result = WEXITSTATUS(status);
            }
        }
    }
    else
    {
        return EXIT_FAILURE;
    }

    setBaseFilename("");

    ProcessExtendedAttributes processExtendedAttributes;
    getSpecification()->accept(&processExtendedAttributes);

    AdjustMethodCount adjustMethodCount;
    getSpecification()->accept(&adjustMethodCount);

    for (int i = 1; i < argc; ++i)
    {
        if (argv[i][0] == '-')
        {
            if (strcmp(argv[i], "-I") == 0 ||
                strcmp(argv[i], "-include") == 0 ||
                strcmp(argv[i], "-isystem") == 0 ||
                strcmp(argv[i], "-namespace") == 0 ||
                strcmp(argv[i], "-object") == 0 ||
                strcmp(argv[i], "-string") == 0)
            {
                ++i;
            }
            continue;
        }
        result = output(argv[i], isystem, useExceptions, stringTypeName, indent,
                        skeleton, generic);
    }

    return result;
}
<commit_msg>(main) : Fix bugs.<commit_after>/*
 * Copyright 2008, 2009 Google Inc.
 * Copyright 2007 Nintendo Co., Ltd.
 *
 * 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 "esidl.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>

namespace
{
    std::string baseFilename;
    std::string filename;
}

const std::string getBaseFilename()
{
    return baseFilename;
}

void setBaseFilename(const char* name)
{
    baseFilename = name;
    if (baseFilename[0] == '"')
    {
        baseFilename = baseFilename.substr(1, baseFilename.length() - 2);
    }
    setFilename(name);
}

const std::string getFilename()
{
    return filename;
}

void setFilename(const char* name)
{
    filename = name;
    if (filename == "\"<stdin>\"")
    {
        filename = getBaseFilename();
    }
    else if (filename[0] == '"')
    {
        filename = filename.substr(1, filename.length() - 2);
    }
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        return EXIT_FAILURE;
    }

    // Construct cpp options
    const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2)));
    if (!argCpp)
    {
        return EXIT_FAILURE;
    }

    int optCpp = 0;
    argCpp[optCpp++] = "cpp";
    argCpp[optCpp++] = "-C";  // Use -C for cpp by default.

    bool skeleton = false;
    bool generic = false;
    bool isystem = false;
    bool useExceptions = true;
    const char* stringTypeName = "char*";   // C++ string type name to be used
    const char* indent = "es";

    for (int i = 1; i < argc; ++i)
    {
        if (argv[i][0] == '-')
        {
            if (argv[i][1] == 'I')
            {
                argCpp[optCpp++] = argv[i];
                if (argv[i][2] == '\0')
                {
                    ++i;
                    argCpp[optCpp++] = argv[i];
                    setIncludePath(argv[i]);
                }
                else
                {
                    setIncludePath(&argv[i][2]);
                }
            }
            else if (strcmp(argv[i], "-fexceptions") == 0)
            {
                useExceptions = true;
            }
            else if (strcmp(argv[i], "-fno-exceptions") == 0)
            {
                useExceptions = false;
            }
            else if (strcmp(argv[i], "-include") == 0)
            {
                argCpp[optCpp++] = argv[i];
                ++i;
                argCpp[optCpp++] = argv[i];
            }
            else if (strcmp(argv[i], "-indent") == 0)
            {
                ++i;
                indent = argv[i];
            }
            else if (strcmp(argv[i], "-isystem") == 0)
            {
                argCpp[optCpp++] = argv[i];
                ++i;
                argCpp[optCpp++] = argv[i];
                setIncludePath(argv[i]);
                isystem = true;
            }
            else if (strcmp(argv[i], "-namespace") == 0)
            {
                ++i;
                Node::setFlatNamespace(argv[i]);
            }
            else if (strcmp(argv[i], "-object") == 0)
            {
                ++i;
                Node::setBaseObjectName(argv[i]);
            }
            else if (strcmp(argv[i], "-template") == 0)
            {
                generic = true;
            }
            else if (strcmp(argv[i], "-skeleton") == 0)
            {
                skeleton = true;
            }
            else if (strcmp(argv[i], "-string") == 0)
            {
                ++i;
                stringTypeName = argv[i];
            }
        }
    }
    argCpp[optCpp] = 0;

    // Set up the global module
    Module* node = new Module("");
    setSpecification(node);
    setCurrent(node);

    if (strcmp(Node::getBaseObjectName(), "::Object") == 0)
    {
        // Manually install 'Object' interface forward declaration.
        Interface* object = new Interface("Object", 0, true);
        object->setRank(2);
        getCurrent()->add(object);
    }

    if (Node::getFlatNamespace())
    {
        Module* module = new Module(Node::getFlatNamespace());
        getCurrent()->add(module);
        setCurrent(module);
    }

    // Load every IDL file at once
    int result = EXIT_SUCCESS;
    int cppStream[2];
    pipe(cppStream);
    pid_t id = fork();
    if (id == 0)
    {
        // Child process
        int catStream[2];
        pipe(catStream);
        pid_t id = fork();
        if (id == 0)
        {
            // cat every IDL file
            close(catStream[0]);
            FILE* out = fdopen(catStream[1], "w");
            for (int i = 1; i < argc; ++i)
            {
                if (argv[i][0] == '-')
                {
                    if (strcmp(argv[i], "-I") == 0 ||
                        strcmp(argv[i], "-include") == 0 ||
                        strcmp(argv[i], "-indent") == 0 ||
                        strcmp(argv[i], "-isystem") == 0 ||
                        strcmp(argv[i], "-namespace") == 0 ||
                        strcmp(argv[i], "-object") == 0 ||
                        strcmp(argv[i], "-string") == 0)
                    {
                        ++i;
                    }
                    continue;
                }

                FILE* in = fopen(argv[i], "r");
                if (!in)
                {
                    return EXIT_FAILURE;
                }

                fprintf(out, "#pragma source \"%s\"\n", argv[i]);
                int ch;
                while ((ch = fgetc(in)) != EOF)
                {
                    putc(ch, out);
                }
                fclose(in);
            }
            fclose(out);
            return EXIT_SUCCESS;
        }
        else if (0 < id)
        {
            // execute cpp
            close(0);
            dup(catStream[0]);
            close(catStream[0]);
            close(catStream[1]);
            close(1);
            dup(cppStream[1]);
            close(cppStream[0]);
            close(cppStream[1]);
            execvp(argCpp[0], const_cast<char**>(argCpp));
            return EXIT_FAILURE;
        }
        else
        {
            return EXIT_FAILURE;
        }
    }
    else if (0 < id)
    {
        // Parent process - process an IDL file
        close(cppStream[1]);
        if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS)
        {
            return EXIT_FAILURE;
        }
        close(cppStream[0]);

        int status;
        while (wait(&status) != id)
        {
        }
        if (result == EXIT_SUCCESS)
        {
            if (!WIFEXITED(status))
            {
                result = EXIT_FAILURE;
            }
            else
            {
                result = WEXITSTATUS(status);
            }
        }
    }
    else
    {
        return EXIT_FAILURE;
    }

    setBaseFilename("");

    ProcessExtendedAttributes processExtendedAttributes;
    getSpecification()->accept(&processExtendedAttributes);

    AdjustMethodCount adjustMethodCount;
    getSpecification()->accept(&adjustMethodCount);

    for (int i = 1; i < argc; ++i)
    {
        if (argv[i][0] == '-')
        {
            if (strcmp(argv[i], "-I") == 0 ||
                strcmp(argv[i], "-include") == 0 ||
                strcmp(argv[i], "-indent") == 0 ||
                strcmp(argv[i], "-isystem") == 0 ||
                strcmp(argv[i], "-namespace") == 0 ||
                strcmp(argv[i], "-object") == 0 ||
                strcmp(argv[i], "-string") == 0)
            {
                ++i;
            }
            continue;
        }
        result = output(argv[i], isystem, useExceptions, stringTypeName, indent,
                        skeleton, generic);
    }

    return result;
}
<|endoftext|>