<commit_before>/*
 * mailreader.cpp
 *
 * Copyright (C) 2008 Andras Mantia <amantia@kde.org>
 */
#include "mailreader.h"

#include "akonadi_next/entitytreeview.h"
#include <akonadi/entityfilterproxymodel.h>
#include <akonadi/entitytreemodel.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/monitor.h>
#include <akonadi/session.h>
#include <akonadi/statisticstooltipproxymodel.h>

#include <KDE/KAction>
#include <KDE/KConfigDialog>
#include <KDE/KActionCollection>
#include <KDE/KLocale>
#include <KDE/KStandardAction>
#include <KDE/KStatusBar>

#include <QtGui/QDockWidget>
#include <QtGui/QSortFilterProxyModel>

#include <messagelist/pane.h>

#include "mailreaderview.h"
#include "settings.h"

mailreader::mailreader()
    : KXmlGuiWindow(),
      m_view(new mailreaderView(this))
{
    // accept dnd
    setAcceptDrops(true);

    // tell the KXmlGuiWindow that this is indeed the main widget
    setCentralWidget(m_view);

    setupDocks();

    // then, setup our actions
    setupActions();

    // add a status bar
    statusBar()->show();

    // a call to KXmlGuiWindow::setupGUI() populates the GUI
    // with actions, using KXMLGUI.
    // It also applies the saved mainwindow settings, if any, and ask the
    // mainwindow to automatically save settings if changed: window size,
    // toolbar position, icon size, etc.
    setupGUI();

}

mailreader::~mailreader()
{
}

void mailreader::setupDocks()
{
  // Setup the core model
  Akonadi::Session *session = new Akonadi::Session( "AkonadiMailReader", this );

  Akonadi::Monitor *monitor = new Akonadi::Monitor( this );
  monitor->setCollectionMonitored( Akonadi::Collection::root() );
  monitor->fetchCollection( true );
  monitor->setMimeTypeMonitored( "message/rfc822", true );
  monitor->itemFetchScope().fetchFullPayload(true);

  Akonadi::EntityTreeModel *entityModel = new Akonadi::EntityTreeModel( session, monitor, this );
  entityModel->setItemPopulationStrategy( Akonadi::EntityTreeModel::LazyPopulation );

  // Create the collection view
  Akonadi::EntityTreeView *collectionView = new Akonadi::EntityTreeView( 0, this );
  collectionView->setSelectionMode( QAbstractItemView::ExtendedSelection );

  // Setup the message folders collection...
  Akonadi::EntityFilterProxyModel *collectionFilter = new Akonadi::EntityFilterProxyModel( this );
  collectionFilter->setSourceModel( entityModel );
  collectionFilter->addMimeTypeInclusionFilter( Akonadi::Collection::mimeType() );
  collectionFilter->setHeaderSet( Akonadi::EntityTreeModel::CollectionTreeHeaders );

  // ... with statistics...
  Akonadi::StatisticsToolTipProxyModel *statisticsProxyModel = new Akonadi::StatisticsToolTipProxyModel( this );
  statisticsProxyModel->setSourceModel( collectionFilter );

  // ... and sortable
  QSortFilterProxyModel *sortModel = new QSortFilterProxyModel( this );
  sortModel->setDynamicSortFilter( true );
  sortModel->setSortCaseSensitivity( Qt::CaseInsensitive );
  sortModel->setSourceModel( statisticsProxyModel );

  // Use the model
  collectionView->setModel( sortModel );

  // Now make the message list multi-tab pane
  m_messagePane = new MessageList::Pane( entityModel, collectionView->selectionModel(), this );
  connect( m_messagePane, SIGNAL(messageSelected(Akonadi::Item)),
           this, SLOT(slotMessageSelected(Akonadi::Item)) );

  // Dock the message list view
  QDockWidget *messageListDock = new QDockWidget( i18n("Messages"), this );
  messageListDock->setObjectName( "Messages" );
  messageListDock->setWidget( m_messagePane );
  messageListDock->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable );
  addDockWidget( Qt::TopDockWidgetArea, messageListDock );

  // Dock the folder tree view
  QDockWidget *folderDock = new QDockWidget( i18n("Folders"), this );
  folderDock->setObjectName( "Folders" );
  folderDock->setWidget( collectionView );
  folderDock->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable );
  addDockWidget( Qt::LeftDockWidgetArea, folderDock );

  // Fine tuning on the dock policy (nesting + corners)
  setDockNestingEnabled( true );
  setCorner( Qt::TopLeftCorner, Qt::LeftDockWidgetArea );
  setCorner( Qt::BottomLeftCorner, Qt::LeftDockWidgetArea );
  setCorner( Qt::TopRightCorner, Qt::RightDockWidgetArea );
  setCorner( Qt::BottomRightCorner, Qt::RightDockWidgetArea );
}

void mailreader::setupActions()
{
    KStandardAction::quit(qApp, SLOT(closeAllWindows()), actionCollection());
    KStandardAction::preferences(m_view, SLOT(slotConfigure()), actionCollection());

    KAction *createTab = new KAction(KIcon("tab-new"),
                                      i18n("Open a new tab"),
                                      this);
    actionCollection()->addAction("new_tab", createTab);
    connect(createTab, SIGNAL(triggered(bool)),
            m_messagePane, SLOT(createNewTab()));

    m_previousMessage = new KAction("Previous Message", this);
    actionCollection()->addAction("previous_message", m_previousMessage);
    connect(m_previousMessage, SIGNAL(triggered( bool )), SLOT(slotPreviousMessage()));
    m_nextMessage = new KAction("Next Message", this);
    actionCollection()->addAction("next_message", m_nextMessage);
    connect(m_nextMessage, SIGNAL(triggered( bool )), SLOT(slotNextMessage()));
}

void mailreader::slotMessageSelected( const Akonadi::Item &item )
{
  m_view->showItem( item );
}

void mailreader::slotPreviousMessage()
{
  m_messagePane->selectPreviousMessageItem( MessageList::Core::MessageTypeAny,
                                            MessageList::Core::ClearExistingSelection,
                                            true, true );
}

void mailreader::slotNextMessage()
{
  m_messagePane->selectNextMessageItem( MessageList::Core::MessageTypeAny,
                                        MessageList::Core::ClearExistingSelection,
                                        true, true );
}

#include "mailreader.moc"
<commit_msg>Add missing i18n <commit_after>/*
 * mailreader.cpp
 *
 * Copyright (C) 2008 Andras Mantia <amantia@kde.org>
 */
#include "mailreader.h"

#include "akonadi_next/entitytreeview.h"
#include <akonadi/entityfilterproxymodel.h>
#include <akonadi/entitytreemodel.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/monitor.h>
#include <akonadi/session.h>
#include <akonadi/statisticstooltipproxymodel.h>

#include <KDE/KAction>
#include <KDE/KConfigDialog>
#include <KDE/KActionCollection>
#include <KDE/KLocale>
#include <KDE/KStandardAction>
#include <KDE/KStatusBar>

#include <QtGui/QDockWidget>
#include <QtGui/QSortFilterProxyModel>

#include <messagelist/pane.h>

#include "mailreaderview.h"
#include "settings.h"

mailreader::mailreader()
    : KXmlGuiWindow(),
      m_view(new mailreaderView(this))
{
    // accept dnd
    setAcceptDrops(true);

    // tell the KXmlGuiWindow that this is indeed the main widget
    setCentralWidget(m_view);

    setupDocks();

    // then, setup our actions
    setupActions();

    // add a status bar
    statusBar()->show();

    // a call to KXmlGuiWindow::setupGUI() populates the GUI
    // with actions, using KXMLGUI.
    // It also applies the saved mainwindow settings, if any, and ask the
    // mainwindow to automatically save settings if changed: window size,
    // toolbar position, icon size, etc.
    setupGUI();

}

mailreader::~mailreader()
{
}

void mailreader::setupDocks()
{
  // Setup the core model
  Akonadi::Session *session = new Akonadi::Session( "AkonadiMailReader", this );

  Akonadi::Monitor *monitor = new Akonadi::Monitor( this );
  monitor->setCollectionMonitored( Akonadi::Collection::root() );
  monitor->fetchCollection( true );
  monitor->setMimeTypeMonitored( "message/rfc822", true );
  monitor->itemFetchScope().fetchFullPayload(true);

  Akonadi::EntityTreeModel *entityModel = new Akonadi::EntityTreeModel( session, monitor, this );
  entityModel->setItemPopulationStrategy( Akonadi::EntityTreeModel::LazyPopulation );

  // Create the collection view
  Akonadi::EntityTreeView *collectionView = new Akonadi::EntityTreeView( 0, this );
  collectionView->setSelectionMode( QAbstractItemView::ExtendedSelection );

  // Setup the message folders collection...
  Akonadi::EntityFilterProxyModel *collectionFilter = new Akonadi::EntityFilterProxyModel( this );
  collectionFilter->setSourceModel( entityModel );
  collectionFilter->addMimeTypeInclusionFilter( Akonadi::Collection::mimeType() );
  collectionFilter->setHeaderSet( Akonadi::EntityTreeModel::CollectionTreeHeaders );

  // ... with statistics...
  Akonadi::StatisticsToolTipProxyModel *statisticsProxyModel = new Akonadi::StatisticsToolTipProxyModel( this );
  statisticsProxyModel->setSourceModel( collectionFilter );

  // ... and sortable
  QSortFilterProxyModel *sortModel = new QSortFilterProxyModel( this );
  sortModel->setDynamicSortFilter( true );
  sortModel->setSortCaseSensitivity( Qt::CaseInsensitive );
  sortModel->setSourceModel( statisticsProxyModel );

  // Use the model
  collectionView->setModel( sortModel );

  // Now make the message list multi-tab pane
  m_messagePane = new MessageList::Pane( entityModel, collectionView->selectionModel(), this );
  connect( m_messagePane, SIGNAL(messageSelected(Akonadi::Item)),
           this, SLOT(slotMessageSelected(Akonadi::Item)) );

  // Dock the message list view
  QDockWidget *messageListDock = new QDockWidget( i18n("Messages"), this );
  messageListDock->setObjectName( "Messages" );
  messageListDock->setWidget( m_messagePane );
  messageListDock->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable );
  addDockWidget( Qt::TopDockWidgetArea, messageListDock );

  // Dock the folder tree view
  QDockWidget *folderDock = new QDockWidget( i18n("Folders"), this );
  folderDock->setObjectName( "Folders" );
  folderDock->setWidget( collectionView );
  folderDock->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable );
  addDockWidget( Qt::LeftDockWidgetArea, folderDock );

  // Fine tuning on the dock policy (nesting + corners)
  setDockNestingEnabled( true );
  setCorner( Qt::TopLeftCorner, Qt::LeftDockWidgetArea );
  setCorner( Qt::BottomLeftCorner, Qt::LeftDockWidgetArea );
  setCorner( Qt::TopRightCorner, Qt::RightDockWidgetArea );
  setCorner( Qt::BottomRightCorner, Qt::RightDockWidgetArea );
}

