<commit_before>/***************************************************************************
 *   Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QAction>
# include <QMenu>
# include <QMessageBox>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoSwitch.h>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoNormal.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Bnd_Box.hxx>
# include <BRepBndLib.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
#endif

#include "ViewProviderPrimitive.h"
#include "TaskPrimitiveParameters.h"
#include "Mod/Part/Gui/SoBrepFaceSet.h"
#include <Mod/PartDesign/App/FeaturePrimitive.h>
#include <Gui/TaskView/TaskDialog.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Base/Console.h>

using namespace PartDesignGui;

PROPERTY_SOURCE(PartDesignGui::ViewProviderPrimitive,PartDesignGui::ViewProvider)

ViewProviderPrimitive::ViewProviderPrimitive()
{
}

ViewProviderPrimitive::~ViewProviderPrimitive()
{

}

void ViewProviderPrimitive::attach(App::DocumentObject* obj) {
    ViewProviderAddSub::attach(obj);
}

void ViewProviderPrimitive::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    QAction* act;
    act = menu->addAction(QObject::tr("Edit primitive"), receiver, member);
    act->setData(QVariant((int)ViewProvider::Default));
    PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member);
}

bool ViewProviderPrimitive::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default ) {
        // When double-clicking on the item for this fillet the
        // object unsets and sets its edit mode without closing
        // the task panel
        Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog();
        TaskPrimitiveParameters *primitiveDlg = qobject_cast<TaskPrimitiveParameters *>(dlg);
        if (dlg && !primitiveDlg) {
            QMessageBox msgBox;
            msgBox.setText(QObject::tr("A dialog is already open in the task panel"));
            msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?"));
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if (ret == QMessageBox::Yes)
                Gui::Control().closeDialog();
            else
                return false;
        }

        // clear the selection (convenience)
        Gui::Selection().clearSelection();

        // always change to PartDesign WB, remember where we come from
        oldWb = Gui::Command::assureWorkbench("PartDesignWorkbench");

        // start the edit dialog
        // another pad left open its task panel
        if (primitiveDlg)
            Gui::Control().showDialog(primitiveDlg);
        else
            Gui::Control().showDialog(new TaskPrimitiveParameters(this));

        setPreviewDisplayMode(true);

        return true;
    }
    else {
        return ViewProviderAddSub::setEdit(ModNum);
    }
}

void ViewProviderPrimitive::unsetEdit(int ModNum)
{
    setPreviewDisplayMode(false);

    // Rely on parent class to:
    // restitute old workbench (set setEdit above) and close the dialog if exiting editing
    PartDesignGui::ViewProvider::unsetEdit(ModNum);

}

void ViewProviderPrimitive::updateData(const App::Property* p) {
    PartDesignGui::ViewProviderAddSub::updateData(p);
}

QIcon ViewProviderPrimitive::getIcon(void) const {

    QString str = QString::fromLatin1("PartDesign_");
    auto* prim = static_cast<PartDesign::FeaturePrimitive*>(getObject());
    if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive)
        str += QString::fromLatin1("Additive_");
    else
        str += QString::fromLatin1("Subtractive_");

    switch(prim->getPrimitiveType()) {
    case PartDesign::FeaturePrimitive::Box:
        str += QString::fromLatin1("Box");
        break;
    case PartDesign::FeaturePrimitive::Cylinder:
        str += QString::fromLatin1("Cylinder");
        break;
    case PartDesign::FeaturePrimitive::Sphere:
        str += QString::fromLatin1("Sphere");
        break;
    case PartDesign::FeaturePrimitive::Cone:
        str += QString::fromLatin1("Cone");
        break;
    case PartDesign::FeaturePrimitive::Ellipsoid:
        str += QString::fromLatin1("Ellipsoid");
        break;
    case PartDesign::FeaturePrimitive::Torus:
        str += QString::fromLatin1("Torus");
        break;
    case PartDesign::FeaturePrimitive::Prism:
        str += QString::fromLatin1("Prism");
        break;
    case PartDesign::FeaturePrimitive::Wedge:
        str += QString::fromLatin1("Wedge");
        break;
    }

    str += QString::fromLatin1(".svg");
    return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str()));
}
<commit_msg>PD: [skip ci] fix ViewProviderPrimitive::getIcon() after renaming of icon files<commit_after>/***************************************************************************
 *   Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QAction>
# include <QMenu>
# include <QMessageBox>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoSwitch.h>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoNormal.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Bnd_Box.hxx>
# include <BRepBndLib.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
#endif

#include "ViewProviderPrimitive.h"
#include "TaskPrimitiveParameters.h"
#include "Mod/Part/Gui/SoBrepFaceSet.h"
#include <Mod/PartDesign/App/FeaturePrimitive.h>
#include <Gui/TaskView/TaskDialog.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Base/Console.h>

using namespace PartDesignGui;

PROPERTY_SOURCE(PartDesignGui::ViewProviderPrimitive,PartDesignGui::ViewProvider)

ViewProviderPrimitive::ViewProviderPrimitive()
{
}

ViewProviderPrimitive::~ViewProviderPrimitive()
{

}

void ViewProviderPrimitive::attach(App::DocumentObject* obj) {
    ViewProviderAddSub::attach(obj);
}

void ViewProviderPrimitive::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    QAction* act;
    act = menu->addAction(QObject::tr("Edit primitive"), receiver, member);
    act->setData(QVariant((int)ViewProvider::Default));
    PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member);
}

bool ViewProviderPrimitive::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default ) {
        // When double-clicking on the item for this fillet the
        // object unsets and sets its edit mode without closing
        // the task panel
        Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog();
        TaskPrimitiveParameters *primitiveDlg = qobject_cast<TaskPrimitiveParameters *>(dlg);
        if (dlg && !primitiveDlg) {
            QMessageBox msgBox;
            msgBox.setText(QObject::tr("A dialog is already open in the task panel"));
            msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?"));
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if (ret == QMessageBox::Yes)
                Gui::Control().closeDialog();
            else
                return false;
        }

        // clear the selection (convenience)
        Gui::Selection().clearSelection();

        // always change to PartDesign WB, remember where we come from
        oldWb = Gui::Command::assureWorkbench("PartDesignWorkbench");

        // start the edit dialog
        // another pad left open its task panel
        if (primitiveDlg)
            Gui::Control().showDialog(primitiveDlg);
        else
            Gui::Control().showDialog(new TaskPrimitiveParameters(this));

        setPreviewDisplayMode(true);

        return true;
    }
    else {
        return ViewProviderAddSub::setEdit(ModNum);
    }
}

void ViewProviderPrimitive::unsetEdit(int ModNum)
{
    setPreviewDisplayMode(false);

    // Rely on parent class to:
    // restitute old workbench (set setEdit above) and close the dialog if exiting editing
    PartDesignGui::ViewProvider::unsetEdit(ModNum);

}

void ViewProviderPrimitive::updateData(const App::Property* p) {
    PartDesignGui::ViewProviderAddSub::updateData(p);
}

QIcon ViewProviderPrimitive::getIcon(void) const {

    QString str = QString::fromLatin1("PartDesign_");
    auto* prim = static_cast<PartDesign::FeaturePrimitive*>(getObject());
    if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive)
        str += QString::fromLatin1("Additive");
    else
        str += QString::fromLatin1("Subtractive");

    switch(prim->getPrimitiveType()) {
    case PartDesign::FeaturePrimitive::Box:
        str += QString::fromLatin1("Box");
        break;
    case PartDesign::FeaturePrimitive::Cylinder:
        str += QString::fromLatin1("Cylinder");
        break;
    case PartDesign::FeaturePrimitive::Sphere:
        str += QString::fromLatin1("Sphere");
        break;
    case PartDesign::FeaturePrimitive::Cone:
        str += QString::fromLatin1("Cone");
        break;
    case PartDesign::FeaturePrimitive::Ellipsoid:
        str += QString::fromLatin1("Ellipsoid");
        break;
    case PartDesign::FeaturePrimitive::Torus:
        str += QString::fromLatin1("Torus");
        break;
    case PartDesign::FeaturePrimitive::Prism:
        str += QString::fromLatin1("Prism");
        break;
    case PartDesign::FeaturePrimitive::Wedge:
        str += QString::fromLatin1("Wedge");
        break;
    }

    str += QString::fromLatin1(".svg");
    return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str()));
}
<|endoftext|>


<commit_before><commit_msg>some initial refactoring in xmlcelli.cxx<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2012, Cornell University
// 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 the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.

// The purpose of this test is to expose consistency errors.

// C
#include <cstdlib>
#include <stdint.h>

// Popt
#include <popt.h>

// C++
#include <iostream>

// STL
#include <map>
#include <tr1/memory>
#include <vector>

// po6
#include <po6/threads/barrier.h>
#include <po6/threads/mutex.h>
#include <po6/threads/thread.h>

// e
#include <e/guard.h>

// HyperClient
#include <hyperclient.h>

static int64_t window = 128;
static int64_t repetitions = 1024;
static int64_t threads = 16;
static const char* space = "consistency";
static const char* host = "127.0.0.1";
static uint16_t port = 1234;
static std::auto_ptr<po6::threads::barrier> barrier;
static po6::threads::mutex results_lock;
static int done = 0;
static std::map<hyperclient_returncode, uint64_t> failed_puts;
static std::map<hyperclient_returncode, uint64_t> failed_loops;
static std::map<hyperclient_returncode, uint64_t> ops;
static uint64_t failed_writes = 0;
static uint64_t inconsistencies = 0;

extern "C"
{

static struct poptOption popts[] = {
    POPT_AUTOHELP
    {"window-size", 'w', POPT_ARG_LONGLONG, &window, 'w',
        "the number of sequential keys which will be used for the test",
        "keys"},
    {"repetitiions", 'r', POPT_ARG_LONGLONG, &repetitions, 'r',
        "the number of tests which will be run before exiting",
        "number"},
    {"threads", 't', POPT_ARG_LONGLONG, &threads, 't',
        "the number of threads which will check for inconsistencies",
        "number"},
    {"space", 's', POPT_ARG_STRING, &space, 's',
        "the HyperDex space to use",
        "space"},
    {"host", 'h', POPT_ARG_STRING, &host, 'h',
        "the IP address of the coordinator",
        "IP"},
    {"port", 'p', POPT_ARG_SHORT, &port, 'p',
        "the port number of the coordinator",
        "port"},
    POPT_TABLEEND
};

} // extern "C"

static void
writer_thread();
static void
reader_thread();

int
main(int argc, const char* argv[])
{
    poptContext poptcon;
    poptcon = poptGetContext(NULL, argc, (const char**) argv, popts, POPT_CONTEXT_POSIXMEHARDER);
    e::guard g = e::makeguard(poptFreeContext, poptcon);
    g.use_variable();
    int rc;

    while ((rc = poptGetNextOpt(poptcon)) != -1)
    {
        switch (rc)
        {
            case 'w':
                if (window < 0)
                {
                    std::cerr << "window-size must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 'r':
                if (repetitions < 0)
                {
                    std::cerr << "repetitions must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 't':
                if (threads < 0)
                {
                    std::cerr << "threads must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 's':
                break;
            case 'h':
                break;
            case 'p':
                break;
            case POPT_ERROR_NOARG:
            case POPT_ERROR_BADOPT:
            case POPT_ERROR_BADNUMBER:
            case POPT_ERROR_OVERFLOW:
                std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl;
                return EXIT_FAILURE;
            case POPT_ERROR_OPTSTOODEEP:
            case POPT_ERROR_BADQUOTE:
            case POPT_ERROR_ERRNO:
            default:
                std::cerr << "logic error in argument parsing" << std::endl;
                return EXIT_FAILURE;
        }
    }

    barrier.reset(new po6::threads::barrier(threads + 1));
    po6::threads::thread writer(writer_thread);
    writer.start();
    std::vector<std::tr1::shared_ptr<po6::threads::thread> > readers;

    for (int64_t i = 0; i < threads; ++i)
    {
        std::tr1::shared_ptr<po6::threads::thread> tptr(new po6::threads::thread(reader_thread));
        readers.push_back(tptr);
        tptr->start();
    }

    writer.join();

    bool success = __sync_bool_compare_and_swap(&done, 0, 1);
    assert(success);

    for (int64_t i = 0; i < threads; ++i)
    {
        readers[i]->join();
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;
    std::cout << "Failed puts:" << std::endl;

    for (result_iter_t o = failed_puts.begin(); o != failed_puts.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "Failed loops:" << std::endl;

    for (result_iter_t o = failed_loops.begin(); o != failed_loops.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "Normal ops:" << std::endl;

    for (result_iter_t o = ops.begin(); o != ops.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "failed writes:  " << failed_writes << std::endl
              << "Inconsistencies:  " << inconsistencies << std::endl;
    return EXIT_SUCCESS;
}

static void
writer_thread()
{
    std::map<hyperclient_returncode, uint64_t> lfailed_puts;
    std::map<hyperclient_returncode, uint64_t> lfailed_loops;
    std::map<hyperclient_returncode, uint64_t> lops;
    uint64_t lfailed_writes = 0;
    hyperclient cl(host, port);
    bool fail = false;

    for (int64_t i = 0; i < window; ++i)
    {
        int64_t key = htobe64(i);
        int64_t did;
        hyperclient_returncode dstatus;

        const char* keystr = reinterpret_cast<const char*>(&key);
        did = cl.del(space, keystr, sizeof(key), &dstatus);

        if (did < 0)
        {
            std::cerr << "delete failed with " << dstatus << std::endl;
            fail = true;
            break;
        }

        int64_t lid;
        hyperclient_returncode lstatus;
        lid = cl.loop(-1, &lstatus);

        if (lid < 0)
        {
            std::cerr << "loop failed with " << lstatus << std::endl;
            fail = true;
            break;
        }

        assert(lid == did);

        if (dstatus != HYPERCLIENT_SUCCESS && dstatus != HYPERCLIENT_NOTFOUND)
        {
            std::cerr << "delete returned " << dstatus << std::endl;
            fail = true;
            break;
        }
    }

    barrier->wait();

    if (fail)
    {
        std::cerr << "the above errors are fatal" << std::endl;
        return;
    }

    std::cout << "starting the consistency stress test" << std::endl;

    for (int64_t r = 0; r < repetitions; ++r)
    {
        for (int64_t i = 0; i < window; ++i)
        {
            uint64_t count = 0;

            for (count = 0; count < 65536; ++count)
            {
                int64_t key = htobe64(i);
                int64_t val = htobe64(r);
                int64_t pid;
                hyperclient_attribute attr;
                hyperclient_returncode pstatus;

                const char* keystr = reinterpret_cast<const char*>(&key);
                attr.attr = "repetition";
                attr.value = reinterpret_cast<const char*>(&val);
                attr.value_sz = sizeof(val);
                pid = cl.put(space, keystr, sizeof(key), &attr, 1, &pstatus);

                if (pid < 0)
                {
                    ++lfailed_puts[pstatus];
                    continue;
                }

                int64_t lid;
                hyperclient_returncode lstatus;
                lid = cl.loop(-1, &lstatus);

                if (lid < 0)
                {
                    ++lfailed_loops[lstatus];
                    continue;
                }

                assert(lid == pid);
                ++lops[pstatus];
                break;
            }

            if (count == 65536)
            {
                ++lfailed_writes;
            }
        }

        std::cout << "done " << r << "/" << repetitions << std::endl;
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;

    for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o)
    {
        failed_puts[o->first] += o->second;
    }

    for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o)
    {
        failed_loops[o->first] += o->second;
    }

    for (result_iter_t o = lops.begin(); o != lops.end(); ++o)
    {
        ops[o->first] += o->second;
    }

    failed_writes = lfailed_writes;
}

static void
reader_thread()
{
    std::map<hyperclient_returncode, uint64_t> lfailed_puts;
    std::map<hyperclient_returncode, uint64_t> lfailed_loops;
    std::map<hyperclient_returncode, uint64_t> lops;
    uint64_t linconsistencies = 0;
    hyperclient cl(host, port);
    barrier->wait();

    while (!__sync_bool_compare_and_swap(&done, 1, 1))
    {
        int64_t oldval = 0;

        for (int64_t i = window - 1; i >= 0; --i)
        {
            while (true)
            {
                int64_t key = htobe64(i);
                int64_t gid;
                hyperclient_attribute* attrs = NULL;
                size_t attrs_sz = 0;
                hyperclient_returncode gstatus;

                const char* keystr = reinterpret_cast<const char*>(&key);
                gid = cl.get(space, keystr, sizeof(key), &gstatus, &attrs, &attrs_sz);

                if (gid < 0)
                {
                    ++lfailed_puts[gstatus];
                    continue;
                }

                int64_t lid;
                hyperclient_returncode lstatus;
                lid = cl.loop(-1, &lstatus);

                if (lid < 0)
                {
                    ++lfailed_loops[lstatus];
                    continue;
                }

                assert(lid == gid);
                ++lops[gstatus];

                if (gstatus == HYPERCLIENT_SUCCESS)
                {
                    assert(attrs_sz == 1);
                    assert(strcmp(attrs[0].attr, "repetition") == 0);
                    int64_t val;
                    memmove(&val, attrs[0].value, attrs[0].value_sz);
                    val = be64toh(val);

                    if (val < oldval)
                    {
                        ++inconsistencies;
                    }

                    oldval = val;
                }

                if (attrs)
                {
                    hyperclient_destroy_attrs(attrs, attrs_sz);
                }

                break;
            }
        }
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;

    for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o)
    {
        failed_puts[o->first] += o->second;
    }

    for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o)
    {
        failed_loops[o->first] += o->second;
    }

    for (result_iter_t o = lops.begin(); o != lops.end(); ++o)
    {
        ops[o->first] += o->second;
    }

    inconsistencies += linconsistencies;
}
<commit_msg>Initialize "val" in scst.<commit_after>// Copyright (c) 2012, Cornell University
// 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 the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.

// The purpose of this test is to expose consistency errors.

// C
#include <cstdlib>
#include <stdint.h>

// Popt
#include <popt.h>

// C++
#include <iostream>

// STL
#include <map>
#include <tr1/memory>
#include <vector>

// po6
#include <po6/threads/barrier.h>
#include <po6/threads/mutex.h>
#include <po6/threads/thread.h>

// e
#include <e/guard.h>

// HyperClient
#include <hyperclient.h>

static int64_t window = 128;
static int64_t repetitions = 1024;
static int64_t threads = 16;
static const char* space = "consistency";
static const char* host = "127.0.0.1";
static uint16_t port = 1234;
static std::auto_ptr<po6::threads::barrier> barrier;
static po6::threads::mutex results_lock;
static int done = 0;
static std::map<hyperclient_returncode, uint64_t> failed_puts;
static std::map<hyperclient_returncode, uint64_t> failed_loops;
static std::map<hyperclient_returncode, uint64_t> ops;
static uint64_t failed_writes = 0;
static uint64_t inconsistencies = 0;

extern "C"
{

static struct poptOption popts[] = {
    POPT_AUTOHELP
    {"window-size", 'w', POPT_ARG_LONGLONG, &window, 'w',
        "the number of sequential keys which will be used for the test",
        "keys"},
    {"repetitiions", 'r', POPT_ARG_LONGLONG, &repetitions, 'r',
        "the number of tests which will be run before exiting",
        "number"},
    {"threads", 't', POPT_ARG_LONGLONG, &threads, 't',
        "the number of threads which will check for inconsistencies",
        "number"},
    {"space", 's', POPT_ARG_STRING, &space, 's',
        "the HyperDex space to use",
        "space"},
    {"host", 'h', POPT_ARG_STRING, &host, 'h',
        "the IP address of the coordinator",
        "IP"},
    {"port", 'p', POPT_ARG_SHORT, &port, 'p',
        "the port number of the coordinator",
        "port"},
    POPT_TABLEEND
};

} // extern "C"

static void
writer_thread();
static void
reader_thread();

int
main(int argc, const char* argv[])
{
    poptContext poptcon;
    poptcon = poptGetContext(NULL, argc, (const char**) argv, popts, POPT_CONTEXT_POSIXMEHARDER);
    e::guard g = e::makeguard(poptFreeContext, poptcon);
    g.use_variable();
    int rc;

    while ((rc = poptGetNextOpt(poptcon)) != -1)
    {
        switch (rc)
        {
            case 'w':
                if (window < 0)
                {
                    std::cerr << "window-size must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 'r':
                if (repetitions < 0)
                {
                    std::cerr << "repetitions must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 't':
                if (threads < 0)
                {
                    std::cerr << "threads must be >= 0" << std::endl;
                    return EXIT_FAILURE;
                }

                break;
            case 's':
                break;
            case 'h':
                break;
            case 'p':
                break;
            case POPT_ERROR_NOARG:
            case POPT_ERROR_BADOPT:
            case POPT_ERROR_BADNUMBER:
            case POPT_ERROR_OVERFLOW:
                std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl;
                return EXIT_FAILURE;
            case POPT_ERROR_OPTSTOODEEP:
            case POPT_ERROR_BADQUOTE:
            case POPT_ERROR_ERRNO:
            default:
                std::cerr << "logic error in argument parsing" << std::endl;
                return EXIT_FAILURE;
        }
    }

    barrier.reset(new po6::threads::barrier(threads + 1));
    po6::threads::thread writer(writer_thread);
    writer.start();
    std::vector<std::tr1::shared_ptr<po6::threads::thread> > readers;

    for (int64_t i = 0; i < threads; ++i)
    {
        std::tr1::shared_ptr<po6::threads::thread> tptr(new po6::threads::thread(reader_thread));
        readers.push_back(tptr);
        tptr->start();
    }

    writer.join();

    bool success = __sync_bool_compare_and_swap(&done, 0, 1);
    assert(success);

    for (int64_t i = 0; i < threads; ++i)
    {
        readers[i]->join();
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;
    std::cout << "Failed puts:" << std::endl;

    for (result_iter_t o = failed_puts.begin(); o != failed_puts.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "Failed loops:" << std::endl;

    for (result_iter_t o = failed_loops.begin(); o != failed_loops.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "Normal ops:" << std::endl;

    for (result_iter_t o = ops.begin(); o != ops.end(); ++o)
    {
        std::cout << o->first << "\t" << o->second << std::endl;
    }

    std::cout << std::endl << "failed writes:  " << failed_writes << std::endl
              << "Inconsistencies:  " << inconsistencies << std::endl;
    return EXIT_SUCCESS;
}

static void
writer_thread()
{
    std::map<hyperclient_returncode, uint64_t> lfailed_puts;
    std::map<hyperclient_returncode, uint64_t> lfailed_loops;
    std::map<hyperclient_returncode, uint64_t> lops;
    uint64_t lfailed_writes = 0;
    hyperclient cl(host, port);
    bool fail = false;

    for (int64_t i = 0; i < window; ++i)
    {
        int64_t key = htobe64(i);
        int64_t did;
        hyperclient_returncode dstatus;

        const char* keystr = reinterpret_cast<const char*>(&key);
        did = cl.del(space, keystr, sizeof(key), &dstatus);

        if (did < 0)
        {
            std::cerr << "delete failed with " << dstatus << std::endl;
            fail = true;
            break;
        }

        int64_t lid;
        hyperclient_returncode lstatus;
        lid = cl.loop(-1, &lstatus);

        if (lid < 0)
        {
            std::cerr << "loop failed with " << lstatus << std::endl;
            fail = true;
            break;
        }

        assert(lid == did);

        if (dstatus != HYPERCLIENT_SUCCESS && dstatus != HYPERCLIENT_NOTFOUND)
        {
            std::cerr << "delete returned " << dstatus << std::endl;
            fail = true;
            break;
        }
    }

    barrier->wait();

    if (fail)
    {
        std::cerr << "the above errors are fatal" << std::endl;
        return;
    }

    std::cout << "starting the consistency stress test" << std::endl;

    for (int64_t r = 0; r < repetitions; ++r)
    {
        for (int64_t i = 0; i < window; ++i)
        {
            uint64_t count = 0;

            for (count = 0; count < 65536; ++count)
            {
                int64_t key = htobe64(i);
                int64_t val = htobe64(r);
                int64_t pid;
                hyperclient_attribute attr;
                hyperclient_returncode pstatus;

                const char* keystr = reinterpret_cast<const char*>(&key);
                attr.attr = "repetition";
                attr.value = reinterpret_cast<const char*>(&val);
                attr.value_sz = sizeof(val);
                pid = cl.put(space, keystr, sizeof(key), &attr, 1, &pstatus);

                if (pid < 0)
                {
                    ++lfailed_puts[pstatus];
                    continue;
                }

                int64_t lid;
                hyperclient_returncode lstatus;
                lid = cl.loop(-1, &lstatus);

                if (lid < 0)
                {
                    ++lfailed_loops[lstatus];
                    continue;
                }

                assert(lid == pid);
                ++lops[pstatus];
                break;
            }

            if (count == 65536)
            {
                ++lfailed_writes;
            }
        }

        std::cout << "done " << r << "/" << repetitions << std::endl;
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;

    for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o)
    {
        failed_puts[o->first] += o->second;
    }

    for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o)
    {
        failed_loops[o->first] += o->second;
    }

    for (result_iter_t o = lops.begin(); o != lops.end(); ++o)
    {
        ops[o->first] += o->second;
    }

    failed_writes = lfailed_writes;
}

static void
reader_thread()
{
    std::map<hyperclient_returncode, uint64_t> lfailed_puts;
    std::map<hyperclient_returncode, uint64_t> lfailed_loops;
    std::map<hyperclient_returncode, uint64_t> lops;
    uint64_t linconsistencies = 0;
    hyperclient cl(host, port);
    barrier->wait();

    while (!__sync_bool_compare_and_swap(&done, 1, 1))
    {
        int64_t oldval = 0;

        for (int64_t i = window - 1; i >= 0; --i)
        {
            while (true)
            {
                int64_t key = htobe64(i);
                int64_t gid;
                hyperclient_attribute* attrs = NULL;
                size_t attrs_sz = 0;
                hyperclient_returncode gstatus;

                const char* keystr = reinterpret_cast<const char*>(&key);
                gid = cl.get(space, keystr, sizeof(key), &gstatus, &attrs, &attrs_sz);

                if (gid < 0)
                {
                    ++lfailed_puts[gstatus];
                    continue;
                }

                int64_t lid;
                hyperclient_returncode lstatus;
                lid = cl.loop(-1, &lstatus);

                if (lid < 0)
                {
                    ++lfailed_loops[lstatus];
                    continue;
                }

                assert(lid == gid);
                ++lops[gstatus];

                if (gstatus == HYPERCLIENT_SUCCESS)
                {
                    assert(attrs_sz == 1);
                    assert(strcmp(attrs[0].attr, "repetition") == 0);
                    int64_t val = 0;
                    memmove(&val, attrs[0].value, attrs[0].value_sz);
                    val = be64toh(val);

                    if (val < oldval)
                    {
                        ++inconsistencies;
                    }

                    oldval = val;
                }

                if (attrs)
                {
                    hyperclient_destroy_attrs(attrs, attrs_sz);
                }

                break;
            }
        }
    }

    po6::threads::mutex::hold hold(&results_lock);
    typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t;

    for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o)
    {
        failed_puts[o->first] += o->second;
    }

    for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o)
    {
        failed_loops[o->first] += o->second;
    }

    for (result_iter_t o = lops.begin(); o != lops.end(); ++o)
    {
        ops[o->first] += o->second;
    }

    inconsistencies += linconsistencies;
}
<|endoftext|>


<commit_before>//
// @Yue Wang
//
// Exercise 11.18:
// Write the type of map_it from the loop on page 430 without using auto or decltype.
//      std::map<std::string, size_t>::const_iterator
//

int main()
{
    return 0;
}
<commit_msg>Delete ex11_18.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pipe_decl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:30:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _OSL_PIPE_DECL_HXX_
#define _OSL_PIPE_DECL_HXX_

#ifndef _OSL_PIPE_H_
#include <osl/pipe.h>
#endif

#ifndef _OSL_SECURITY_HXX_
#   include <osl/security.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

namespace osl {

class StreamPipe;

/** Represents a pipe.
*/
class Pipe
{
protected:
    oslPipe m_handle;

public:

    /** Does not create a pipe. Use assignment operator to
        make this a useable pipe.
    */
    inline Pipe();

    /** Creates an insecure pipe that is accessible for all users.
        @param strName
        @param Options
    */
    inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options);

    /** Creates a secure pipe that access depends on the umask settings.
        @param strName
        @param Options
        @param Security
    */
    inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity);

    /** Copy constructor.
    */
    inline Pipe(const Pipe& pipe);

    /** Constructs a Pipe reference without acquiring the handle
    */
    inline Pipe( oslPipe pipe, __sal_NoAcquire noacquire );

    /** Creates pipe as wrapper around the underlying oslPipe.
        @param Pipe
    */
    inline Pipe(oslPipe Pipe);

    /** Destructor. Destroys the underlying oslPipe.
    */
    inline ~Pipe();

    inline sal_Bool SAL_CALL is() const;

    /** Creates an insecure pipe that is accessible for all users
        with the given attributes.
        If the pipe was already created, the old one will be discarded.
        @param strName
        @param Options
        @param Security
        @return True if socket was successfully created.
    */
    inline sal_Bool create( const ::rtl::OUString & strName,
                            oslPipeOptions Options, const Security &rSec );

    /** Creates a secure that access rights depend on the umask settings
        with the given attributes.

        If socket was already created, the old one will be discarded.
        @param strName
        @param Options
        @return True if socket was successfully created.
    */
    inline sal_Bool create( const ::rtl::OUString & strName, oslPipeOptions Options = osl_Pipe_OPEN );

    /** releases the underlying handle
     */
    inline void SAL_CALL clear();

    /** Assignment operator. If pipe was already created, the old one will
        be discarded.
    */
    inline Pipe& SAL_CALL operator= (const Pipe& pipe);

    /** Assignment operator. If pipe was already created, the old one will
        be discarded.
    */
    inline Pipe& SAL_CALL operator= (const oslPipe pipe );

    /** Checks if the pipe is valid.
        @return True if the object represents a valid pipe.
    */
    inline sal_Bool SAL_CALL isValid() const;

    inline sal_Bool SAL_CALL operator==( const Pipe& rPipe ) const;

    /** Closes the pipe.
    */
    inline void SAL_CALL close();

    /** Accept connection on an existing pipe
    */
    inline oslPipeError SAL_CALL accept(StreamPipe& Connection);

    /** Delivers a constant decribing the last error for the pipe system.
        @return ENONE if no error occured, invalid_PipeError if
        an unknown (unmapped) error occured, otherwise an enum describing the
        error.
    */
    inline oslPipeError SAL_CALL getError() const;

    inline oslPipe SAL_CALL getHandle() const;
};