void mailreader::setupActions()
{
    KStandardAction::quit(qApp, SLOT(closeAllWindows()), actionCollection());
    KStandardAction::preferences(m_view, SLOT(slotConfigure()), actionCollection());

    KAction *createTab = new KAction(KIcon("tab-new"),
                                      i18n("Open a new tab"),
                                      this);
    actionCollection()->addAction("new_tab", createTab);
    connect(createTab, SIGNAL(triggered(bool)),
            m_messagePane, SLOT(createNewTab()));

    m_previousMessage = new KAction(i18n("Previous Message"), this);
    actionCollection()->addAction("previous_message", m_previousMessage);
    connect(m_previousMessage, SIGNAL(triggered( bool )), SLOT(slotPreviousMessage()));
    m_nextMessage = new KAction(i18n("Next Message"), this);
    actionCollection()->addAction("next_message", m_nextMessage);
    connect(m_nextMessage, SIGNAL(triggered( bool )), SLOT(slotNextMessage()));
}

void mailreader::slotMessageSelected( const Akonadi::Item &item )
{
  m_view->showItem( item );
}

void mailreader::slotPreviousMessage()
{
  m_messagePane->selectPreviousMessageItem( MessageList::Core::MessageTypeAny,
                                            MessageList::Core::ClearExistingSelection,
                                            true, true );
}

void mailreader::slotNextMessage()
{
  m_messagePane->selectNextMessageItem( MessageList::Core::MessageTypeAny,
                                        MessageList::Core::ClearExistingSelection,
                                        true, true );
}

#include "mailreader.moc"
<|endoftext|>


<commit_before>/**
 * @mainpage	COSSB(Component-based Open & Simple Service Broker)
 * @details	COSSB is a software framework to support IoT service interoperability among the networked devices or gadgets scattered in WLAN environment.
 */

/**
 * @file		engine.hpp
 * @brief		COSSB Engine
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details	COSSB Engine main routine
 */

#include <iostream>
#include <csignal>
#include <cstdlib>
#include <unistd.h>
#include <popt.h>

#include "cossb.hpp"

using namespace std;

/**
 * @brief	destroy main instance
 * @details	It will be called by SIGINT signal
 */
void destroy()
{

}

/**
 * @brief	SIGINT signal callback function
 * @details	Stop all services and destroy all instances
 */
void sigc_interrupt(int param) { destroy();	exit(0); }

/**
 * @brief	Main routine
 * @param	command
 * @details	Start with default components
 */
int main(int argc, char* argv[])
{
	signal(SIGINT, sigc_interrupt);

	char* config_file = nullptr;
	struct poptOption optionTable[] = {
			{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
			{"config", 'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open config file", "XML Config file"},
			POPT_AUTOHELP
			POPT_TABLEEND
	};
	poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
	poptSetOtherOptionHelp(optionCon, "<option>");

	if(argc<2)
	{
		destroy();
		exit(0);
	}

	int opt = 0;
	while((opt = poptGetNextOpt(optionCon))>=0)
	{
		switch(opt)
		{
		// install components
		case 'v':
		{
			//print out version

		} break;

		case 'c':
		{
			string config_file = (const char*)poptGetOptArg(optionCon);
		}
			break;

		}
	}

	if (opt<-1)
	{
		cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
		destroy();
		exit(0);
	}

	//notice, this function affects the checking memory leak, especially when you are using valgrind.
	poptFreeContext(optionCon);

	destroy();
	exit(0);

	return 0;
}
<commit_msg>fixed engine command<commit_after>/**
 * @mainpage	COSSB(Component-based Open & Simple Service Broker)
 * @details	COSSB is a software framework to support IoT service interoperability among the networked devices or gadgets scattered in WLAN environment.
 */

/**
 * @file		engine.hpp
 * @brief		COSSB Engine
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details	COSSB Engine main routine
 */

#include <iostream>
#include <csignal>
#include <cstdlib>
#include <unistd.h>
#include <popt.h>
#include <memory>

#include "cossb.hpp"

using namespace std;

/**
 * @brief	destroy main instance
 * @details	It will be called by SIGINT signal
 */
void destroy()
{

}

/**
 * @brief	SIGINT signal callback function
 * @details	Stop all services and destroy all instances
 */
void sigc_interrupt(int param) { destroy();	exit(0); }

/**
 * @brief	Main routine
 * @param	command
 * @details	Start with default components
 */
int main(int argc, char* argv[])
{
	signal(SIGINT, sigc_interrupt);

	char* config_file = nullptr;
	struct poptOption optionTable[] = {
			{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
			{"config", 'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open config file", "XML Config file"},
			POPT_AUTOHELP
			POPT_TABLEEND
	};
	poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
	poptSetOtherOptionHelp(optionCon, "<option>");

	if(argc<2)
	{
		destroy();
		exit(0);
	}

	int opt = 0;
	while((opt = poptGetNextOpt(optionCon))>=0)
	{
		switch(opt)
		{
		// install components
		case 'v':
		{
			//print out version

		} break;

		case 'c':
		{
			string config_file = (const char*)poptGetOptArg(optionCon);
		}
			break;

		}
	}

	if (opt<-1)
	{
		cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
		destroy();
		exit(0);
	}

	//notice, this function affects the checking memory leak, especially when you are using valgrind.
	poptFreeContext(optionCon);

	destroy();
	exit(0);

	return 0;
}
<|endoftext|>


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

#include "condor_common.h"
#include "condor_config.h"
#include "starter.h"
#include "StarterHookMgr.h"
#include "condor_attributes.h"
#include "hook_utils.h"
#include "status_string.h"
#include "classad_merge.h"

extern CStarter *Starter;

// // // // // // // // // // // //
// StarterHookMgr
// // // // // // // // // // // //

StarterHookMgr::StarterHookMgr()
	: HookClientMgr()
{
	m_hook_keyword = NULL;
	m_hook_prepare_job = NULL;
	m_hook_update_job_info = NULL;
	m_hook_job_exit = NULL;

	dprintf( D_FULLDEBUG, "Instantiating a StarterHookMgr\n" );
}

StarterHookMgr::~StarterHookMgr()
{
	dprintf( D_FULLDEBUG, "Deleting the StarterHookMgr\n" );

		// Delete our copies of the paths for each hook.
	clearHookPaths();

	if (m_hook_keyword) {
		free(m_hook_keyword);
	}
}

void
StarterHookMgr::clearHookPaths()
{
	if (m_hook_prepare_job) {
		free(m_hook_prepare_job);
	}
	if (m_hook_update_job_info) {
		free(m_hook_update_job_info);
	}
	if (m_hook_job_exit) {
		free(m_hook_job_exit);
	}
}

bool
StarterHookMgr::initialize(ClassAd* job_ad)
{
	char* tmp = param("STARTER_JOB_HOOK_KEYWORD");
	if (tmp) {
		m_hook_keyword = tmp;
		dprintf(D_FULLDEBUG, "Using STARTER_JOB_HOOK_KEYWORD value from config file: \"%s\"\n", m_hook_keyword);
	}
	else if (!job_ad->LookupString(ATTR_HOOK_KEYWORD, &m_hook_keyword)) {
		dprintf(D_FULLDEBUG,
				"Job does not define %s, not invoking any job hooks.\n",
				ATTR_HOOK_KEYWORD);
		return false;
	}
	else {
		dprintf(D_FULLDEBUG,
				"Using %s value from job ClassAd: \"%s\"\n",
				ATTR_HOOK_KEYWORD, m_hook_keyword);
	}
	reconfig();
	return HookClientMgr::initialize();
}

bool
StarterHookMgr::reconfig()
{
		// Clear out our old copies of each hook's path.
	clearHookPaths();

	m_hook_prepare_job = getHookPath(HOOK_PREPARE_JOB);
	m_hook_update_job_info = getHookPath(HOOK_UPDATE_JOB_INFO);
	m_hook_job_exit = getHookPath(HOOK_JOB_EXIT);

	return true;
}

char*
StarterHookMgr::getHookPath(HookType hook_type)
{
	if (!m_hook_keyword) {
		return NULL;
	}
	MyString _param;
	_param.sprintf("%s_HOOK_%s", m_hook_keyword, getHookTypeString(hook_type));
	return validateHookPath(_param.Value());
}

int
StarterHookMgr::tryHookPrepareJob()
{
	if (!m_hook_prepare_job) {
		dprintf(D_FULLDEBUG, "HOOK_PREPARE_JOB not configured.\n");
		return 0;
	}

	MyString hook_stdin;
	ClassAd* job_ad = Starter->jic->jobClassAd();
	job_ad->sPrint(hook_stdin);

	HookClient* hook_client = new HookPrepareJobClient(m_hook_prepare_job);

	if (!spawn(hook_client, NULL, &hook_stdin)) {
		MyString err_msg;
		err_msg.sprintf("failed to execute HOOK_PREPARE_JOB (%s)",
						m_hook_prepare_job);
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookPrepareJob: %s\n",
				err_msg.Value());
		Starter->jic->notifyStarterError(err_msg.Value(), true,
						 CONDOR_HOLD_CODE_HookPrepareJobFailure, 0);
		return -1;
	}

	dprintf(D_FULLDEBUG, "HOOK_PREPARE_JOB (%s) invoked.\n",
			m_hook_prepare_job);
	return 1;
}

bool
StarterHookMgr::hookUpdateJobInfo(ClassAd* job_info)
{
	if (!m_hook_update_job_info) {
			// No need to dprintf() here, since this happens a lot.
		return false;
	}
	ASSERT(job_info);

	ClassAd update_ad(*(Starter->jic->jobClassAd()));
	MergeClassAds(&update_ad, job_info, true);

	MyString hook_stdin;
	update_ad.sPrint(hook_stdin);

		// Since we're not saving the output, this can just live on
        // the stack and be destroyed as soon as we return.
    HookClient client(HOOK_UPDATE_JOB_INFO, m_hook_update_job_info, false);

	if (!spawn(&client, NULL, &hook_stdin)) {
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::hookUpdateJobInfo: "
				"failed to spawn HOOK_UPDATE_JOB_INFO (%s)\n",
				m_hook_update_job_info);
		return false;
	}

	dprintf(D_FULLDEBUG, "HOOK_PREPARE_JOB (%s) invoked.\n",
			m_hook_prepare_job);
	return true;
}

int
StarterHookMgr::tryHookJobExit(ClassAd* job_info, const char* exit_reason)
{
	if (!m_hook_job_exit) {
		static bool logged_not_configured = false;
		if (!logged_not_configured) {
			dprintf(D_FULLDEBUG, "HOOK_JOB_EXIT not configured.\n");
			logged_not_configured = true;
		}
		return 0;
	}

	HookClient *hook_client;

		// Next, in case of retry, make sure we didn't already spawn
		// this hook and are just waiting for it to return.
    m_client_list.Rewind();
    while (m_client_list.Next(hook_client)) {
		if (hook_client->type() == HOOK_JOB_EXIT) {
			dprintf(D_FULLDEBUG,
					"StarterHookMgr::tryHookJobExit() retried while still "
					"waiting for HOOK_JOB_EXIT to return - ignoring\n");
				// We want to return 1 here to indicate to the JIC
				// that the hook is currently running and it should
				// wait before moving on.
			return 1;
		}
	}

	ASSERT(job_info);
	ASSERT(exit_reason);

	MyString hook_stdin;
	job_info->sPrint(hook_stdin);

	ArgList args;
	args.AppendArg(exit_reason);

	hook_client = new HookJobExitClient(m_hook_job_exit);

	if (!spawn(hook_client, &args, &hook_stdin)) {
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookJobExit: "
				"failed to spawn HOOK_JOB_EXIT (%s)\n", m_hook_job_exit);
		return -1;
	}

	dprintf(D_FULLDEBUG, "HOOK_JOB_EXIT (%s) invoked with reason: \"%s\"\n",
			m_hook_job_exit, exit_reason);
	return 1;
}

// // // // // // // // // // // //
// HookPrepareJobClient class
// // // // // // // // // // // //

HookPrepareJobClient::HookPrepareJobClient(const char* hook_path)
	: HookClient(HOOK_PREPARE_JOB, hook_path, true)
{
		// Nothing special needed in the child class.
}

void
HookPrepareJobClient::hookExited(int exit_status) {
	HookClient::hookExited(exit_status);
	if (WIFSIGNALED(exit_status) || WEXITSTATUS(exit_status) != 0) {
		MyString status_msg = "";
		statusString(exit_status, status_msg);
		int subcode;
		if (WIFSIGNALED(exit_status)) {
			subcode = -1 * WTERMSIG(exit_status);
		}
		else {
			subcode = WEXITSTATUS(exit_status);
		}
		MyString err_msg;
		err_msg.sprintf("HOOK_PREPARE_JOB (%s) failed (%s)", m_hook_path,
						status_msg.Value());
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookPrepareJob: %s\n",
				err_msg.Value());
		Starter->jic->notifyStarterError(err_msg.Value(), true,
							 CONDOR_HOLD_CODE_HookPrepareJobFailure, subcode);
		Starter->RemoteShutdownFast(0);
	}
	else {
			// Make an update ad from the stdout of the hook
		MyString out(*getStdOut());
		ClassAd updateAd((char *)out.Value(), '\n');
		dprintf(D_FULLDEBUG, "Prepare hook output classad\n");
		updateAd.dPrint(D_FULLDEBUG);

			// Insert each expr from the update ad into the job ad
		updateAd.ResetExpr();
		ClassAd* job_ad = Starter->jic->jobClassAd();
		ExprTree *et;
		while ((et = updateAd.NextExpr())) {
			job_ad->Insert(et->DeepCopy());
		}
		dprintf(D_FULLDEBUG, "After Prepare hook: merged job classad:\n");
		job_ad->dPrint(D_FULLDEBUG);
		Starter->jobEnvironmentReady();
	}
}