/** A pipe to send or receive a stream of data.
*/
class StreamPipe : public Pipe
{
public:

    /** Creates an unattached pipe. You must attach the pipe to an oslPipe
        e.g. by using the operator=(oslPipe), before you can use the stream-
        functionality of the object.
    */
    inline StreamPipe();

    /** Creates pipe as wrapper around the underlying oslPipe.
        @param Pipe
    */
    inline StreamPipe(oslPipe Pipe);

    /** Copy constructor.
        @param Pipe
    */
    inline StreamPipe(const StreamPipe& Pipe);

    /** Creates a pipe.
        @param strName
        @param Options
    */
    inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN);

    /** Creates a pipe.
        @param strName
        @param Options
        @param rSec
    */
    inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec );

    /** Constructs a Pipe reference without acquiring the handle
    */
    inline StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire );

    /** Attaches the oslPipe to this object. If the object
        already was attached to an oslPipe, the old one will
        be closed and destroyed.
        @param Pipe.
    */
    inline StreamPipe & SAL_CALL operator=(oslPipe Pipe);

    /** Assignment operator
    */
    inline StreamPipe& SAL_CALL operator=(const Pipe& pipe);

    /** Tries to receives BytesToRead data from the connected pipe,

        @param pBuffer [out] Points to a buffer that will be filled with the received
        data.
        @param BytesToRead [in] The number of bytes to read. pBuffer must have at least
        this size.
        @return the number of received bytes.
    */
    inline sal_Int32 SAL_CALL recv(void* pBuffer, sal_Int32 BytesToRead) const;

    /** Tries to sends BytesToSend data from the connected pipe.

        @param pBuffer [in] Points to a buffer that contains the send-data.
        @param BytesToSend [in] The number of bytes to send. pBuffer must have at least
        this size.
        @return the number of transfered bytes.
    */
    inline sal_Int32 SAL_CALL send(const void* pBuffer, sal_Int32 BytesToSend) const;

    /** Retrieves n bytes from the stream and copies them into pBuffer.
        The method avoids incomplete reads due to packet boundaries.
        @param pBuffer receives the read data.
        @param n the number of bytes to read. pBuffer must be large enough
        to hold the n bytes!
        @return the number of read bytes. The number will only be smaller than
        n if an exceptional condition (e.g. connection closed) occurs.
    */
    inline sal_Int32 SAL_CALL read(void* pBuffer, sal_Int32 n) const;

    /** Writes n bytes from pBuffer to the stream. The method avoids
        incomplete writes due to packet boundaries.
        @param pBuffer contains the data to be written.
        @param n the number of bytes to write.
        @return the number of written bytes. The number will only be smaller than
        n if an exceptional condition (e.g. connection closed) occurs.
    */
    sal_Int32 SAL_CALL write(const void* pBuffer, sal_Int32 n) const;
};

}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.378); FILE MERGED 2008/04/01 15:25:00 thb 1.3.378.3: #i85898# Stripping all external header guards 2008/04/01 12:34:02 thb 1.3.378.2: #i85898# Stripping all external header guards 2008/03/31 13:23:36 rt 1.3.378.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: pipe_decl.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _OSL_PIPE_DECL_HXX_
#define _OSL_PIPE_DECL_HXX_