// // // // // // // // // // // //
// HookJobExitClient class
// // // // // // // // // // // //

HookJobExitClient::HookJobExitClient(const char* hook_path)
	: HookClient(HOOK_JOB_EXIT, hook_path, true)
{
		// Nothing special needed in the child class.
}

void
HookJobExitClient::hookExited(int exit_status) {
	HookClient::hookExited(exit_status);
		// Tell the JIC that it can mark allJobsDone() finished.
	Starter->jic->finishAllJobsDone();
}
<commit_msg>The update job status hook was printing a message stating that the Prepare hook was invoked, when actually it was the the update job status hook. The function now prints the correct message.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_config.h"
#include "starter.h"
#include "StarterHookMgr.h"
#include "condor_attributes.h"
#include "hook_utils.h"
#include "status_string.h"
#include "classad_merge.h"

extern CStarter *Starter;

// // // // // // // // // // // //
// StarterHookMgr
// // // // // // // // // // // //

StarterHookMgr::StarterHookMgr()
	: HookClientMgr()
{
	m_hook_keyword = NULL;
	m_hook_prepare_job = NULL;
	m_hook_update_job_info = NULL;
	m_hook_job_exit = NULL;

	dprintf( D_FULLDEBUG, "Instantiating a StarterHookMgr\n" );
}

StarterHookMgr::~StarterHookMgr()
{
	dprintf( D_FULLDEBUG, "Deleting the StarterHookMgr\n" );

		// Delete our copies of the paths for each hook.
	clearHookPaths();

	if (m_hook_keyword) {
		free(m_hook_keyword);
	}
}

void
StarterHookMgr::clearHookPaths()
{
	if (m_hook_prepare_job) {
		free(m_hook_prepare_job);
	}
	if (m_hook_update_job_info) {
		free(m_hook_update_job_info);
	}
	if (m_hook_job_exit) {
		free(m_hook_job_exit);
	}
}

bool
StarterHookMgr::initialize(ClassAd* job_ad)
{
	char* tmp = param("STARTER_JOB_HOOK_KEYWORD");
	if (tmp) {
		m_hook_keyword = tmp;
		dprintf(D_FULLDEBUG, "Using STARTER_JOB_HOOK_KEYWORD value from config file: \"%s\"\n", m_hook_keyword);
	}
	else if (!job_ad->LookupString(ATTR_HOOK_KEYWORD, &m_hook_keyword)) {
		dprintf(D_FULLDEBUG,
				"Job does not define %s, not invoking any job hooks.\n",
				ATTR_HOOK_KEYWORD);
		return false;
	}
	else {
		dprintf(D_FULLDEBUG,
				"Using %s value from job ClassAd: \"%s\"\n",
				ATTR_HOOK_KEYWORD, m_hook_keyword);
	}
	reconfig();
	return HookClientMgr::initialize();
}

bool
StarterHookMgr::reconfig()
{
		// Clear out our old copies of each hook's path.
	clearHookPaths();

	m_hook_prepare_job = getHookPath(HOOK_PREPARE_JOB);
	m_hook_update_job_info = getHookPath(HOOK_UPDATE_JOB_INFO);
	m_hook_job_exit = getHookPath(HOOK_JOB_EXIT);

	return true;
}

char*
StarterHookMgr::getHookPath(HookType hook_type)
{
	if (!m_hook_keyword) {
		return NULL;
	}
	MyString _param;
	_param.sprintf("%s_HOOK_%s", m_hook_keyword, getHookTypeString(hook_type));
	return validateHookPath(_param.Value());
}

int
StarterHookMgr::tryHookPrepareJob()
{
	if (!m_hook_prepare_job) {
		dprintf(D_FULLDEBUG, "HOOK_PREPARE_JOB not configured.\n");
		return 0;
	}

	MyString hook_stdin;
	ClassAd* job_ad = Starter->jic->jobClassAd();
	job_ad->sPrint(hook_stdin);

	HookClient* hook_client = new HookPrepareJobClient(m_hook_prepare_job);

	if (!spawn(hook_client, NULL, &hook_stdin)) {
		MyString err_msg;
		err_msg.sprintf("failed to execute HOOK_PREPARE_JOB (%s)",
						m_hook_prepare_job);
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookPrepareJob: %s\n",
				err_msg.Value());
		Starter->jic->notifyStarterError(err_msg.Value(), true,
						 CONDOR_HOLD_CODE_HookPrepareJobFailure, 0);
		return -1;
	}

	dprintf(D_FULLDEBUG, "HOOK_PREPARE_JOB (%s) invoked.\n",
			m_hook_prepare_job);
	return 1;
}