#include <osl/pipe.h>
#   include <osl/security.hxx>
#include <rtl/ustring.hxx>

namespace osl {

class StreamPipe;

/** Represents a pipe.
*/
class Pipe
{
protected:
    oslPipe m_handle;

public:

    /** Does not create a pipe. Use assignment operator to
        make this a useable pipe.
    */
    inline Pipe();

    /** Creates an insecure pipe that is accessible for all users.
        @param strName
        @param Options
    */
    inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options);

    /** Creates a secure pipe that access depends on the umask settings.
        @param strName
        @param Options
        @param Security
    */
    inline Pipe(const ::rtl::OUString& strName, oslPipeOptions Options,const Security & rSecurity);

    /** Copy constructor.
    */
    inline Pipe(const Pipe& pipe);

    /** Constructs a Pipe reference without acquiring the handle
    */
    inline Pipe( oslPipe pipe, __sal_NoAcquire noacquire );

    /** Creates pipe as wrapper around the underlying oslPipe.
        @param Pipe
    */
    inline Pipe(oslPipe Pipe);

    /** Destructor. Destroys the underlying oslPipe.
    */
    inline ~Pipe();

    inline sal_Bool SAL_CALL is() const;

    /** Creates an insecure pipe that is accessible for all users
        with the given attributes.
        If the pipe was already created, the old one will be discarded.
        @param strName
        @param Options
        @param Security
        @return True if socket was successfully created.
    */
    inline sal_Bool create( const ::rtl::OUString & strName,
                            oslPipeOptions Options, const Security &rSec );

    /** Creates a secure that access rights depend on the umask settings
        with the given attributes.

        If socket was already created, the old one will be discarded.
        @param strName
        @param Options
        @return True if socket was successfully created.
    */
    inline sal_Bool create( const ::rtl::OUString & strName, oslPipeOptions Options = osl_Pipe_OPEN );

    /** releases the underlying handle
     */
    inline void SAL_CALL clear();

    /** Assignment operator. If pipe was already created, the old one will
        be discarded.
    */
    inline Pipe& SAL_CALL operator= (const Pipe& pipe);

    /** Assignment operator. If pipe was already created, the old one will
        be discarded.
    */
    inline Pipe& SAL_CALL operator= (const oslPipe pipe );

    /** Checks if the pipe is valid.
        @return True if the object represents a valid pipe.
    */
    inline sal_Bool SAL_CALL isValid() const;

    inline sal_Bool SAL_CALL operator==( const Pipe& rPipe ) const;

    /** Closes the pipe.
    */
    inline void SAL_CALL close();

    /** Accept connection on an existing pipe
    */
    inline oslPipeError SAL_CALL accept(StreamPipe& Connection);

    /** Delivers a constant decribing the last error for the pipe system.
        @return ENONE if no error occured, invalid_PipeError if
        an unknown (unmapped) error occured, otherwise an enum describing the
        error.
    */
    inline oslPipeError SAL_CALL getError() const;

    inline oslPipe SAL_CALL getHandle() const;
};

/** A pipe to send or receive a stream of data.
*/
class StreamPipe : public Pipe
{
public:

    /** Creates an unattached pipe. You must attach the pipe to an oslPipe
        e.g. by using the operator=(oslPipe), before you can use the stream-
        functionality of the object.
    */
    inline StreamPipe();

    /** Creates pipe as wrapper around the underlying oslPipe.
        @param Pipe
    */
    inline StreamPipe(oslPipe Pipe);

    /** Copy constructor.
        @param Pipe
    */
    inline StreamPipe(const StreamPipe& Pipe);

    /** Creates a pipe.
        @param strName
        @param Options
    */
    inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options = osl_Pipe_OPEN);

    /** Creates a pipe.
        @param strName
        @param Options
        @param rSec
    */
    inline StreamPipe(const ::rtl::OUString& strName, oslPipeOptions Options, const Security &rSec );

    /** Constructs a Pipe reference without acquiring the handle
    */
    inline StreamPipe( oslPipe pipe, __sal_NoAcquire noacquire );

    /** Attaches the oslPipe to this object. If the object
        already was attached to an oslPipe, the old one will
        be closed and destroyed.
        @param Pipe.
    */
    inline StreamPipe & SAL_CALL operator=(oslPipe Pipe);

    /** Assignment operator
    */
    inline StreamPipe& SAL_CALL operator=(const Pipe& pipe);

    /** Tries to receives BytesToRead data from the connected pipe,

        @param pBuffer [out] Points to a buffer that will be filled with the received
        data.
        @param BytesToRead [in] The number of bytes to read. pBuffer must have at least
        this size.
        @return the number of received bytes.
    */
    inline sal_Int32 SAL_CALL recv(void* pBuffer, sal_Int32 BytesToRead) const;

    /** Tries to sends BytesToSend data from the connected pipe.

        @param pBuffer [in] Points to a buffer that contains the send-data.
        @param BytesToSend [in] The number of bytes to send. pBuffer must have at least
        this size.
        @return the number of transfered bytes.
    */
    inline sal_Int32 SAL_CALL send(const void* pBuffer, sal_Int32 BytesToSend) const;

    /** Retrieves n bytes from the stream and copies them into pBuffer.
        The method avoids incomplete reads due to packet boundaries.
        @param pBuffer receives the read data.
        @param n the number of bytes to read. pBuffer must be large enough
        to hold the n bytes!
        @return the number of read bytes. The number will only be smaller than
        n if an exceptional condition (e.g. connection closed) occurs.
    */
    inline sal_Int32 SAL_CALL read(void* pBuffer, sal_Int32 n) const;

    /** Writes n bytes from pBuffer to the stream. The method avoids
        incomplete writes due to packet boundaries.
        @param pBuffer contains the data to be written.
        @param n the number of bytes to write.
        @return the number of written bytes. The number will only be smaller than
        n if an exceptional condition (e.g. connection closed) occurs.
    */
    sal_Int32 SAL_CALL write(const void* pBuffer, sal_Int32 n) const;
};

}
#endif
<|endoftext|>


<commit_before><commit_msg>Configuration: unbreak behavior of setArray: comma only between elements, no enclosing double quotes<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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 the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_LINUX_LINUX_HH__
#define __ARCH_X86_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class X86Linux64 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint64_t st_ino;
        uint64_t st_nlink;
        uint32_t st_mode;
        uint32_t st_uid;
        uint32_t st_gid;
        uint32_t __pad0;
        uint64_t st_rdev;
        int64_t st_size;
        int64_t st_blksize;
        int64_t st_blocks;
        uint64_t st_atimeX;
        uint64_t st_atime_nsec;
        uint64_t st_mtimeX;
        uint64_t st_mtime_nsec;
        uint64_t st_ctimeX;
        uint64_t st_ctime_nsec;
        int64_t unused0[3];
    } tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY       = 00000000;     //!< O_RDONLY
    static const int TGT_O_WRONLY       = 00000001;     //!< O_WRONLY
    static const int TGT_O_RDWR         = 00000002;     //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 00004000;     //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 00002000;     //!< O_APPEND
    static const int TGT_O_CREAT        = 00000100;     //!< O_CREAT
    static const int TGT_O_TRUNC        = 00001000;     //!< O_TRUNC
    static const int TGT_O_EXCL         = 00000200;     //!< O_EXCL
    static const int TGT_O_NOCTTY       = 00000400;     //!< O_NOCTTY
    static const int TGT_O_SYNC         = 00010000;     //!< O_SYNC
//    static const int TGT_O_DRD        = 0x00010000;   //!< O_DRD
//    static const int TGT_O_DIRECTIO   = 0x00020000; //!< O_DIRECTIO
//    static const int TGT_O_CACHE      = 0x00002000;   //!< O_CACHE
//    static const int TGT_O_DSYNC      = 0x00008000;   //!< O_DSYNC
//    static const int TGT_O_RSYNC      = 0x00040000;   //!< O_RSYNC

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    typedef struct {
        uint64_t iov_base; // void *
        uint64_t iov_len;  // size_t
    } tgt_iovec;

    typedef struct {
        int64_t  uptime;    /* Seconds since boot */
        uint64_t loads[3];  /* 1, 5, and 15 minute load averages */
        uint64_t totalram;  /* Total usable main memory size */
        uint64_t freeram;   /* Available memory size */
        uint64_t sharedram; /* Amount of shared memory */
        uint64_t bufferram; /* Memory used by buffers */
        uint64_t totalswap; /* Total swap space size */
        uint64_t freeswap;  /* swap space still available */
        uint16_t procs;     /* Number of current processes */
        uint64_t totalhigh; /* Total high memory size */
        uint64_t freehigh;  /* Available high memory size */
        uint64_t mem_unit;  /* Memory unit size in bytes */
   } tgt_sysinfo;

};

class X86Linux32 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint8_t __pad0[4];
        uint32_t __st_ino;
        uint32_t st_mode;
        uint32_t st_nlink;
        uint32_t st_uid;
        uint32_t st_gid;
        uint64_t st_rdev;
        uint8_t __pad3[4];
        int64_t st_size;
        uint32_t st_blksize;
        uint64_t st_blocks;
        uint32_t st_atimeX;
        uint32_t st_atime_nsec;
        uint32_t st_mtimeX;
        uint32_t st_mtime_nsec;
        uint32_t st_ctimeX;
        uint32_t st_ctime_nsec;
        uint64_t st_ino;
    } __attribute__((__packed__)) tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY       = 00000000;     //!< O_RDONLY
    static const int TGT_O_WRONLY       = 00000001;     //!< O_WRONLY
    static const int TGT_O_RDWR         = 00000002;     //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 00004000;     //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 00002000;     //!< O_APPEND
    static const int TGT_O_CREAT        = 00000100;     //!< O_CREAT
    static const int TGT_O_TRUNC        = 00001000;     //!< O_TRUNC
    static const int TGT_O_EXCL         = 00000200;     //!< O_EXCL
    static const int TGT_O_NOCTTY       = 00000400;     //!< O_NOCTTY
    static const int TGT_O_SYNC         = 00010000;     //!< O_SYNC
    static const int TGT_O_ASYNC        = 00020000;
    static const int TGT_O_DIRECT       = 00040000;     //!< O_DIRECTIO
    static const int TGT_O_LARGEFILE    = 00100000;
    static const int TGT_O_DIRECTORY    = 00200000;
    static const int TGT_O_NOFOLLOW     = 00400000;
    static const int TGT_O_NOATIME      = 01000000;
    static const int TGT_O_CLOEXEC      = 02000000;

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    typedef struct {
       int32_t  uptime;    /* Seconds since boot */
       uint32_t loads[3];  /* 1, 5, and 15 minute load averages */
       uint32_t totalram;  /* Total usable main memory size */
       uint32_t freeram;   /* Available memory size */
       uint32_t sharedram; /* Amount of shared memory */
       uint32_t bufferram; /* Memory used by buffers */
       uint32_t totalswap; /* Total swap space size */
       uint32_t freeswap;  /* swap space still available */
       uint16_t procs;     /* Number of current processes */
       uint32_t totalhigh; /* Total high memory size */
       uint32_t freehigh;  /* Available high memory size */
       uint32_t mem_unit;  /* Memory unit size in bytes */
    } tgt_sysinfo;

    static bool mmapGrowsDown() { return true; }
};

#endif
<commit_msg>X86: Fix up the open system call's flags.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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 the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_LINUX_LINUX_HH__
#define __ARCH_X86_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class X86Linux64 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint64_t st_ino;
        uint64_t st_nlink;
        uint32_t st_mode;
        uint32_t st_uid;
        uint32_t st_gid;
        uint32_t __pad0;
        uint64_t st_rdev;
        int64_t st_size;
        int64_t st_blksize;
        int64_t st_blocks;
        uint64_t st_atimeX;
        uint64_t st_atime_nsec;
        uint64_t st_mtimeX;
        uint64_t st_mtime_nsec;
        uint64_t st_ctimeX;
        uint64_t st_ctime_nsec;
        int64_t unused0[3];
    } tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY       = 00000000;     //!< O_RDONLY
    static const int TGT_O_WRONLY       = 00000001;     //!< O_WRONLY
    static const int TGT_O_RDWR         = 00000002;     //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 00004000;     //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 00002000;     //!< O_APPEND
    static const int TGT_O_CREAT        = 00000100;     //!< O_CREAT
    static const int TGT_O_TRUNC        = 00001000;     //!< O_TRUNC
    static const int TGT_O_EXCL         = 00000200;     //!< O_EXCL
    static const int TGT_O_NOCTTY       = 00000400;     //!< O_NOCTTY
    static const int TGT_O_SYNC         = 00010000;     //!< O_SYNC
    static const int TGT_O_ASYNC        = 00020000;
    static const int TGT_O_DIRECT       = 00040000;     //!< O_DIRECTIO
    static const int TGT_O_LARGEFILE    = 00100000;
    static const int TGT_O_DIRECTORY    = 00200000;
    static const int TGT_O_NOFOLLOW     = 00400000;
    static const int TGT_O_NOATIME      = 01000000;
    static const int TGT_O_CLOEXEC      = 02000000;

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    typedef struct {
        uint64_t iov_base; // void *
        uint64_t iov_len;  // size_t
    } tgt_iovec;

    typedef struct {
        int64_t  uptime;    /* Seconds since boot */
        uint64_t loads[3];  /* 1, 5, and 15 minute load averages */
        uint64_t totalram;  /* Total usable main memory size */
        uint64_t freeram;   /* Available memory size */
        uint64_t sharedram; /* Amount of shared memory */
        uint64_t bufferram; /* Memory used by buffers */
        uint64_t totalswap; /* Total swap space size */
        uint64_t freeswap;  /* swap space still available */
        uint16_t procs;     /* Number of current processes */
        uint64_t totalhigh; /* Total high memory size */
        uint64_t freehigh;  /* Available high memory size */
        uint64_t mem_unit;  /* Memory unit size in bytes */
   } tgt_sysinfo;

};

class X86Linux32 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint8_t __pad0[4];
        uint32_t __st_ino;
        uint32_t st_mode;
        uint32_t st_nlink;
        uint32_t st_uid;
        uint32_t st_gid;
        uint64_t st_rdev;
        uint8_t __pad3[4];
        int64_t st_size;
        uint32_t st_blksize;
        uint64_t st_blocks;
        uint32_t st_atimeX;
        uint32_t st_atime_nsec;
        uint32_t st_mtimeX;
        uint32_t st_mtime_nsec;
        uint32_t st_ctimeX;
        uint32_t st_ctime_nsec;
        uint64_t st_ino;
    } __attribute__((__packed__)) tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY       = 00000000;     //!< O_RDONLY
    static const int TGT_O_WRONLY       = 00000001;     //!< O_WRONLY
    static const int TGT_O_RDWR         = 00000002;     //!< O_RDWR
    static const int TGT_O_NONBLOCK     = 00004000;     //!< O_NONBLOCK
    static const int TGT_O_APPEND       = 00002000;     //!< O_APPEND
    static const int TGT_O_CREAT        = 00000100;     //!< O_CREAT
    static const int TGT_O_TRUNC        = 00001000;     //!< O_TRUNC
    static const int TGT_O_EXCL         = 00000200;     //!< O_EXCL
    static const int TGT_O_NOCTTY       = 00000400;     //!< O_NOCTTY
    static const int TGT_O_SYNC         = 00010000;     //!< O_SYNC
    static const int TGT_O_ASYNC        = 00020000;
    static const int TGT_O_DIRECT       = 00040000;     //!< O_DIRECTIO
    static const int TGT_O_LARGEFILE    = 00100000;
    static const int TGT_O_DIRECTORY    = 00200000;
    static const int TGT_O_NOFOLLOW     = 00400000;
    static const int TGT_O_NOATIME      = 01000000;
    static const int TGT_O_CLOEXEC      = 02000000;

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;
    static const unsigned TGT_MAP_FIXED     = 0x10;

    typedef struct {
       int32_t  uptime;    /* Seconds since boot */
       uint32_t loads[3];  /* 1, 5, and 15 minute load averages */
       uint32_t totalram;  /* Total usable main memory size */
       uint32_t freeram;   /* Available memory size */
       uint32_t sharedram; /* Amount of shared memory */
       uint32_t bufferram; /* Memory used by buffers */
       uint32_t totalswap; /* Total swap space size */
       uint32_t freeswap;  /* swap space still available */
       uint16_t procs;     /* Number of current processes */
       uint32_t totalhigh; /* Total high memory size */
       uint32_t freehigh;  /* Available high memory size */
       uint32_t mem_unit;  /* Memory unit size in bytes */
    } tgt_sysinfo;

    static bool mmapGrowsDown() { return true; }
};

#endif
<|endoftext|>


<commit_before><commit_msg>Fix compilation error without C++11<commit_after><|endoftext|>


<commit_before>#include "archivator.h"
#include <vector>
#include <algorithm>
#include <fstream>

void archivator::compress(const std::string &dir, const std::string &destination)
{
	archive *a;
	archive_entry *entry;
	ssize_t r;

	std::vector<fs::path> files;
	fs::path dir_path;
	try {
		dir_path = fs::canonical(fs::path(dir));
		if (fs::is_directory(dir_path)) {
			for (auto i = fs::recursive_directory_iterator(dir_path); i != fs::recursive_directory_iterator(); ++i) {
				fs::path file = *i;
				if (fs::is_regular_file(file)) {
					// find out where the two paths diverge
					fs::path::const_iterator itr_dir = dir_path.begin();
					fs::path::const_iterator itr_file = file.begin();
					while (*itr_dir == *itr_file && itr_dir != dir_path.end()) {
						++itr_dir;
						++itr_file;
					}
					// result is what is left in second path (it's relative path to the first one)
					fs::path result;
					while (itr_file != file.end()) {
						result /= *itr_file;
						itr_file++;
					}
					files.push_back(result);
				}
			}
		}
	} catch (fs::filesystem_error &e) {
		throw archive_exception(e.what());
	}

	a = archive_write_new();
	archive_write_set_format_zip(a);
	r = archive_write_open_filename(a, destination.c_str());
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open destination archive.");
	}

	for (auto &file : files) {
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, (fs::path(destination).stem() / file).string().c_str());
		archive_entry_set_size(entry, fs::file_size(dir_path / file));
		archive_entry_set_mtime(entry, fs::last_write_time(dir_path / file), 0);
		archive_entry_set_filetype(entry, AE_IFREG);
		archive_entry_set_perm(entry, 0644);

		r = archive_write_header(a, entry);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		std::ifstream ifs((dir_path / file).string(), std::ios::binary);
		if (ifs.is_open()) {
			// read data by small blocks to avoid memory overfill on possibly large files
			char buff[4096];

			while (!ifs.eof()) {
				ifs.read(buff, sizeof(buff));

				if (ifs.gcount() <= 0) {
					throw archive_exception("Error reading input file");
				}

				r = archive_write_data(a, buff, (size_t) ifs.gcount());
				if (r < ARCHIVE_OK) {
					throw archive_exception(archive_error_string(a));
				}
			}
		}
		archive_entry_free(entry);
	}
	archive_write_close(a);
	archive_write_free(a);
}

void archivator::decompress(const std::string &filename, const std::string &destination)
{
	archive *a;
	archive *ext;
	archive_entry *entry;
	int flags;
	int r;

	// Select which attributes we want to restore.
	flags = ARCHIVE_EXTRACT_TIME;
	flags |= ARCHIVE_EXTRACT_FFLAGS;
	// Don't allow ".." in any path within archive
	flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;

	a = archive_read_new();
	archive_read_support_format_all(a);
	archive_read_support_compression_all(a);
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
	archive_write_disk_set_standard_lookup(ext);

	r = archive_read_open_filename(a, filename.c_str(), 10240);
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open source archive.");
	}

	while (true) {
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		const char* current_file = archive_entry_pathname(entry);
		const std::string full_path = (fs::path(destination) / current_file).string();
		archive_entry_set_pathname(entry, full_path.c_str());

		r = archive_write_header(ext, entry);

		if (archive_entry_size(entry) > 0) {
			copy_data(a, ext);
		}

		r = archive_write_finish_entry(ext);

		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ext));
		}
	}

	archive_read_close(a);
	archive_read_free(a);
	archive_write_close(ext);
	archive_write_free(ext);
}

void archivator::copy_data(archive *ar, archive *aw)
{
	int r;
	const void *buff;
	size_t size;
	int64_t offset;

	while (true) {
		r = archive_read_data_block(ar, &buff, &size, &offset);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ar));
		}
		r = archive_write_data_block(aw, buff, size, offset);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(aw));
		}
	}
}
<commit_msg>use long instead of ssize_t and int in archivator<commit_after>#include "archivator.h"
#include <vector>
#include <algorithm>
#include <fstream>