bool
StarterHookMgr::hookUpdateJobInfo(ClassAd* job_info)
{
	if (!m_hook_update_job_info) {
			// No need to dprintf() here, since this happens a lot.
		return false;
	}
	ASSERT(job_info);

	ClassAd update_ad(*(Starter->jic->jobClassAd()));
	MergeClassAds(&update_ad, job_info, true);

	MyString hook_stdin;
	update_ad.sPrint(hook_stdin);

		// Since we're not saving the output, this can just live on
        // the stack and be destroyed as soon as we return.
    HookClient client(HOOK_UPDATE_JOB_INFO, m_hook_update_job_info, false);

	if (!spawn(&client, NULL, &hook_stdin)) {
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::hookUpdateJobInfo: "
				"failed to spawn HOOK_UPDATE_JOB_INFO (%s)\n",
				m_hook_update_job_info);
		return false;
	}

	dprintf(D_FULLDEBUG, "HOOK_UPDATE_JOB_INFO (%s) invoked.\n",
			m_hook_prepare_job);
	return true;
}

int
StarterHookMgr::tryHookJobExit(ClassAd* job_info, const char* exit_reason)
{
	if (!m_hook_job_exit) {
		static bool logged_not_configured = false;
		if (!logged_not_configured) {
			dprintf(D_FULLDEBUG, "HOOK_JOB_EXIT not configured.\n");
			logged_not_configured = true;
		}
		return 0;
	}

	HookClient *hook_client;

		// Next, in case of retry, make sure we didn't already spawn
		// this hook and are just waiting for it to return.
    m_client_list.Rewind();
    while (m_client_list.Next(hook_client)) {
		if (hook_client->type() == HOOK_JOB_EXIT) {
			dprintf(D_FULLDEBUG,
					"StarterHookMgr::tryHookJobExit() retried while still "
					"waiting for HOOK_JOB_EXIT to return - ignoring\n");
				// We want to return 1 here to indicate to the JIC
				// that the hook is currently running and it should
				// wait before moving on.
			return 1;
		}
	}

	ASSERT(job_info);
	ASSERT(exit_reason);

	MyString hook_stdin;
	job_info->sPrint(hook_stdin);

	ArgList args;
	args.AppendArg(exit_reason);

	hook_client = new HookJobExitClient(m_hook_job_exit);

	if (!spawn(hook_client, &args, &hook_stdin)) {
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookJobExit: "
				"failed to spawn HOOK_JOB_EXIT (%s)\n", m_hook_job_exit);
		return -1;
	}

	dprintf(D_FULLDEBUG, "HOOK_JOB_EXIT (%s) invoked with reason: \"%s\"\n",
			m_hook_job_exit, exit_reason);
	return 1;
}

// // // // // // // // // // // //
// HookPrepareJobClient class
// // // // // // // // // // // //

HookPrepareJobClient::HookPrepareJobClient(const char* hook_path)
	: HookClient(HOOK_PREPARE_JOB, hook_path, true)
{
		// Nothing special needed in the child class.
}

void
HookPrepareJobClient::hookExited(int exit_status) {
	HookClient::hookExited(exit_status);
	if (WIFSIGNALED(exit_status) || WEXITSTATUS(exit_status) != 0) {
		MyString status_msg = "";
		statusString(exit_status, status_msg);
		int subcode;
		if (WIFSIGNALED(exit_status)) {
			subcode = -1 * WTERMSIG(exit_status);
		}
		else {
			subcode = WEXITSTATUS(exit_status);
		}
		MyString err_msg;
		err_msg.sprintf("HOOK_PREPARE_JOB (%s) failed (%s)", m_hook_path,
						status_msg.Value());
		dprintf(D_ALWAYS|D_FAILURE,
				"ERROR in StarterHookMgr::tryHookPrepareJob: %s\n",
				err_msg.Value());
		Starter->jic->notifyStarterError(err_msg.Value(), true,
							 CONDOR_HOLD_CODE_HookPrepareJobFailure, subcode);
		Starter->RemoteShutdownFast(0);
	}
	else {
			// Make an update ad from the stdout of the hook
		MyString out(*getStdOut());
		ClassAd updateAd((char *)out.Value(), '\n');
		dprintf(D_FULLDEBUG, "Prepare hook output classad\n");
		updateAd.dPrint(D_FULLDEBUG);

			// Insert each expr from the update ad into the job ad
		updateAd.ResetExpr();
		ClassAd* job_ad = Starter->jic->jobClassAd();
		ExprTree *et;
		while ((et = updateAd.NextExpr())) {
			job_ad->Insert(et->DeepCopy());
		}
		dprintf(D_FULLDEBUG, "After Prepare hook: merged job classad:\n");
		job_ad->dPrint(D_FULLDEBUG);
		Starter->jobEnvironmentReady();
	}
}

// // // // // // // // // // // //
// HookJobExitClient class
// // // // // // // // // // // //

HookJobExitClient::HookJobExitClient(const char* hook_path)
	: HookClient(HOOK_JOB_EXIT, hook_path, true)
{
		// Nothing special needed in the child class.
}

void
HookJobExitClient::hookExited(int exit_status) {
	HookClient::hookExited(exit_status);
		// Tell the JIC that it can mark allJobsDone() finished.
	Starter->jic->finishAllJobsDone();
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_int_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140;
constexpr uint64_t literal_0x0000004000028000 = 0x0000004000028000;
constexpr uint64_t literal_0x00000000040101C3 = 0x00000000040101C3;
constexpr uint64_t literal_0x9554021F80100E0C = 0x9554021F80100E0C;
constexpr uint64_t literal_0b00 = 0b00;
constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020;
constexpr uint64_t literal_0xD8DFB200FFAFFFD7 = 0xD8DFB200FFAFFFD7;
constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002;
constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD;
constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000;
constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701;
constexpr uint64_t literal_0x00001003000002 = 0x00001003000002;
constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC;
constexpr uint64_t literal_0x0003C018006 = 0x0003C018006;
constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA;

fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer ));

            l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 );

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004000028000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x00000000040101C3 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80100E0C );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer ));

            l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200FFAFFFD7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer ));

            constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>INT FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_int_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140;
constexpr uint64_t literal_0x0000004004028000 = 0x0000004004028000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0x9554021F80110FCF = 0x9554021F80110FCF;
constexpr uint64_t literal_0b00 = 0b00;
constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020;
constexpr uint64_t literal_0xD8DFB200DFAFFFD7 = 0xD8DFB200DFAFFFD7;
constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002;
constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD;
constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000;
constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701;
constexpr uint64_t literal_0x00001003000002 = 0x00001003000002;
constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC;
constexpr uint64_t literal_0x0003C018006 = 0x0003C018006;
constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA;

fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer ));

            l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 );

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004004028000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80110FCF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer ));

            l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200DFAFFFD7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer ));

            constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer));
        }

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


<commit_before>#pragma once

#include "../indexer/feature.hpp"
#include "../indexer/features_vector.hpp"
#include "../indexer/index.hpp"

#include "../geometry/rect2d.hpp"
#include "../geometry/point2d.hpp"

#include "../coding/file_reader.hpp"
#include "../coding/buffer_reader.hpp"

#include "../base/start_mem_debug.hpp"

namespace model
{
//#define USE_BUFFER_READER

  class FeaturesFetcher
  {
    m2::RectD m_rect;

#ifdef USE_BUFFER_READER
    typedef BufferReader reader_t;
#else
    typedef FileReader reader_t;
#endif

    typedef Index<reader_t>::Type index_t;

    index_t m_multiIndex;

    // Cached query, which stores several caches for the index.
    mutable index_t::Query m_multiIndexQuery;

  public:

    void InitClassificator();

    void AddMap(string const & fName);
    void RemoveMap(string const & fName);
    void Clean();
    void ClearCaches();

    // process features by param type indices
    template <class ToDo>
    void ForEachFeature(m2::RectD const & rect, ToDo toDo) const
    {
      m_multiIndexQuery.Clear();
      m_multiIndex.ForEachInViewport(toDo, rect, m_multiIndexQuery);
      // Uncomment to traverse all features (SLOW!!):
      // m_multiIndex.ForEachInScale(toDo, GetScaleLevel(rect));
    }

    template <class ToDo>
    void ForEachFeatureWithScale(m2::RectD const & rect, ToDo toDo, int scale) const
    {
      m_multiIndex.ForEachInRect(toDo, rect, scale);
    }

    void AddWorldRect(m2::RectD const & r) { m_rect.Add(r); }
    m2::RectD GetWorldRect() const;
  };
}

#include "../base/stop_mem_debug.hpp"
<commit_msg>Add GetIndex() to the FeatureFetcher.<commit_after>#pragma once

#include "../indexer/feature.hpp"
#include "../indexer/features_vector.hpp"
#include "../indexer/index.hpp"

#include "../geometry/rect2d.hpp"
#include "../geometry/point2d.hpp"

#include "../coding/file_reader.hpp"
#include "../coding/buffer_reader.hpp"

#include "../base/start_mem_debug.hpp"

namespace model
{
//#define USE_BUFFER_READER

  class FeaturesFetcher
  {
    m2::RectD m_rect;

#ifdef USE_BUFFER_READER
    typedef BufferReader reader_t;
#else
    typedef FileReader reader_t;
#endif

    typedef Index<reader_t>::Type index_t;

    index_t m_multiIndex;

    // Cached query, which stores several caches for the index.
    mutable index_t::Query m_multiIndexQuery;

  public:

    void InitClassificator();

    void AddMap(string const & fName);
    void RemoveMap(string const & fName);
    void Clean();
    void ClearCaches();

    // process features by param type indices
    template <class ToDo>
    void ForEachFeature(m2::RectD const & rect, ToDo toDo) const
    {
      m_multiIndexQuery.Clear();
      m_multiIndex.ForEachInViewport(toDo, rect, m_multiIndexQuery);
      // Uncomment to traverse all features (SLOW!!):
      // m_multiIndex.ForEachInScale(toDo, GetScaleLevel(rect));
    }

    template <class ToDo>
    void ForEachFeatureWithScale(m2::RectD const & rect, ToDo toDo, int scale) const
    {
      m_multiIndex.ForEachInRect(toDo, rect, scale);
    }

    index_t const & GetIndex() const { return m_multiIndex; }

    void AddWorldRect(m2::RectD const & r) { m_rect.Add(r); }
    m2::RectD GetWorldRect() const;
  };
}

#include "../base/stop_mem_debug.hpp"
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013 Andrew Ruef

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <list>
#include "parse.h"
#include "nt-headers.h"

using namespace std;
using namespace boost;

struct section {
  string                sectionName;
  RVA                   sectionBase;
  bounded_buffer        *sectionData;
  image_section_header  sec;
};

struct reloc {
  RVA shiftedAddr;
  RVA shiftedTo;
};

struct parsed_pe_internal {
  list<section>   secs;
};

bool getSections( bounded_buffer  *b,
                  bounded_buffer  *fileBegin,
                  nt_header_32    &nthdr,
                  list<section>   &secs) {
  if(b == NULL) {
    return false;
  }

  //get each of the sections...
  for(::uint32_t i = 0; i < nthdr.FileHeader.NumberOfSections; i++) {
    image_section_header  curSec;

    ::uint32_t  o = i*sizeof(image_section_header);
    for(::uint32_t k = 0; k < NT_SHORT_NAME_LEN; k++) {
      readByte(b, o+k, curSec.Name[k]);
    }
#define READ_WORD(x) \
  if(readWord(b, o+_offset(image_section_header, x), curSec.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, o+_offset(image_section_header, x), curSec.x) == false) { \
    return false; \
  }

    READ_DWORD(VirtualAddress);
    READ_DWORD(SizeOfRawData);
    READ_DWORD(PointerToRawData);
    READ_DWORD(PointerToRelocations);
    READ_DWORD(PointerToLinenumbers);
    READ_WORD(NumberOfRelocations);
    READ_WORD(NumberOfLinenumbers);
    READ_DWORD(Characteristics);
#undef READ_WORD
#undef READ_DWORD

    //now we have the section header information, so fill in a section
    //object appropriately
    section thisSec;
    for(::uint32_t i = 0; i < NT_SHORT_NAME_LEN; i++) {
      ::uint8_t c = curSec.Name[i];
      if(c == 0) {
        break;
      }

      thisSec.sectionName.push_back((char)c);
    }

    thisSec.sectionBase = nthdr.OptionalHeader.ImageBase+curSec.VirtualAddress;
    thisSec.sec = curSec;
    ::uint32_t  lowOff = curSec.PointerToRawData;
    ::uint32_t  highOff = lowOff+curSec.SizeOfRawData;
    thisSec.sectionData = splitBuffer(fileBegin, lowOff, highOff);

    secs.push_back(thisSec);
  }

  return true;
}