void archivator::compress(const std::string &dir, const std::string &destination)
{
	archive *a;
	archive_entry *entry;
	long r;

	std::vector<fs::path> files;
	fs::path dir_path;
	try {
		dir_path = fs::canonical(fs::path(dir));
		if (fs::is_directory(dir_path)) {
			for (auto i = fs::recursive_directory_iterator(dir_path); i != fs::recursive_directory_iterator(); ++i) {
				fs::path file = *i;
				if (fs::is_regular_file(file)) {
					// find out where the two paths diverge
					fs::path::const_iterator itr_dir = dir_path.begin();
					fs::path::const_iterator itr_file = file.begin();
					while (*itr_dir == *itr_file && itr_dir != dir_path.end()) {
						++itr_dir;
						++itr_file;
					}
					// result is what is left in second path (it's relative path to the first one)
					fs::path result;
					while (itr_file != file.end()) {
						result /= *itr_file;
						itr_file++;
					}
					files.push_back(result);
				}
			}
		}
	} catch (fs::filesystem_error &e) {
		throw archive_exception(e.what());
	}

	a = archive_write_new();
	archive_write_set_format_zip(a);
	r = archive_write_open_filename(a, destination.c_str());
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open destination archive.");
	}

	for (auto &file : files) {
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, (fs::path(destination).stem() / file).string().c_str());
		archive_entry_set_size(entry, fs::file_size(dir_path / file));
		archive_entry_set_mtime(entry, fs::last_write_time(dir_path / file), 0);
		archive_entry_set_filetype(entry, AE_IFREG);
		archive_entry_set_perm(entry, 0644);

		r = archive_write_header(a, entry);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		std::ifstream ifs((dir_path / file).string(), std::ios::binary);
		if (ifs.is_open()) {
			// read data by small blocks to avoid memory overfill on possibly large files
			char buff[4096];

			while (!ifs.eof()) {
				ifs.read(buff, sizeof(buff));

				if (ifs.gcount() <= 0) {
					throw archive_exception("Error reading input file");
				}

				r = archive_write_data(a, buff, (size_t) ifs.gcount());
				if (r < ARCHIVE_OK) {
					throw archive_exception(archive_error_string(a));
				}
			}
		}
		archive_entry_free(entry);
	}
	archive_write_close(a);
	archive_write_free(a);
}

void archivator::decompress(const std::string &filename, const std::string &destination)
{
	archive *a;
	archive *ext;
	archive_entry *entry;
	int flags;
	long r;

	// Select which attributes we want to restore.
	flags = ARCHIVE_EXTRACT_TIME;
	flags |= ARCHIVE_EXTRACT_FFLAGS;
	// Don't allow ".." in any path within archive
	flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;

	a = archive_read_new();
	archive_read_support_format_all(a);
	archive_read_support_compression_all(a);
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
	archive_write_disk_set_standard_lookup(ext);

	r = archive_read_open_filename(a, filename.c_str(), 10240);
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open source archive.");
	}

	while (true) {
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		const char* current_file = archive_entry_pathname(entry);
		const std::string full_path = (fs::path(destination) / current_file).string();
		archive_entry_set_pathname(entry, full_path.c_str());

		r = archive_write_header(ext, entry);

		if (archive_entry_size(entry) > 0) {
			copy_data(a, ext);
		}

		r = archive_write_finish_entry(ext);

		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ext));
		}
	}

	archive_read_close(a);
	archive_read_free(a);
	archive_write_close(ext);
	archive_write_free(ext);
}

void archivator::copy_data(archive *ar, archive *aw)
{
	int r;
	const void *buff;
	size_t size;
	int64_t offset;

	while (true) {
		r = archive_read_data_block(ar, &buff, &size, &offset);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ar));
		}
		r = archive_write_data_block(aw, buff, size, offset);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(aw));
		}
	}
}
<|endoftext|>


<commit_before>#include <exceptxx/NtstatusException.h>
#include <Windows.h>
#include <winternl.h>
#include <iostream>

using namespace std;

int main()
{
    try
    {
        auto myRtlConvertSidToUnicodeString = reinterpret_cast<decltype(::RtlConvertSidToUnicodeString)*>(::GetProcAddress(::GetModuleHandleW(L"ntdll"), "RtlConvertSidToUnicodeString"));

        NTSTATUS st = myRtlConvertSidToUnicodeString(nullptr, nullptr, false);
        CHECK_NTSTATUS(st) << "Failed to convert SID";
    }
    catch (const exception& ex)
    {
        cerr << ex.what() << endl << endl;
    }

    try
    {
        CHECK_NTSTATUS(STATUS_INVALID_HANDLE);
    }
    catch (const exception& ex)
    {
        cerr << ex.what() << endl << endl;
    }

    return 0;
}
<commit_msg>Fixed incorrect letter case in included header from NsStatus samples<commit_after>#include <exceptxx/NtStatusException.h>
#include <Windows.h>
#include <winternl.h>
#include <iostream>

using namespace std;

int main()
{
    try
    {
        auto myRtlConvertSidToUnicodeString = reinterpret_cast<decltype(::RtlConvertSidToUnicodeString)*>(::GetProcAddress(::GetModuleHandleW(L"ntdll"), "RtlConvertSidToUnicodeString"));

        NTSTATUS st = myRtlConvertSidToUnicodeString(nullptr, nullptr, false);
        CHECK_NTSTATUS(st) << "Failed to convert SID";
    }
    catch (const exception& ex)
    {
        cerr << ex.what() << endl << endl;
    }

    try
    {
        CHECK_NTSTATUS(STATUS_INVALID_HANDLE);
    }
    catch (const exception& ex)
    {
        cerr << ex.what() << endl << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>// $Id$

/*
Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
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 the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 <limits>
#include <sstream>
#include <fstream>

#include "packet_reply_info.hpp"
#include "random_utils.hpp"
#include "batchtrafficmanager.hpp"

BatchTrafficManager::BatchTrafficManager( const Configuration &config,
					  const vector<Network *> & net )
: TrafficManager(config, net), _last_id(-1), _last_pid(-1),
   _overall_min_batch_time(0), _overall_avg_batch_time(0),
   _overall_max_batch_time(0)
{

  _max_outstanding = config.GetInt ("max_outstanding_requests");

  _batch_size = config.GetInt( "batch_size" );
  _batch_count = config.GetInt( "batch_count" );

  _batch_time = new Stats( this, "batch_time", 1.0, 1000 );
  _stats["batch_time"] = _batch_time;

  string sent_packets_out_file = config.GetStr( "sent_packets_out" );
  if(sent_packets_out_file == "") {
    _sent_packets_out = NULL;
  } else {
    _sent_packets_out = new ofstream(sent_packets_out_file.c_str());
  }
}

BatchTrafficManager::~BatchTrafficManager( )
{
  delete _batch_time;
  if(_sent_packets_out) delete _sent_packets_out;
}

void BatchTrafficManager::_RetireFlit( Flit *f, int dest )
{
  _last_id = f->id;
  _last_pid = f->pid;
  TrafficManager::_RetireFlit(f, dest);
}

int BatchTrafficManager::_IssuePacket( int source, int cl )
{
  int result = 0;
  if(_use_read_write[cl]) { //read write packets
    //check queue for waiting replies.
    //check to make sure it is on time yet
    if(!_repliesPending[source].empty()) {
      if(_repliesPending[source].front()->time <= _qtime[source][cl]) {
	result = -1;
      }
    } else {
      if((_sent_packets[source] < _batch_size) &&
	 ((_max_outstanding <= 0) ||
	  (_requestsOutstanding[source] < _max_outstanding))) {

	//coin toss to determine request type.
	result = (RandomFloat() < 0.5) ? 2 : 1;

	_requestsOutstanding[source]++;
      }
    }
  } else { //normal
    if((_sent_packets[source] < _batch_size) &&
       ((_max_outstanding <= 0) ||
	(_requestsOutstanding[source] < _max_outstanding))) {
      result = _packet_size[cl];
      _requestsOutstanding[source]++;
    }
  }
  if(result != 0) {
    _sent_packets[source]++;
  }
  return result;
}

void BatchTrafficManager::_ClearStats( )
{
  TrafficManager::_ClearStats();
  _batch_time->Clear( );
}

bool BatchTrafficManager::_SingleSim( )
{
  int batch_index = 0;
  while(batch_index < _batch_count) {
    _sent_packets.assign(_nodes, 0);
    _last_id = -1;
    _last_pid = -1;
    _sim_state = running;
    int start_time = _time;
    bool batch_complete;
    do {
      _Step();
      batch_complete = true;
      for(int i = 0; i < _nodes; ++i) {
	if(_sent_packets[i] < _batch_size) {
	  batch_complete = false;
	  break;
	}
      }
      if(_sent_packets_out) {
	*_sent_packets_out << _sent_packets << ";" << endl;
      }
    } while(!batch_complete);
    cout << "Batch " << batch_index + 1 << " ("<<_batch_size  <<  " packets) sent. Time used is " << _time - start_time << " cycles." << endl;
    cout << "Draining the Network...................\n";
    _sim_state = draining;
    _drain_time = _time;
    int empty_steps = 0;

    bool packets_left = false;
    for(int c = 0; c < _classes; ++c) {
      packets_left |= !_total_in_flight_flits[c].empty();
    }

    while( packets_left ) {
      _Step( );

      ++empty_steps;

      if ( empty_steps % 1000 == 0 ) {
	_DisplayRemaining( );
	cout << ".";
      }

      packets_left = false;
      for(int c = 0; c < _classes; ++c) {
	packets_left |= !_total_in_flight_flits[c].empty();
      }
    }
    cout << endl;
    cout << "Batch " << batch_index + 1 << " ("<<_batch_size  <<  " packets) received. Time used is " << _time - _drain_time << " cycles. Last packet was " << _last_pid << ", last flit was " << _last_id << "." <<endl;

    _batch_time->AddSample(_time - start_time);

    cout << _sim_state << endl;

    DisplayStats();

    ++batch_index;
  }
  return 1;
}

void BatchTrafficManager::_UpdateOverallStats() {
  TrafficManager::_UpdateOverallStats();
  _overall_min_batch_time += _batch_time->Min();
  _overall_avg_batch_time += _batch_time->Average();
  _overall_max_batch_time += _batch_time->Max();
}

string BatchTrafficManager::_OverallStatsCSV(int c) const
{
  ostringstream os;
  os << TrafficManager::_OverallStatsCSV(c) << ','
     << _overall_min_batch_time << ','
     << _overall_avg_batch_time << ','
     << _overall_max_batch_time;
  return os.str();
}

void BatchTrafficManager::WriteStats(ostream & os) const
{
  os << "batch_time = " << _batch_time->Average() << ";" << endl;
  TrafficManager::WriteStats(os);
}

void BatchTrafficManager::DisplayStats(ostream & os) const {
  os << "Minimum batch duration = " << _batch_time->Min() << endl;
  os << "Average batch duration = " << _batch_time->Average() << endl;
  os << "Maximum batch duration = " << _batch_time->Max() << endl;
  TrafficManager::DisplayStats();
}

void BatchTrafficManager::DisplayOverallStats(ostream & os) const {
  TrafficManager::DisplayOverallStats(os);
  os << "Overall min batch duration = " << _overall_min_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl
     << "Overall min batch duration = " << _overall_avg_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl
     << "Overall min batch duration = " << _overall_max_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl;
}
<commit_msg>properly scale overall batch time stats<commit_after>// $Id$

/*
Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
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 the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 <limits>
#include <sstream>
#include <fstream>

#include "packet_reply_info.hpp"
#include "random_utils.hpp"
#include "batchtrafficmanager.hpp"

BatchTrafficManager::BatchTrafficManager( const Configuration &config,
					  const vector<Network *> & net )
: TrafficManager(config, net), _last_id(-1), _last_pid(-1),
   _overall_min_batch_time(0), _overall_avg_batch_time(0),
   _overall_max_batch_time(0)
{

  _max_outstanding = config.GetInt ("max_outstanding_requests");

  _batch_size = config.GetInt( "batch_size" );
  _batch_count = config.GetInt( "batch_count" );

  _batch_time = new Stats( this, "batch_time", 1.0, 1000 );
  _stats["batch_time"] = _batch_time;

  string sent_packets_out_file = config.GetStr( "sent_packets_out" );
  if(sent_packets_out_file == "") {
    _sent_packets_out = NULL;
  } else {
    _sent_packets_out = new ofstream(sent_packets_out_file.c_str());
  }
}

BatchTrafficManager::~BatchTrafficManager( )
{
  delete _batch_time;
  if(_sent_packets_out) delete _sent_packets_out;
}

void BatchTrafficManager::_RetireFlit( Flit *f, int dest )
{
  _last_id = f->id;
  _last_pid = f->pid;
  TrafficManager::_RetireFlit(f, dest);
}

int BatchTrafficManager::_IssuePacket( int source, int cl )
{
  int result = 0;
  if(_use_read_write[cl]) { //read write packets
    //check queue for waiting replies.
    //check to make sure it is on time yet
    if(!_repliesPending[source].empty()) {
      if(_repliesPending[source].front()->time <= _qtime[source][cl]) {
	result = -1;
      }
    } else {
      if((_sent_packets[source] < _batch_size) &&
	 ((_max_outstanding <= 0) ||
	  (_requestsOutstanding[source] < _max_outstanding))) {

	//coin toss to determine request type.
	result = (RandomFloat() < 0.5) ? 2 : 1;

	_requestsOutstanding[source]++;
      }
    }
  } else { //normal
    if((_sent_packets[source] < _batch_size) &&
       ((_max_outstanding <= 0) ||
	(_requestsOutstanding[source] < _max_outstanding))) {
      result = _packet_size[cl];
      _requestsOutstanding[source]++;
    }
  }
  if(result != 0) {
    _sent_packets[source]++;
  }
  return result;
}

void BatchTrafficManager::_ClearStats( )
{
  TrafficManager::_ClearStats();
  _batch_time->Clear( );
}

bool BatchTrafficManager::_SingleSim( )
{
  int batch_index = 0;
  while(batch_index < _batch_count) {
    _sent_packets.assign(_nodes, 0);
    _last_id = -1;
    _last_pid = -1;
    _sim_state = running;
    int start_time = _time;
    bool batch_complete;
    do {
      _Step();
      batch_complete = true;
      for(int i = 0; i < _nodes; ++i) {
	if(_sent_packets[i] < _batch_size) {
	  batch_complete = false;
	  break;
	}
      }
      if(_sent_packets_out) {
	*_sent_packets_out << _sent_packets << ";" << endl;
      }
    } while(!batch_complete);
    cout << "Batch " << batch_index + 1 << " ("<<_batch_size  <<  " packets) sent. Time used is " << _time - start_time << " cycles." << endl;
    cout << "Draining the Network...................\n";
    _sim_state = draining;
    _drain_time = _time;
    int empty_steps = 0;

    bool packets_left = false;
    for(int c = 0; c < _classes; ++c) {
      packets_left |= !_total_in_flight_flits[c].empty();
    }

    while( packets_left ) {
      _Step( );

      ++empty_steps;

      if ( empty_steps % 1000 == 0 ) {
	_DisplayRemaining( );
	cout << ".";
      }

      packets_left = false;
      for(int c = 0; c < _classes; ++c) {
	packets_left |= !_total_in_flight_flits[c].empty();
      }
    }
    cout << endl;
    cout << "Batch " << batch_index + 1 << " ("<<_batch_size  <<  " packets) received. Time used is " << _time - _drain_time << " cycles. Last packet was " << _last_pid << ", last flit was " << _last_id << "." <<endl;

    _batch_time->AddSample(_time - start_time);

    cout << _sim_state << endl;

    DisplayStats();

    ++batch_index;
  }
  return 1;
}

void BatchTrafficManager::_UpdateOverallStats() {
  TrafficManager::_UpdateOverallStats();
  _overall_min_batch_time += _batch_time->Min();
  _overall_avg_batch_time += _batch_time->Average();
  _overall_max_batch_time += _batch_time->Max();
}

string BatchTrafficManager::_OverallStatsCSV(int c) const
{
  ostringstream os;
  os << TrafficManager::_OverallStatsCSV(c) << ','
     << _overall_min_batch_time / (double)_total_sims << ','
     << _overall_avg_batch_time / (double)_total_sims << ','
     << _overall_max_batch_time / (double)_total_sims;
  return os.str();
}

void BatchTrafficManager::WriteStats(ostream & os) const
{
  os << "batch_time = " << _batch_time->Average() << ";" << endl;
  TrafficManager::WriteStats(os);
}

void BatchTrafficManager::DisplayStats(ostream & os) const {
  os << "Minimum batch duration = " << _batch_time->Min() << endl;
  os << "Average batch duration = " << _batch_time->Average() << endl;
  os << "Maximum batch duration = " << _batch_time->Max() << endl;
  TrafficManager::DisplayStats();
}

void BatchTrafficManager::DisplayOverallStats(ostream & os) const {
  TrafficManager::DisplayOverallStats(os);
  os << "Overall min batch duration = " << _overall_min_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl
     << "Overall min batch duration = " << _overall_avg_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl
     << "Overall min batch duration = " << _overall_max_batch_time / (double)_total_sims
     << " (" << _total_sims << " samples)" << endl;
}
<|endoftext|>


<commit_before>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>

namespace {
  bool
  verifyUser(void)
  {
    uid_t consoleUID;
    CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
    if (! result) return false;
    CFRelease(result);

    return (getuid() == consoleUID);
  }
}

int
main(int argc, char** argv)
{
  if (argc != 3) {
    fprintf(stderr, "Usage: %s key value\n", argv[0]);
    return 1;
  }

  if (! verifyUser()) {
    return 1;
  }

  char name[512];
  snprintf(name, sizeof(name), "keyremap4macbook.%s", argv[1]);

  if (strcmp(argv[1], "socket_path") == 0) {
    char* value = argv[2];
    size_t oldlen = 0;
    size_t newlen = strlen(value) + 1;
    int error = sysctlbyname(name, NULL, &oldlen, value, newlen);

    if (error) {
      perror("sysctl_set socket_path");
      return 1;
    }

  } else {
    int value = atoi(argv[2]);

    size_t oldlen = 0;
    size_t newlen = sizeof(value);
    int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);

    if (error) {
      perror("sysctl_set");
      return 1;
    }
  }

  return 0;
}
<commit_msg>remove perror @ sysctl_set<commit_after>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>

namespace {
  bool
  verifyUser(void)
  {
    uid_t consoleUID;
    CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
    if (! result) return false;
    CFRelease(result);

    return (getuid() == consoleUID);
  }
}

int
main(int argc, char** argv)
{
  if (argc != 3) {
    fprintf(stderr, "Usage: %s key value\n", argv[0]);
    return 1;
  }

  if (! verifyUser()) {
    return 1;
  }

  char name[512];
  snprintf(name, sizeof(name), "keyremap4macbook.%s", argv[1]);

  if (strcmp(argv[1], "socket_path") == 0) {
    char* value = argv[2];
    size_t oldlen = 0;
    size_t newlen = strlen(value) + 1;
    int error = sysctlbyname(name, NULL, &oldlen, value, newlen);

    if (error) {
      //perror("sysctl_set socket_path");
      return 1;
    }

  } else {
    int value = atoi(argv[2]);

    size_t oldlen = 0;
    size_t newlen = sizeof(value);
    int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);

    if (error) {
      //perror("sysctl_set");
      return 1;
    }
  }

  return 0;
}
<|endoftext|>