bool readOptionalHeader(bounded_buffer *b, optional_header_32 &header) {
#define READ_WORD(x) \
  if(readWord(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }
#define READ_BYTE(x) \
  if(readByte(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }

  READ_WORD(Magic);

  if(header.Magic != NT_OPTIONAL_32_MAGIC) {
    return false;
  }

  READ_BYTE(MajorLinkerVersion);
  READ_BYTE(MinorLinkerVersion);
  READ_DWORD(SizeOfCode);
  READ_DWORD(SizeOfInitializedData);
  READ_DWORD(SizeOfUninitializedData);
  READ_DWORD(AddressOfEntryPoint);
  READ_DWORD(BaseOfCode);
  READ_DWORD(BaseOfData);
  READ_DWORD(ImageBase);
  READ_DWORD(SectionAlignment);
  READ_DWORD(FileAlignment);
  READ_WORD(MajorOperatingSystemVersion);
  READ_WORD(MinorOperatingSystemVersion);
  READ_WORD(MajorImageVersion);
  READ_WORD(MinorImageVersion);
  READ_WORD(MajorSubsystemVersion);
  READ_WORD(MinorSubsystemVersion);
  READ_DWORD(Win32VersionValue);
  READ_DWORD(SizeOfImage);
  READ_DWORD(SizeOfHeaders);
  READ_DWORD(CheckSum);
  READ_WORD(Subsystem);
  READ_WORD(DllCharacteristics);
  READ_DWORD(SizeOfStackReserve);
  READ_DWORD(SizeOfStackCommit);
  READ_DWORD(SizeOfHeapReserve);
  READ_DWORD(SizeOfHeapCommit);
  READ_DWORD(LoaderFlags);
  READ_DWORD(NumberOfRvaAndSizes);

#undef READ_WORD
#undef READ_DWORD
#undef READ_BYTE

  for(::uint32_t i = 0; i < header.NumberOfRvaAndSizes; i++) {
    ::uint32_t  c = (i*sizeof(data_directory));
    ::uint32_t  o;

    o = c + _offset(data_directory, VirtualAddress);
    if(readDword(b, o, header.DataDirectory[i].VirtualAddress) == false) {
      return false;
    }

    o = c+ _offset(data_directory, Size);
    if(readDword(b, o, header.DataDirectory[i].Size) == false) {
      return false;
    }
  }

  return true;
}

bool readFileHeader(bounded_buffer *b, file_header &header) {
#define READ_WORD(x) \
  if(readWord(b, _offset(file_header, x), header.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, _offset(file_header, x), header.x) == false) { \
    return false; \
  }

  READ_WORD(Machine);
  READ_WORD(NumberOfSections);
  READ_DWORD(TimeDateStamp);
  READ_DWORD(PointerToSymbolTable);
  READ_DWORD(NumberOfSymbols);
  READ_WORD(SizeOfOptionalHeader);
  READ_WORD(Characteristics);

#undef READ_DWORD
#undef READ_WORD
  return true;
}

bool readNtHeader(bounded_buffer *b, nt_header_32 &header) {
  if(b == NULL) {
    return false;
  }

  ::uint32_t  pe_magic;
  ::uint32_t  curOffset =0;
  if(readDword(b, curOffset, pe_magic) == false || pe_magic != NT_MAGIC) {
    return false;
  }

  header.Signature = pe_magic;
  bounded_buffer  *fhb =
    splitBuffer(b, _offset(nt_header_32, FileHeader), b->bufLen);

  if(fhb == NULL) {
    return false;
  }

  if(readFileHeader(fhb, header.FileHeader) == false) {
    deleteBuffer(fhb);
    return false;
  }

  bounded_buffer *ohb =
    splitBuffer(b, _offset(nt_header_32, OptionalHeader), b->bufLen);

  if(ohb == NULL) {
    deleteBuffer(fhb);
    return false;
  }

  if(readOptionalHeader(ohb, header.OptionalHeader) == false) {
    deleteBuffer(ohb);
    deleteBuffer(fhb);
    return false;
  }

  deleteBuffer(ohb);
  deleteBuffer(fhb);

  return true;
}

bool getHeader(bounded_buffer *file, pe_header &p, bounded_buffer *&rem) {
  if(file == NULL) {
    return false;
  }

  //start by reading MZ
  ::uint16_t  tmp = 0;
  ::uint32_t  curOffset = 0;
  readWord(file, curOffset, tmp);
  if(tmp != MZ_MAGIC) {
    return false;
  }

  //read the offset to the NT headers
  ::uint32_t  offset;
  if(readDword(file, _offset(dos_header, e_lfanew), offset) == false) {
    return false;
  }
  curOffset += offset;

  //now, we can read out the fields of the NT headers
  bounded_buffer  *ntBuf = splitBuffer(file, curOffset, file->bufLen);
  if(readNtHeader(ntBuf, p.nt) == false) {
    return false;
  }

  //update 'rem' to point to the space after the header
  rem = splitBuffer(ntBuf, sizeof(nt_header_32), ntBuf->bufLen);
  deleteBuffer(ntBuf);

  return true;
}

parsed_pe *ParsePEFromFile(const char *filePath) {
  //first, create a new parsed_pe structure
  parsed_pe *p = new parsed_pe();

  if(p == NULL) {
    return NULL;
  }

  //make a new buffer object to hold just our file data
  p->fileBuffer = readFileToFileBuffer(filePath);

  if(p->fileBuffer == NULL) {
    delete p;
    return NULL;
  }

  p->internal = new parsed_pe_internal();

  if(p->internal == NULL) {
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }

  //now, we need to do some actual PE parsing and file carving.

  //get header information
  bounded_buffer  *remaining = NULL;
  if(getHeader(p->fileBuffer, p->peHeader, remaining) == false) {
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }

  bounded_buffer  *file = p->fileBuffer;
  if(getSections(remaining, file, p->peHeader.nt, p->internal->secs) == false) {
    deleteBuffer(remaining);
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }

  //get raw section data

  //get exports

  //get relocations

  deleteBuffer(remaining);

  return p;
}

void DestructParsedPE(parsed_pe *p) {

  delete p;
  return;
}

//iterate over the imports by RVA and string
void IterImpRVAString(parsed_pe *pe, iterRVAStr cb, void *cbd) {

  return;
}

//iterate over relocations in the PE file
void IterRelocs(parsed_pe *pe, iterReloc cb, void *cbd) {

  return;
}

//iterate over the exports by RVA
void IterExpRVA(parsed_pe *pe, iterRVA cb, void *cbd) {

  return;
}

//iterate over sections
void IterSec(parsed_pe *pe, iterSec cb, void *cbd) {
  parsed_pe_internal  *pint = pe->internal;

  for(list<section>::iterator sit = pint->secs.begin(), e = pint->secs.end();
      sit != e;
      ++sit)
  {
    section s = *sit;
    cb(cbd, s.sectionBase, s.sectionName, s.sectionData);
  }

  return;
}
<commit_msg>add some more things<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013 Andrew Ruef

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <list>
#include "parse.h"
#include "nt-headers.h"

using namespace std;
using namespace boost;

struct section {
  string                sectionName;
  RVA                   sectionBase;
  bounded_buffer        *sectionData;
  image_section_header  sec;
};

struct reloc {
  RVA shiftedAddr;
  RVA shiftedTo;
};

struct parsed_pe_internal {
  list<section>   secs;
};

bool getSections( bounded_buffer  *b,
                  bounded_buffer  *fileBegin,
                  nt_header_32    &nthdr,
                  list<section>   &secs) {
  if(b == NULL) {
    return false;
  }

  //get each of the sections...
  for(::uint32_t i = 0; i < nthdr.FileHeader.NumberOfSections; i++) {
    image_section_header  curSec;

    ::uint32_t  o = i*sizeof(image_section_header);
    for(::uint32_t k = 0; k < NT_SHORT_NAME_LEN; k++) {
      readByte(b, o+k, curSec.Name[k]);
    }
#define READ_WORD(x) \
  if(readWord(b, o+_offset(image_section_header, x), curSec.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, o+_offset(image_section_header, x), curSec.x) == false) { \
    return false; \
  }

    READ_DWORD(VirtualAddress);
    READ_DWORD(SizeOfRawData);
    READ_DWORD(PointerToRawData);
    READ_DWORD(PointerToRelocations);
    READ_DWORD(PointerToLinenumbers);
    READ_WORD(NumberOfRelocations);
    READ_WORD(NumberOfLinenumbers);
    READ_DWORD(Characteristics);
#undef READ_WORD
#undef READ_DWORD

    //now we have the section header information, so fill in a section
    //object appropriately
    section thisSec;
    for(::uint32_t i = 0; i < NT_SHORT_NAME_LEN; i++) {
      ::uint8_t c = curSec.Name[i];
      if(c == 0) {
        break;
      }

      thisSec.sectionName.push_back((char)c);
    }

    thisSec.sectionBase = nthdr.OptionalHeader.ImageBase+curSec.VirtualAddress;
    thisSec.sec = curSec;
    ::uint32_t  lowOff = curSec.PointerToRawData;
    ::uint32_t  highOff = lowOff+curSec.SizeOfRawData;
    thisSec.sectionData = splitBuffer(fileBegin, lowOff, highOff);

    secs.push_back(thisSec);
  }

  return true;
}

bool readOptionalHeader(bounded_buffer *b, optional_header_32 &header) {
#define READ_WORD(x) \
  if(readWord(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }
#define READ_BYTE(x) \
  if(readByte(b, _offset(optional_header_32, x), header.x) == false) { \
    return false; \
  }

  READ_WORD(Magic);

  if(header.Magic != NT_OPTIONAL_32_MAGIC) {
    return false;
  }

  READ_BYTE(MajorLinkerVersion);
  READ_BYTE(MinorLinkerVersion);
  READ_DWORD(SizeOfCode);
  READ_DWORD(SizeOfInitializedData);
  READ_DWORD(SizeOfUninitializedData);
  READ_DWORD(AddressOfEntryPoint);
  READ_DWORD(BaseOfCode);
  READ_DWORD(BaseOfData);
  READ_DWORD(ImageBase);
  READ_DWORD(SectionAlignment);
  READ_DWORD(FileAlignment);
  READ_WORD(MajorOperatingSystemVersion);
  READ_WORD(MinorOperatingSystemVersion);
  READ_WORD(MajorImageVersion);
  READ_WORD(MinorImageVersion);
  READ_WORD(MajorSubsystemVersion);
  READ_WORD(MinorSubsystemVersion);
  READ_DWORD(Win32VersionValue);
  READ_DWORD(SizeOfImage);
  READ_DWORD(SizeOfHeaders);
  READ_DWORD(CheckSum);
  READ_WORD(Subsystem);
  READ_WORD(DllCharacteristics);
  READ_DWORD(SizeOfStackReserve);
  READ_DWORD(SizeOfStackCommit);
  READ_DWORD(SizeOfHeapReserve);
  READ_DWORD(SizeOfHeapCommit);
  READ_DWORD(LoaderFlags);
  READ_DWORD(NumberOfRvaAndSizes);

#undef READ_WORD
#undef READ_DWORD
#undef READ_BYTE

  for(::uint32_t i = 0; i < header.NumberOfRvaAndSizes; i++) {
    ::uint32_t  c = (i*sizeof(data_directory));
    ::uint32_t  o;

    o = c + _offset(data_directory, VirtualAddress);
    if(readDword(b, o, header.DataDirectory[i].VirtualAddress) == false) {
      return false;
    }

    o = c+ _offset(data_directory, Size);
    if(readDword(b, o, header.DataDirectory[i].Size) == false) {
      return false;
    }
  }

  return true;
}

bool readFileHeader(bounded_buffer *b, file_header &header) {
#define READ_WORD(x) \
  if(readWord(b, _offset(file_header, x), header.x) == false) { \
    return false; \
  }
#define READ_DWORD(x) \
  if(readDword(b, _offset(file_header, x), header.x) == false) { \
    return false; \
  }

  READ_WORD(Machine);
  READ_WORD(NumberOfSections);
  READ_DWORD(TimeDateStamp);
  READ_DWORD(PointerToSymbolTable);
  READ_DWORD(NumberOfSymbols);
  READ_WORD(SizeOfOptionalHeader);
  READ_WORD(Characteristics);

#undef READ_DWORD
#undef READ_WORD
  return true;
}

bool readNtHeader(bounded_buffer *b, nt_header_32 &header) {
  if(b == NULL) {
    return false;
  }

  ::uint32_t  pe_magic;
  ::uint32_t  curOffset =0;
  if(readDword(b, curOffset, pe_magic) == false || pe_magic != NT_MAGIC) {
    return false;
  }

  header.Signature = pe_magic;
  bounded_buffer  *fhb =
    splitBuffer(b, _offset(nt_header_32, FileHeader), b->bufLen);

  if(fhb == NULL) {
    return false;
  }

  if(readFileHeader(fhb, header.FileHeader) == false) {
    deleteBuffer(fhb);
    return false;
  }

  bounded_buffer *ohb =
    splitBuffer(b, _offset(nt_header_32, OptionalHeader), b->bufLen);

  if(ohb == NULL) {
    deleteBuffer(fhb);
    return false;
  }

  if(readOptionalHeader(ohb, header.OptionalHeader) == false) {
    deleteBuffer(ohb);
    deleteBuffer(fhb);
    return false;
  }

  deleteBuffer(ohb);
  deleteBuffer(fhb);

  return true;
}

bool getHeader(bounded_buffer *file, pe_header &p, bounded_buffer *&rem) {
  if(file == NULL) {
    return false;
  }

  //start by reading MZ
  ::uint16_t  tmp = 0;
  ::uint32_t  curOffset = 0;
  readWord(file, curOffset, tmp);
  if(tmp != MZ_MAGIC) {
    return false;
  }

  //read the offset to the NT headers
  ::uint32_t  offset;
  if(readDword(file, _offset(dos_header, e_lfanew), offset) == false) {
    return false;
  }
  curOffset += offset;

  //now, we can read out the fields of the NT headers
  bounded_buffer  *ntBuf = splitBuffer(file, curOffset, file->bufLen);
  if(readNtHeader(ntBuf, p.nt) == false) {
    return false;
  }

  //update 'rem' to point to the space after the header
  rem = splitBuffer(ntBuf, sizeof(nt_header_32), ntBuf->bufLen);
  deleteBuffer(ntBuf);

  return true;
}

parsed_pe *ParsePEFromFile(const char *filePath) {
  //first, create a new parsed_pe structure
  parsed_pe *p = new parsed_pe();

  if(p == NULL) {
    return NULL;
  }

  //make a new buffer object to hold just our file data
  p->fileBuffer = readFileToFileBuffer(filePath);

  if(p->fileBuffer == NULL) {
    delete p;
    return NULL;
  }

  p->internal = new parsed_pe_internal();

  if(p->internal == NULL) {
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }

  //now, we need to do some actual PE parsing and file carving.

  //get header information
  bounded_buffer  *remaining = NULL;
  if(getHeader(p->fileBuffer, p->peHeader, remaining) == false) {
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }

  bounded_buffer  *file = p->fileBuffer;
  if(getSections(remaining, file, p->peHeader.nt, p->internal->secs) == false) {
    deleteBuffer(remaining);
    deleteBuffer(p->fileBuffer);
    delete p;
    return NULL;
  }
  //get exports

  //get relocations

  //get imports

  deleteBuffer(remaining);

  return p;
}

void DestructParsedPE(parsed_pe *p) {

  delete p;
  return;
}

//iterate over the imports by RVA and string
void IterImpRVAString(parsed_pe *pe, iterRVAStr cb, void *cbd) {

  return;
}

//iterate over relocations in the PE file
void IterRelocs(parsed_pe *pe, iterReloc cb, void *cbd) {

  return;
}

//iterate over the exports by RVA
void IterExpRVA(parsed_pe *pe, iterRVA cb, void *cbd) {

  return;
}

//iterate over sections
void IterSec(parsed_pe *pe, iterSec cb, void *cbd) {
  parsed_pe_internal  *pint = pe->internal;

  for(list<section>::iterator sit = pint->secs.begin(), e = pint->secs.end();
      sit != e;
      ++sit)
  {
    section s = *sit;
    cb(cbd, s.sectionBase, s.sectionName, s.sectionData);
  }

  return;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *  @file       merge_sort.hpp
 *  @author     Yue.Wang
 *  @date       23  Aug 2014
 *  @update     02  Dec 2014
 *  @version    3
 *  @remark     CLRS Algorithms implementation in C++ templates.
 ***************************************************************************/
#ifndef MERGE_SORT_HPP
#define MERGE_SORT_HPP

#include <vector>
#include "iterator.hpp"
#include <iostream>

namespace clrs {namespace ch2 {

/**
 * @brief merge
 * @param first
 * @param mid
 * @param last
 *
 * @pseudocode  MERGE, page 31, clrs.
 * @complx  O(n)
 */
template<typename Iter>
void merge(Iter first, Iter mid, Iter last )
{
    //! init
    using Vector = std::vector<clrs::IterValue<Iter>>;
    Vector left(first, mid), right(mid, last);
    auto l = left.cbegin(), r = right.cbegin();
    auto it = first;

    //! copy until either one reaches its end
    for(; l != left.end() and r != right.end();  *it++ = *(*r < *l ? r : l)++);

    //! copy the rest.
    for(auto rest = (l == left.end() ? r : l);  it != last;  *it++ = *rest++);
}

/**
 * @brief merge_sort
 * @param first
 * @param last
 *
 * @pseudocode  MERGE-SORT, page 34, clrs.
 * @complx  O(n lg n)
 */
template<typename Iter>
void merge_sort(Iter first, Iter last)
{
    if(first + 1 < last )
    {
        auto mid = first + (last - first)/2;
        merge_sort(first, mid );
        merge_sort(mid  , last);
        merge(first, mid, last);
    }
}

}}//namespace
#endif // MERGE_SORT_HPP

//! @test   merge sort
//!
//#include <iostream>
//#include <vector>
//#include "alan.hpp"
//#include "merge_sort.hpp"

//int main()
//{
//    std::vector<std::string> v{"99","22","z55","s11","b33"};

//    clrs::ch2::merge_sort(v.begin(), v.end());
//    alan::print_container(v);

//    alan::end();
//    return 0;
//}

//! @output
//!
//22 99 b33 s11 z55
//exit normally
<commit_msg>	modified:   ch02/merge_sort.hpp<commit_after>/***************************************************************************
 *  @file       merge_sort.hpp
 *  @author     Yue.Wang
 *  @date       23  Aug 2014
 *  @update     02  Dec 2014
 *  @version    3
 *  @remark     CLRS Algorithms implementation in C++ templates.
 ***************************************************************************/
#ifndef MERGE_SORT_HPP
#define MERGE_SORT_HPP

#include <vector>
#include "iterator.hpp"
#include <iostream>

namespace clrs {namespace ch2 {

/**
 * @brief merge
 * @param first
 * @param mid
 * @param last
 *
 * @pseudocode  MERGE, page 31, clrs.
 * @complx  O(n)
 */
template<typename Iter>
void merge(Iter first, Iter mid, Iter last )
{
    using Vector = std::vector<clrs::IterValue<Iter>>;
    Vector left(first, mid), right(mid, last);
    auto l = left.cbegin(), r = right.cbegin();
    auto it = first;

    //! compare and copy, until either one exausted
    for(; l != left.end() and r != right.end();  *it++ = *(*r < *l ? r : l)++);

    //! copy the rest.
    for(auto rest = (l == left.end() ? r : l);  it != last;  *it++ = *rest++);
}

/**
 * @brief merge_sort
 * @param first
 * @param last
 *
 * @pseudocode  MERGE-SORT, page 34, clrs.
 * @complx  O(n lg n)
 */
template<typename Iter>
void merge_sort(Iter first, Iter last)
{
    if(first+1 < last){
        auto mid = first + (last-first)/2;
        merge_sort(first, mid );
        merge_sort(mid  , last);
        merge(first, mid, last);
    }
}

}}//namespace
#endif // MERGE_SORT_HPP

//! @test   merge sort
//!
//#include <iostream>
//#include <vector>
//#include "alan.hpp"
//#include "merge_sort.hpp"

//int main()
//{
//    std::vector<std::string> v{"99","22","z55","s11","b33"};

//    clrs::ch2::merge_sort(v.begin(), v.end());
//    alan::print_container(v);

//    alan::end();
//    return 0;
//}

//! @output
//!
//22 99 b33 s11 z55
//exit normally
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "asset.h"
#include "game.h"

#include <core/metainfo.h>

#include <QtGui/QAction>
#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QMimeData>

REGISTER_OBJECTTYPE( GluonEngine, Asset )

using namespace GluonEngine;

class GluonEngine::AssetPrivate
{
    public:
        AssetPrivate()
            : loaded( false )
            , mime( new QMimeData )
        {
        }

        QUrl file;
        bool loaded;
        QMimeData* mime;
};

Asset::Asset( QObject* parent )
    : GluonObject( parent )
    , d( new AssetPrivate )
{
}

Asset::~Asset()
{
    delete d->mime;
    delete d;
}

void
Asset::setName( const QString& newName )
{
    QString oldName( name() );

    GluonCore::GluonObject::setName( newName );

    // Rename the underlying file, if one exists...
    if( !d->file.isEmpty() )
    {
        // If we use QDir::current(), .exists will throw debug crap... this works around that particular annoyance
        if( QDir( QDir::currentPath() ).exists( d->file.toLocalFile() ) )
        {
            QUrl newFile = Asset::fullyQualifiedFileName( this, QFileInfo( d->file.toLocalFile() ).completeSuffix() );

            QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
            QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
            QDir::current().mkpath( newPath );

            if( QDir::current().rename( d->file.toLocalFile(), newFile.toLocalFile() ) )
            {
                if( QDir::current().exists( oldPath ) )
                    QDir::current().rmpath( oldPath );
                setFile( newFile );
            }
        }
    }
}

void
Asset::setFile( const QUrl& newFile )
{
    if( !d->file.isEmpty() )
    {
        QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
        if( QDir::current().exists( oldPath ) )
            QDir::current().rmpath( oldPath );
    }
    QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
    QDir::current().mkpath( newPath );
    d->file = newFile;
    emit dataChanged();
}

QUrl
Asset::file() const
{
    return d->file;
}

QString
Asset::absolutePath() const
{
    return GluonEngine::Game::instance()->gameProject()->dirname().toLocalFile() + '/' + d->file.toLocalFile();
}

QIcon
Asset::icon() const
{
    return QIcon();
}

const QMimeData*
Asset::data() const
{
    return d->mime;
}

QMimeData* Asset::dragData() const
{
    DEBUG_BLOCK
    QMimeData* data = new QMimeData();
    QByteArray encodedData;
    QDataStream stream( &encodedData, QIODevice::WriteOnly );
    stream << fullyQualifiedName();
    data->setData( QString("application/gluon.engine.").append(metaObject()->className()), encodedData );
    DEBUG_TEXT(data->formats().join(","));
    return data;
}

const QList<AssetTemplate*>
Asset::templates()
{
    QList<AssetTemplate*> templates;
    return templates;
}

QList<QAction*>
Asset::actions()
{
    return QList<QAction*>();
}

bool
Asset::isLoaded() const
{
    return d->loaded;
}

void
Asset::load()
{
    d->loaded = true;
    emit dataChanged();
}

void Asset::unload()
{
    d->loaded = false;
}

void
Asset::reload()
{
    unload();
    load();
}

bool
Asset::shouldSerializeChildren( ) const
{
    // We do not recurse here - this allows the assets to handle their own
    // children
    return false;
}

QMimeData*
Asset::mimeData() const
{
    return d->mime;
}

void
Asset::setLoaded( bool loaded )
{
    d->loaded = loaded;
}

QUrl
Asset::fullyQualifiedFileName( GluonCore::GluonObject* obj, const QString& extension )
{
    DEBUG_FUNC_NAME
    QStringList parts = obj->fullyQualifiedName().split( '/' );
    if( parts.count() > 1 && parts.first() == obj->gameProject()->name() )
        parts.removeFirst();

    QRegExp filter( "[^a-z0-9_]+" );

    QString file = parts.last().toLower().replace( ' ', '_' ).remove( filter );
    parts.removeLast();

    QStringList path;
    foreach( const QString & part, parts )
    {
        path.append( part.toLower().replace( ' ', '_' ).remove( filter ) );
    }

    QString dir = path.join( "/" );
    if( dir.length() > 0 )
        dir.append( '/' );

    QString ext = extension.isEmpty() ? obj->metaInfo()->defaultExtension() : extension;
    return QUrl( QString( "%1%2.%3" ).arg( dir, file, ext ) );
}

#include "asset.moc"

<commit_msg>Fix the extension handling while importing an asset<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "asset.h"
#include "game.h"

#include <core/metainfo.h>

#include <QtGui/QAction>
#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QMimeData>

REGISTER_OBJECTTYPE( GluonEngine, Asset )

using namespace GluonEngine;

class GluonEngine::AssetPrivate
{
    public:
        AssetPrivate()
            : loaded( false )
            , mime( new QMimeData )
        {
        }

        QUrl file;
        bool loaded;
        QMimeData* mime;
};

Asset::Asset( QObject* parent )
    : GluonObject( parent )
    , d( new AssetPrivate )
{
}

Asset::~Asset()
{
    delete d->mime;
    delete d;
}

void
Asset::setName( const QString& newName )
{
    QString oldName( name() );

    GluonCore::GluonObject::setName( newName );

    // Rename the underlying file, if one exists...
    if( !d->file.isEmpty() )
    {
        // If we use QDir::current(), .exists will throw debug crap... this works around that particular annoyance
        if( QDir( QDir::currentPath() ).exists( d->file.toLocalFile() ) )
        {
            QUrl newFile = Asset::fullyQualifiedFileName( this, QFileInfo( d->file.toLocalFile() ).completeSuffix() );

            QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
            QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
            QDir::current().mkpath( newPath );

            if( QDir::current().rename( d->file.toLocalFile(), newFile.toLocalFile() ) )
            {
                if( QDir::current().exists( oldPath ) )
                    QDir::current().rmpath( oldPath );
                setFile( newFile );
            }
        }
    }
}

void
Asset::setFile( const QUrl& newFile )
{
    if( !d->file.isEmpty() )
    {
        QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
        if( QDir::current().exists( oldPath ) )
            QDir::current().rmpath( oldPath );
    }
    QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
    QDir::current().mkpath( newPath );
    d->file = newFile;
    emit dataChanged();
}

QUrl
Asset::file() const
{
    return d->file;
}

QString
Asset::absolutePath() const
{
    return GluonEngine::Game::instance()->gameProject()->dirname().toLocalFile() + '/' + d->file.toLocalFile();
}

QIcon
Asset::icon() const
{
    return QIcon();
}

const QMimeData*
Asset::data() const
{
    return d->mime;
}

QMimeData* Asset::dragData() const
{
    DEBUG_BLOCK
    QMimeData* data = new QMimeData();
    QByteArray encodedData;
    QDataStream stream( &encodedData, QIODevice::WriteOnly );
    stream << fullyQualifiedName();
    data->setData( QString("application/gluon.engine.").append(metaObject()->className()), encodedData );
    DEBUG_TEXT(data->formats().join(","));
    return data;
}

const QList<AssetTemplate*>
Asset::templates()
{
    QList<AssetTemplate*> templates;
    return templates;
}

QList<QAction*>
Asset::actions()
{
    return QList<QAction*>();
}

bool
Asset::isLoaded() const
{
    return d->loaded;
}

void
Asset::load()
{
    d->loaded = true;
    emit dataChanged();
}

void Asset::unload()
{
    d->loaded = false;
}

void
Asset::reload()
{
    unload();
    load();
}

bool
Asset::shouldSerializeChildren( ) const
{
    // We do not recurse here - this allows the assets to handle their own
    // children
    return false;
}

QMimeData*
Asset::mimeData() const
{
    return d->mime;
}

void
Asset::setLoaded( bool loaded )
{
    d->loaded = loaded;
}

QUrl
Asset::fullyQualifiedFileName( GluonCore::GluonObject* obj, const QString& extension )
{
    DEBUG_FUNC_NAME
    QStringList parts = obj->fullyQualifiedName().split( '/' );
    if( parts.count() > 1 && parts.first() == obj->gameProject()->name() )
        parts.removeFirst();

    QString fileExtension = parts.last().section(".", -1, -1, QString::SectionIncludeLeadingSep);
    if (fileExtension == QString(".%1").arg(extension))
        parts.last().remove(fileExtension);

    QRegExp filter( "[^a-z0-9_]+" );

    QString file = parts.last().toLower().replace( ' ', '_' ).remove( filter );
    parts.removeLast();

    QStringList path;
    foreach( const QString & part, parts )
    {
        path.append( part.toLower().replace( ' ', '_' ).remove( filter ) );
    }

    QString dir = path.join( "/" );
    if( dir.length() > 0 )
        dir.append( '/' );

    QString ext = extension.isEmpty() ? obj->metaInfo()->defaultExtension() : extension;
    return QUrl( QString( "%1%2.%3" ).arg( dir, file, ext ) );
}

#include "asset.moc"

<|endoftext|>


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

#ifndef _OSL_MUTEX_HXX_ //autogen wg. ::osl::Mutex
#include <osl/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

namespace comphelper
{
    namespace stario    = ::com::sun::star::io;
    namespace staruno   = ::com::sun::star::uno;

//==================================================================
// FmUnoIOStream,
// stream zum schreiben un lesen von Daten, basieren  auf File
//==================================================================
typedef ::cppu::WeakImplHelper1<stario::XInputStream> InputStreamWrapper_Base;
    // needed for some compilers
class OSLInputStreamWrapper : public InputStreamWrapper_Base
{
    ::osl::Mutex    m_aMutex;
    ::osl::File*    m_pFile;
    sal_Bool        m_bFileOwner : 1;

public:
    OSLInputStreamWrapper(::osl::File& _rStream);
    OSLInputStreamWrapper(::osl::File* pStream, sal_Bool bOwner=sal_False);
    virtual ~OSLInputStreamWrapper();

// UNO Anbindung
    virtual void            SAL_CALL acquire() throw()
        { InputStreamWrapper_Base::acquire(); }
    virtual void            SAL_CALL release() throw()
        { InputStreamWrapper_Base::release(); }
    virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException)
        { return InputStreamWrapper_Base::queryInterface(_rType); }

// stario::XInputStream
    virtual sal_Int32   SAL_CALL    readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual sal_Int32   SAL_CALL    readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void        SAL_CALL    skipBytes(sal_Int32 nBytesToSkip) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual sal_Int32   SAL_CALL    available() throw(stario::NotConnectedException, staruno::RuntimeException);
    virtual void        SAL_CALL    closeInput() throw(stario::NotConnectedException, staruno::RuntimeException);
};

//==================================================================
// FmUnoOutStream,
// Datensenke fuer Files
//==================================================================
typedef ::cppu::WeakImplHelper1<stario::XOutputStream> OutputStreamWrapper_Base;
    // needed for some compilers
class OSLOutputStreamWrapper : public OutputStreamWrapper_Base
{
    ::osl::File&        rFile;

public:
    OSLOutputStreamWrapper(::osl::File& _rFile) :rFile(_rFile) { }

// UNO Anbindung
    virtual void            SAL_CALL acquire() throw()
        { OutputStreamWrapper_Base::acquire(); }
    virtual void            SAL_CALL release() throw()
        { OutputStreamWrapper_Base::release(); }
    virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException)
        { return OutputStreamWrapper_Base::queryInterface(_rType); }

// stario::XOutputStream
    virtual void SAL_CALL writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void SAL_CALL flush() throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void SAL_CALL closeOutput() throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
};

}   // namespace comphelper

#endif // _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_

<commit_msg>INTEGRATION: CWS visibility02 (1.2.260); FILE MERGED 2005/01/28 10:59:44 mhu 1.2.260.1: #i38608# More classes / symbols need to be exported.<commit_after>/*************************************************************************
 *
 *  $RCSfile: oslfile2streamwrap.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 15:57:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_
#define _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_

#ifndef _OSL_MUTEX_HXX_ //autogen wg. ::osl::Mutex
#include <osl/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

namespace comphelper
{
    namespace stario    = ::com::sun::star::io;
    namespace staruno   = ::com::sun::star::uno;

//==================================================================
// FmUnoIOStream,
// stream zum schreiben un lesen von Daten, basieren  auf File
//==================================================================
struct InputStreamWrapper_Base : public ::cppu::WeakImplHelper1<stario::XInputStream>
{};

class COMPHELPER_DLLPUBLIC OSLInputStreamWrapper : public InputStreamWrapper_Base
{
    ::osl::Mutex    m_aMutex;
    ::osl::File*    m_pFile;
    sal_Bool        m_bFileOwner : 1;

public:
    OSLInputStreamWrapper(::osl::File& _rStream);
    OSLInputStreamWrapper(::osl::File* pStream, sal_Bool bOwner=sal_False);
    virtual ~OSLInputStreamWrapper();

// UNO Anbindung
    virtual void            SAL_CALL acquire() throw()
        { InputStreamWrapper_Base::acquire(); }
    virtual void            SAL_CALL release() throw()
        { InputStreamWrapper_Base::release(); }
    virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException)
        { return InputStreamWrapper_Base::queryInterface(_rType); }

// stario::XInputStream
    virtual sal_Int32   SAL_CALL    readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual sal_Int32   SAL_CALL    readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void        SAL_CALL    skipBytes(sal_Int32 nBytesToSkip) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual sal_Int32   SAL_CALL    available() throw(stario::NotConnectedException, staruno::RuntimeException);
    virtual void        SAL_CALL    closeInput() throw(stario::NotConnectedException, staruno::RuntimeException);
};

//==================================================================
// FmUnoOutStream,
// Datensenke fuer Files
//==================================================================
struct OutputStreamWrapper_Base : public ::cppu::WeakImplHelper1<stario::XOutputStream>
{};

class COMPHELPER_DLLPUBLIC OSLOutputStreamWrapper : public OutputStreamWrapper_Base
{
    ::osl::File&        rFile;

public:
    OSLOutputStreamWrapper(::osl::File& _rFile) :rFile(_rFile) { }

// UNO Anbindung
    virtual void            SAL_CALL acquire() throw()
        { OutputStreamWrapper_Base::acquire(); }
    virtual void            SAL_CALL release() throw()
        { OutputStreamWrapper_Base::release(); }
    virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException)
        { return OutputStreamWrapper_Base::queryInterface(_rType); }

// stario::XOutputStream
    virtual void SAL_CALL writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void SAL_CALL flush() throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
    virtual void SAL_CALL closeOutput() throw(stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException);
};

}   // namespace comphelper

#endif // _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_

<|endoftext|>