<commit_before>
/*
 * testCounter.cpp
 *
 *      Author: Peter Johansson
 */
#ifdef _MOCK_

#include "gtest/gtest.h"
#include "../src/CalvinDone/CalvinMini.h"
#include "../src/CalvinDone/Actors.h"

class testCounter : public ::testing::Test {
protected:
	virtual void SetUp() {}
	virtual void TearDown() {}
};

TEST(testCounter, testReceiveCounter)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-miniscule\", \"from_rt_uuid\": \"422828ae-02c1-4d2f-9837-43a32fb6decb\""
                 ", \"state\": {\"prev_connections\": {\"actor_name\": \"test3:src\", \"inports\": {}, \"actor_id\": \"6bc4b467-a2d2-4254-ad84-bf918231c68e\""
                 ", \"outports\": {\"f4822772-bca4-465c-8109-a1e7a960e304\": [[\"422828ae-02c1-4d2f-9837-43a32fb6decb\", \"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\"]]}}"
                 ", \"actor_type\": \"std.Counter\", \"actor_state\": {\"count\": 117, \"name\": \"test3:src\", \"inports\": {}, \"_managed\": [\"count\", \"id\", \"name\"]"
                 ", \"outports\": {\"integer\": {\"fanout\": 1, \"name\": \"integer\", \"fifo\": {\"write_pos\": 117, \"readers\": [\"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\"]"
                 ", \"fifo\": [{\"data\": 113, \"type\": \"Token\"}, {\"data\": 114, \"type\": \"Token\"}, {\"data\": 115, \"type\": \"Token\"}"
                 ", {\"data\": 116, \"type\": \"Token\"}, {\"data\": 117, \"type\": \"Token\"}], \"N\": 5, \"tentative_read_pos\": {\"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\": 113}"
                 ", \"read_pos\": {\"98f7f8ad-f4d3-44ae-9228-7228a54c2fee3\": 113}}, \"id\": \"f4822772-bca4-465c-8109-a1e7a960e304\"}}"
                 ", \"id\": \"6bc4b467-a2d2-4254-ad84-bf918231c68e\"}}, \"cmd\": \"ACTOR_NEW\", \"msg_uuid\": \"fd71b46d-0e44-4298-9bb3-61aa0420bc45\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    // Test what number arduino should start counting from
    JsonObject &fifoObject = msg["state"]["actor_state"]["outports"]["integer"]["fifo"];
    JsonArray &fifoArray = fifoObject.get("fifo");
    JsonObject &count = fifoArray.get(0);
    EXPECT_EQ(113,(uint32_t)count.get("data"));

    int8_t size = mini.handleMsg(msg, reply, request, 0);
    JsonObject &actor_state = msg["state"]["actor_state"];

    // Test if number of outgoing messages is 2
    EXPECT_EQ(size,2);

    // Test if actor_type Counter is triggered
    EXPECT_STREQ("std.Counter", msg["state"]["actor_type"]);

    // Test if actor_state contains key count
    // which should be true when actor is Counter
    EXPECT_TRUE(actor_state.containsKey("count"));

    // Test if PORT_CONNECT is returned cmd
    // which it should be after an actor migrate
    EXPECT_STREQ("PORT_CONNECT", request["cmd"]);

    // Test part of actor type name
    const char *p = msg["state"]["actor_type"].asString();
    String str2 = "";
    while(*p != '.')
    {
       str2 += *p;
       p++;
    }
    EXPECT_STREQ("std", str2.c_str());

    // Test part of actor type name
    uint8_t actorBool = !strncmp("std", msg["state"]["actor_type"].asString(), 3);
    EXPECT_EQ(1, actorBool);
}

TEST(testCounter, testCounterACK)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"babc045f-5da1-4eb1-a08e-95e6a272cfde\""
                 ", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 0, \"peer_port_id\": \"50017184-4e7f-4f76-8c39-9e1f35f59b46\""
                 ", \"cmd\": \"TOKEN_REPLY\", \"port_id\": \"be1fbbb2-9fb3-4bac-bb94-0e601f2df6df\", \"value\": \"ACK\"}, \"tunnel_id\": \"fake-tunnel\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    int8_t size = mini.handleMsg(msg, reply, request, 0);

    // Test if number of outgoing messages is 1
    EXPECT_EQ(size, 1);

    JsonObject &value = reply.get("value");
    int sequencenbr = value.get("sequencenbr");

    // Test if sequencenbr is updated from 0 to 1 when ACK from base
    EXPECT_EQ(1, sequencenbr);
}

TEST(testCounter, testCounterNACK)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"babc045f-5da1-4eb1-a08e-95e6a272cfde\""
                 ", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 0, \"peer_port_id\": \"50017184-4e7f-4f76-8c39-9e1f35f59b46\""
                 ", \"cmd\": \"TOKEN_REPLY\", \"port_id\": \"be1fbbb2-9fb3-4bac-bb94-0e601f2df6df\", \"value\": \"NACK\"}, \"tunnel_id\": \"fake-tunnel\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    int8_t size = mini.handleMsg(msg, reply, request, 0);

    // Test if number of outgoing messages is 1
    EXPECT_EQ(size, 1);

    JsonObject &value = reply.get("value");
    int sequencenbr = value.get("sequencenbr");

    // Test if sequencenbr is unchanged from 0 when NACK from base
    EXPECT_EQ(0, sequencenbr);
}

TEST(testCounter,testCounting)
{
	CalvinMini mini;
	actor testActor;
	fifo testFifo;
	initFifo(&testFifo);
	testActor.inportsFifo[0] = testFifo;
	fifoPop(&testActor.inportsFifo[0]);
	testActor.count = 0;
	EXPECT_EQ(0,testActor.count);
	EXPECT_EQ(0,actorCount(&testActor));
	EXPECT_EQ(1,testActor.count);
	fifoPop(&testActor.inportsFifo[0]);
	testActor.count = 0;
	for(int i = 0; i < 1000; i++){
		actorCount(&testActor);
		EXPECT_EQ(i+1,fifoPop(&testActor.inportsFifo[0]));
	}
	EXPECT_EQ(1000,testActor.count);

}

#endif
<commit_msg>Fixed strncmp in if<commit_after>
/*
 * testCounter.cpp
 *
 *      Author: Peter Johansson
 */
#ifdef _MOCK_

#include "gtest/gtest.h"
#include "../src/CalvinDone/CalvinMini.h"
#include "../src/CalvinDone/Actors.h"

class testCounter : public ::testing::Test {
protected:
	virtual void SetUp() {}
	virtual void TearDown() {}
};

TEST(testCounter, testReceiveCounter)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-miniscule\", \"from_rt_uuid\": \"422828ae-02c1-4d2f-9837-43a32fb6decb\""
                 ", \"state\": {\"prev_connections\": {\"actor_name\": \"test3:src\", \"inports\": {}, \"actor_id\": \"6bc4b467-a2d2-4254-ad84-bf918231c68e\""
                 ", \"outports\": {\"f4822772-bca4-465c-8109-a1e7a960e304\": [[\"422828ae-02c1-4d2f-9837-43a32fb6decb\", \"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\"]]}}"
                 ", \"actor_type\": \"std.Counter\", \"actor_state\": {\"count\": 117, \"name\": \"test3:src\", \"inports\": {}, \"_managed\": [\"count\", \"id\", \"name\"]"
                 ", \"outports\": {\"integer\": {\"fanout\": 1, \"name\": \"integer\", \"fifo\": {\"write_pos\": 117, \"readers\": [\"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\"]"
                 ", \"fifo\": [{\"data\": 113, \"type\": \"Token\"}, {\"data\": 114, \"type\": \"Token\"}, {\"data\": 115, \"type\": \"Token\"}"
                 ", {\"data\": 116, \"type\": \"Token\"}, {\"data\": 117, \"type\": \"Token\"}], \"N\": 5, \"tentative_read_pos\": {\"98f7f8ad-f4d3-44ae-9228-728a54c2fee3\": 113}"
                 ", \"read_pos\": {\"98f7f8ad-f4d3-44ae-9228-7228a54c2fee3\": 113}}, \"id\": \"f4822772-bca4-465c-8109-a1e7a960e304\"}}"
                 ", \"id\": \"6bc4b467-a2d2-4254-ad84-bf918231c68e\"}}, \"cmd\": \"ACTOR_NEW\", \"msg_uuid\": \"fd71b46d-0e44-4298-9bb3-61aa0420bc45\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    // Test what number arduino should start counting from
    JsonObject &fifoObject = msg["state"]["actor_state"]["outports"]["integer"]["fifo"];
    JsonArray &fifoArray = fifoObject.get("fifo");
    JsonObject &count = fifoArray.get(0);
    EXPECT_EQ(113,(uint32_t)count.get("data"));

    int8_t size = mini.handleMsg(msg, reply, request, 0);
    JsonObject &actor_state = msg["state"]["actor_state"];

    // Test if number of outgoing messages is 2
    EXPECT_EQ(size,2);

    // Test if actor_type Counter is triggered
    EXPECT_STREQ("std.Counter", msg["state"]["actor_type"]);

    // Test if actor_state contains key count
    // which should be true when actor is Counter
    EXPECT_TRUE(actor_state.containsKey("count"));

    // Test if PORT_CONNECT is returned cmd
    // which it should be after an actor migrate
    EXPECT_STREQ("PORT_CONNECT", request["cmd"]);

    // Test code that searches for a '.' and
    // builds a string of the actor type name
    const char *p = msg["state"]["actor_type"].asString();
    String str2 = "";
    while(*p != '.')
    {
       str2 += *p;
       p++;
    }
    EXPECT_STREQ("std", str2.c_str());

    // Test code that compares part of actor type name
    uint8_t actorBool = !strncmp("std", msg["state"]["actor_type"].asString(), 3);
    EXPECT_EQ(1, actorBool);
}

TEST(testCounter, testCounterACK)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"babc045f-5da1-4eb1-a08e-95e6a272cfde\""
                 ", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 0, \"peer_port_id\": \"50017184-4e7f-4f76-8c39-9e1f35f59b46\""
                 ", \"cmd\": \"TOKEN_REPLY\", \"port_id\": \"be1fbbb2-9fb3-4bac-bb94-0e601f2df6df\", \"value\": \"ACK\"}, \"tunnel_id\": \"fake-tunnel\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    int8_t size = mini.handleMsg(msg, reply, request, 0);

    // Test if number of outgoing messages is 1
    EXPECT_EQ(size, 1);

    JsonObject &value = reply.get("value");
    int sequencenbr = value.get("sequencenbr");

    // Test if sequencenbr is updated from 0 to 1 when ACK from base
    EXPECT_EQ(1, sequencenbr);
}

TEST(testCounter, testCounterNACK)
{
    CalvinMini mini;
    String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"babc045f-5da1-4eb1-a08e-95e6a272cfde\""
                 ", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 0, \"peer_port_id\": \"50017184-4e7f-4f76-8c39-9e1f35f59b46\""
                 ", \"cmd\": \"TOKEN_REPLY\", \"port_id\": \"be1fbbb2-9fb3-4bac-bb94-0e601f2df6df\", \"value\": \"NACK\"}, \"tunnel_id\": \"fake-tunnel\"}";

    StaticJsonBuffer<4096> jsonBuffer;
    JsonObject &msg = jsonBuffer.parseObject(str.c_str());
    JsonObject &reply = jsonBuffer.createObject();
    JsonObject &request = jsonBuffer.createObject();

    int8_t size = mini.handleMsg(msg, reply, request, 0);

    // Test if number of outgoing messages is 1
    EXPECT_EQ(size, 1);

    JsonObject &value = reply.get("value");
    int sequencenbr = value.get("sequencenbr");

    // Test if sequencenbr is unchanged from 0 when NACK from base
    EXPECT_EQ(0, sequencenbr);
}

TEST(testCounter,testCounting)
{
	CalvinMini mini;
	actor testActor;
	fifo testFifo;
	initFifo(&testFifo);
	testActor.inportsFifo[0] = testFifo;
	fifoPop(&testActor.inportsFifo[0]);
	testActor.count = 0;
	EXPECT_EQ(0,testActor.count);
	EXPECT_EQ(0,actorCount(&testActor));
	EXPECT_EQ(1,testActor.count);
	fifoPop(&testActor.inportsFifo[0]);
	testActor.count = 0;
	for(int i = 0; i < 1000; i++){
		actorCount(&testActor);
		EXPECT_EQ(i+1,fifoPop(&testActor.inportsFifo[0]));
	}
	EXPECT_EQ(1000,testActor.count);

}

#endif
<|endoftext|>


<commit_before>
#include "Buffer.cpp"

#include <thread>

void test1() {
	Buffer buf;

#define N 10000
	// We want to force multiple buffer chunks.
	assert(N * sizeof(uint32_t) > BUFFER_CHUNK_SIZE);

	auto producer_ = [&buf](int start, int end){
		for(uint32_t i = start; i < end; ++i) {
			buf.push((uint8_t*)&i, sizeof(uint32_t));
		}
	};
	auto producer = [&]() { producer_(0, N); };

	auto consumer = [&buf](){
		for(uint32_t i = 0; i < N; ++i) {
			int ret;
			while(buf.size() < sizeof(uint32_t)); // wait for entry
			size_t c = buf.pop((uint8_t*)&ret, sizeof(uint32_t));
			assert(c == sizeof(uint32_t));
			assert(ret == i);
		}
	};

	for(int i = 0; i < 3; ++i) {
		producer();
		assert(buf.size() == N * sizeof(int));
		consumer();
		assert(buf.empty());
	}

	for(int i = 0; i < 1000; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}

	for(int i = 0; i < 1000; ++i) {
		producer_(0, N/2);
		std::thread t1([&](){ producer_(N/2, N); }), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}
}

int main() {
	test1();
}
<commit_msg>less testing. takes long<commit_after>
#include "Buffer.cpp"

#include <thread>

void test1() {
	Buffer buf;

#define N 10000
	// We want to force multiple buffer chunks.
	assert(N * sizeof(uint32_t) > BUFFER_CHUNK_SIZE);

	auto producer_ = [&buf](int start, int end){
		for(uint32_t i = start; i < end; ++i) {
			buf.push((uint8_t*)&i, sizeof(uint32_t));
		}
	};
	auto producer = [&]() { producer_(0, N); };

	auto consumer = [&buf](){
		for(uint32_t i = 0; i < N; ++i) {
			int ret;
			while(buf.size() < sizeof(uint32_t)); // wait for entry
			size_t c = buf.pop((uint8_t*)&ret, sizeof(uint32_t));
			assert(c == sizeof(uint32_t));
			assert(ret == i);
		}
	};

	for(int i = 0; i < 3; ++i) {
		producer();
		assert(buf.size() == N * sizeof(int));
		consumer();
		assert(buf.empty());
	}

	for(int i = 0; i < 30; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}

	for(int i = 0; i < 10; ++i) {
		producer_(0, N/2);
		std::thread t1([&](){ producer_(N/2, N); }), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}
}

int main() {
	test1();
}
<|endoftext|>


<commit_before>#include "gui/mainwindow.h"
#include <QApplication>
#include <QFile>
#include "blocktypesreader.h"
#include "gui/applicationdata.h"
#include "flowchart/blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // error message
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(bytes);
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    appData.blockTypes = BlockTypes_fromJson(nodeArray);

    MainWindow w(appData);
    w.show();

    return a.exec();
}
<commit_msg>Fix nonexistant include in main<commit_after>#include "gui/mainwindow.h"
#include <QApplication>
#include <QFile>
#include "gui/applicationdata.h"
#include "flowchart/blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // error message
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(bytes);
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    appData.blockTypes = BlockTypes_fromJson(nodeArray);

    MainWindow w(appData);
    w.show();

    return a.exec();
}
<|endoftext|>


<commit_before>/*=============================================================================
	Copyright (c) 2012-2013 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// N-Dimensional uniform grid

#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID

#include <vector>
#include <numeric>

struct NDGrid {
	template <typename Func> static void apply(
			const double& min_extent,
			const double& max_extent,
			const std::size_t& dimension,
			const double& grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == dimension) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				apply(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
			}
		}
	}
	template <typename Func> static inline void apply(
			const double& min_extent,
			const double& max_extent,
			const std::size_t& dimension,
			const double& grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		apply(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
	}
};

#endif
<commit_msg>Don't pass primitives by const reference<commit_after>/*=============================================================================
	Copyright (c) 2012-2013 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// N-Dimensional uniform grid

#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID

#include <vector>
#include <numeric>

struct NDGrid {
	template <typename Func> static void apply(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == dimension) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				apply(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
			}
		}
	}
	template <typename Func> static inline void apply(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		apply(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
	}
};

#endif
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectmanagerconstants.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojecttarget.h"
#include "projectexplorer/projectexplorer.h"

#include <coreplugin/mimedatabase.h>
#include <projectexplorer/buildconfiguration.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <coreplugin/ifile.h>
#include <utils/synchronousprocess.h>
#include <utils/pathchooser.h>

#include <QFormLayout>
#include <QComboBox>
#include <QCoreApplication>
#include <QLineEdit>
#include <QSpinBox>
#include <QStringListModel>
#include <QDebug>

namespace QmlProjectManager {

QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) :
    ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)),
    m_debugServerAddress("127.0.0.1"),
    m_debugServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT),
    m_fileListModel(new QStringListModel(this)),
    m_projectTarget(parent),
    m_usingCurrentFile(true),
    m_isEnabled(false)
{
    ctor();
}

QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) :
    ProjectExplorer::RunConfiguration(parent, source),
    m_scriptFile(source->m_scriptFile),
    m_qmlViewerCustomPath(source->m_qmlViewerCustomPath),
    m_qmlViewerArgs(source->m_qmlViewerArgs),
    m_debugServerAddress(source->m_debugServerAddress),
    m_debugServerPort(source->m_debugServerPort)
{
    ctor();
}

bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const
{
    Q_UNUSED(bc);

    if (!QFile::exists(mainScript())
        || !Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml")))
    {
        return false;
    }
    return true;
}

void QmlProjectRunConfiguration::ctor()
{
    Core::EditorManager *em = Core::EditorManager::instance();
    connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(changeCurrentFile(Core::IEditor*)));

    setDisplayName(tr("QML Runtime", "QMLRunConfiguration display name."));

    // prepend creator/bin dir to search path (only useful for special creator-qml package)
    const QString searchPath = QCoreApplication::applicationDirPath()
                               + Utils::SynchronousProcess::pathSeparator()
                               + QString(qgetenv("PATH"));
    m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qml"));
}

QmlProjectRunConfiguration::~QmlProjectRunConfiguration()
{
}

QString QmlProjectRunConfiguration::debugServerAddress() const
{
    return m_debugServerAddress;
}

Internal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const
{
    return static_cast<Internal::QmlProjectTarget *>(target());
}

QString QmlProjectRunConfiguration::viewerPath() const
{
    if (!m_qmlViewerCustomPath.isEmpty())
        return m_qmlViewerCustomPath;
    return m_qmlViewerDefaultPath;
}

QStringList QmlProjectRunConfiguration::viewerArguments() const
{
    QStringList args;

    // arguments in .user file
    if (!m_qmlViewerArgs.isEmpty())
        args.append(m_qmlViewerArgs.split(QLatin1Char(' ')));

    // arguments from .qmlproject file
    foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) {
        args.append(QLatin1String("-L"));
        args.append(importPath);
    }

    const QString s = mainScript();
    if (! s.isEmpty())
        args.append(s);
    return args;
}

QString QmlProjectRunConfiguration::workingDirectory() const
{
    QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName());
    return projectFile.absolutePath();
}

uint QmlProjectRunConfiguration::debugServerPort() const
{
    return m_debugServerPort;
}

static bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
{
    return s1.toLower() < s2.toLower();
}

QWidget *QmlProjectRunConfiguration::configurationWidget()
{
    QWidget *config = new QWidget;
    QFormLayout *form = new QFormLayout(config);

    m_fileListCombo = new QComboBox;
    m_fileListCombo.data()->setModel(m_fileListModel);
    updateFileComboBox();

    connect(m_fileListCombo.data(), SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), SLOT(updateFileComboBox()));

    Utils::PathChooser *qmlViewer = new Utils::PathChooser;
    qmlViewer->setExpectedKind(Utils::PathChooser::Command);
    qmlViewer->setPath(viewerPath());
    connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onViewerChanged()));

    QLineEdit *qmlViewerArgs = new QLineEdit;
    qmlViewerArgs->setText(m_qmlViewerArgs);
    connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onViewerArgsChanged()));

    QLineEdit *debugServer = new QLineEdit;
    debugServer->setText(m_debugServerAddress);
    connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged()));

    QSpinBox *debugPort = new QSpinBox;
    debugPort->setMinimum(1024); // valid registered/dynamic/free ports according to http://www.iana.org/assignments/port-numbers
    debugPort->setMaximum(65535);
    debugPort->setValue(m_debugServerPort);
    connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged()));

    form->addRow(tr("QML Runtime"), qmlViewer);
    form->addRow(tr("QML Runtime arguments:"), qmlViewerArgs);
    form->addRow(tr("Main QML File:"), m_fileListCombo.data());
    form->addRow(tr("Debugging Address:"), debugServer);
    form->addRow(tr("Debugging Port:"), debugPort);

    return config;
}

QString QmlProjectRunConfiguration::mainScript() const
{
    if (m_usingCurrentFile)
        return m_currentFileFilename;

    return m_mainScriptFilename;
}

void QmlProjectRunConfiguration::updateFileComboBox()
{
    if (m_fileListCombo.isNull())
        return;

    QDir projectDir = qmlTarget()->qmlProject()->projectDir();
    QStringList files;

    files.append(CURRENT_FILE);
    int currentIndex = -1;
    QStringList sortedFiles = qmlTarget()->qmlProject()->files();
    qStableSort(sortedFiles.begin(), sortedFiles.end(), caseInsensitiveLessThan);

    foreach (const QString &fn, sortedFiles) {
        QFileInfo fileInfo(fn);
        if (fileInfo.suffix() != QLatin1String("qml"))
            continue;

        QString fileName = projectDir.relativeFilePath(fn);
        if (fileName == m_scriptFile)
            currentIndex = files.size();

        files.append(fileName);
    }
    m_fileListModel->setStringList(files);

    if (currentIndex != -1)
        m_fileListCombo.data()->setCurrentIndex(currentIndex);
    else
        m_fileListCombo.data()->setCurrentIndex(0);
}

void QmlProjectRunConfiguration::onDebugServerAddressChanged()
{
    if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))
        m_debugServerAddress = lineEdit->text();
}

void QmlProjectRunConfiguration::setMainScript(const QString &scriptFile)
{
    m_scriptFile = scriptFile;
    // replace with locale-agnostic string
    if (m_scriptFile == CURRENT_FILE)
        m_scriptFile = M_CURRENT_FILE;

    if (m_scriptFile.isEmpty() || m_scriptFile == M_CURRENT_FILE) {
        m_usingCurrentFile = true;
        changeCurrentFile(Core::EditorManager::instance()->currentEditor());
    } else {
        m_usingCurrentFile = false;
        m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(scriptFile);
        setEnabled(true);
    }
}

void QmlProjectRunConfiguration::onViewerChanged()
{
    if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) {
        m_qmlViewerCustomPath = chooser->path();
    }
}

void QmlProjectRunConfiguration::onViewerArgsChanged()
{
    if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))
        m_qmlViewerArgs = lineEdit->text();
}

void QmlProjectRunConfiguration::onDebugServerPortChanged()
{
    if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) {
        m_debugServerPort = spinBox->value();
    }
}

QVariantMap QmlProjectRunConfiguration::toMap() const
{
    QVariantMap map(ProjectExplorer::RunConfiguration::toMap());

    map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath);
    map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);
    map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY),  m_scriptFile);
    map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugServerPort);
    map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), m_debugServerAddress);
    return map;
}

bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
{
    m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString();
    m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();
    m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString();
    m_debugServerPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt();
    m_debugServerAddress = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), QLatin1String("127.0.0.1")).toString();
    setMainScript(m_scriptFile);

    return RunConfiguration::fromMap(map);
}

void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor)
{
    if (m_usingCurrentFile) {
        bool enable = false;
        if (editor) {
            m_currentFileFilename = editor->file()->fileName();
            if (Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml")))
                enable = true;
        } else {
            // find a qml file with lowercase filename. This is slow but only done in initialization/other border cases.
            foreach(const QString& filename, m_projectTarget->qmlProject()->files()) {
                const QFileInfo fi(filename);

                if (!filename.isEmpty() && fi.baseName()[0].isLower()
                    && Core::ICore::instance()->mimeDatabase()->findByFile(fi).matchesType(QLatin1String("application/x-qml")))
                {
                    m_currentFileFilename = filename;
                    enable = true;
                    break;
                }

            }
        }

        setEnabled(enable);
    }
}

void QmlProjectRunConfiguration::setEnabled(bool value)
{
    m_isEnabled = value;
    emit isEnabledChanged(m_isEnabled);
}

} // namespace QmlProjectManager
<commit_msg>QmlProject: Qml runtime command parameter -L has been replaced by -I<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectmanagerconstants.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojecttarget.h"
#include "projectexplorer/projectexplorer.h"

#include <coreplugin/mimedatabase.h>
#include <projectexplorer/buildconfiguration.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <coreplugin/ifile.h>
#include <utils/synchronousprocess.h>
#include <utils/pathchooser.h>

#include <QFormLayout>
#include <QComboBox>
#include <QCoreApplication>
#include <QLineEdit>
#include <QSpinBox>
#include <QStringListModel>
#include <QDebug>

namespace QmlProjectManager {

QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent) :
    ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)),
    m_debugServerAddress("127.0.0.1"),
    m_debugServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT),
    m_fileListModel(new QStringListModel(this)),
    m_projectTarget(parent),
    m_usingCurrentFile(true),
    m_isEnabled(false)
{
    ctor();
}

QmlProjectRunConfiguration::QmlProjectRunConfiguration(Internal::QmlProjectTarget *parent, QmlProjectRunConfiguration *source) :
    ProjectExplorer::RunConfiguration(parent, source),
    m_scriptFile(source->m_scriptFile),
    m_qmlViewerCustomPath(source->m_qmlViewerCustomPath),
    m_qmlViewerArgs(source->m_qmlViewerArgs),
    m_debugServerAddress(source->m_debugServerAddress),
    m_debugServerPort(source->m_debugServerPort)
{
    ctor();
}

bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const
{
    Q_UNUSED(bc);

    if (!QFile::exists(mainScript())
        || !Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml")))
    {
        return false;
    }
    return true;
}

void QmlProjectRunConfiguration::ctor()
{
    Core::EditorManager *em = Core::EditorManager::instance();
    connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(changeCurrentFile(Core::IEditor*)));

    setDisplayName(tr("QML Runtime", "QMLRunConfiguration display name."));

    // prepend creator/bin dir to search path (only useful for special creator-qml package)
    const QString searchPath = QCoreApplication::applicationDirPath()
                               + Utils::SynchronousProcess::pathSeparator()
                               + QString(qgetenv("PATH"));
    m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qml"));
}

QmlProjectRunConfiguration::~QmlProjectRunConfiguration()
{
}

QString QmlProjectRunConfiguration::debugServerAddress() const
{
    return m_debugServerAddress;
}

Internal::QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const
{
    return static_cast<Internal::QmlProjectTarget *>(target());
}

QString QmlProjectRunConfiguration::viewerPath() const
{
    if (!m_qmlViewerCustomPath.isEmpty())
        return m_qmlViewerCustomPath;
    return m_qmlViewerDefaultPath;
}

QStringList QmlProjectRunConfiguration::viewerArguments() const
{
    QStringList args;

    // arguments in .user file
    if (!m_qmlViewerArgs.isEmpty())
        args.append(m_qmlViewerArgs.split(QLatin1Char(' ')));

    // arguments from .qmlproject file
    foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) {
        args.append(QLatin1String("-I"));
        args.append(importPath);
    }

    const QString s = mainScript();
    if (! s.isEmpty())
        args.append(s);
    return args;
}

QString QmlProjectRunConfiguration::workingDirectory() const
{
    QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName());
    return projectFile.absolutePath();
}

uint QmlProjectRunConfiguration::debugServerPort() const
{
    return m_debugServerPort;
}

static bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
{
    return s1.toLower() < s2.toLower();
}

QWidget *QmlProjectRunConfiguration::configurationWidget()
{
    QWidget *config = new QWidget;
    QFormLayout *form = new QFormLayout(config);

    m_fileListCombo = new QComboBox;
    m_fileListCombo.data()->setModel(m_fileListModel);
    updateFileComboBox();

    connect(m_fileListCombo.data(), SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), SLOT(updateFileComboBox()));

    Utils::PathChooser *qmlViewer = new Utils::PathChooser;
    qmlViewer->setExpectedKind(Utils::PathChooser::Command);
    qmlViewer->setPath(viewerPath());
    connect(qmlViewer, SIGNAL(changed(QString)), this, SLOT(onViewerChanged()));

    QLineEdit *qmlViewerArgs = new QLineEdit;
    qmlViewerArgs->setText(m_qmlViewerArgs);
    connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onViewerArgsChanged()));

    QLineEdit *debugServer = new QLineEdit;
    debugServer->setText(m_debugServerAddress);
    connect(debugServer, SIGNAL(textChanged(QString)), this, SLOT(onDebugServerAddressChanged()));

    QSpinBox *debugPort = new QSpinBox;
    debugPort->setMinimum(1024); // valid registered/dynamic/free ports according to http://www.iana.org/assignments/port-numbers
    debugPort->setMaximum(65535);
    debugPort->setValue(m_debugServerPort);
    connect(debugPort, SIGNAL(valueChanged(int)), this, SLOT(onDebugServerPortChanged()));

    form->addRow(tr("QML Runtime"), qmlViewer);
    form->addRow(tr("QML Runtime arguments:"), qmlViewerArgs);
    form->addRow(tr("Main QML File:"), m_fileListCombo.data());
    form->addRow(tr("Debugging Address:"), debugServer);
    form->addRow(tr("Debugging Port:"), debugPort);

    return config;
}

QString QmlProjectRunConfiguration::mainScript() const
{
    if (m_usingCurrentFile)
        return m_currentFileFilename;

    return m_mainScriptFilename;
}

void QmlProjectRunConfiguration::updateFileComboBox()
{
    if (m_fileListCombo.isNull())
        return;

    QDir projectDir = qmlTarget()->qmlProject()->projectDir();
    QStringList files;

    files.append(CURRENT_FILE);
    int currentIndex = -1;
    QStringList sortedFiles = qmlTarget()->qmlProject()->files();
    qStableSort(sortedFiles.begin(), sortedFiles.end(), caseInsensitiveLessThan);

    foreach (const QString &fn, sortedFiles) {
        QFileInfo fileInfo(fn);
        if (fileInfo.suffix() != QLatin1String("qml"))
            continue;

        QString fileName = projectDir.relativeFilePath(fn);
        if (fileName == m_scriptFile)
            currentIndex = files.size();

        files.append(fileName);
    }
    m_fileListModel->setStringList(files);

    if (currentIndex != -1)
        m_fileListCombo.data()->setCurrentIndex(currentIndex);
    else
        m_fileListCombo.data()->setCurrentIndex(0);
}

void QmlProjectRunConfiguration::onDebugServerAddressChanged()
{
    if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))
        m_debugServerAddress = lineEdit->text();
}

void QmlProjectRunConfiguration::setMainScript(const QString &scriptFile)
{
    m_scriptFile = scriptFile;
    // replace with locale-agnostic string
    if (m_scriptFile == CURRENT_FILE)
        m_scriptFile = M_CURRENT_FILE;

    if (m_scriptFile.isEmpty() || m_scriptFile == M_CURRENT_FILE) {
        m_usingCurrentFile = true;
        changeCurrentFile(Core::EditorManager::instance()->currentEditor());
    } else {
        m_usingCurrentFile = false;
        m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(scriptFile);
        setEnabled(true);
    }
}

void QmlProjectRunConfiguration::onViewerChanged()
{
    if (Utils::PathChooser *chooser = qobject_cast<Utils::PathChooser *>(sender())) {
        m_qmlViewerCustomPath = chooser->path();
    }
}

void QmlProjectRunConfiguration::onViewerArgsChanged()
{
    if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender()))
        m_qmlViewerArgs = lineEdit->text();
}

void QmlProjectRunConfiguration::onDebugServerPortChanged()
{
    if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender())) {
        m_debugServerPort = spinBox->value();
    }
}

QVariantMap QmlProjectRunConfiguration::toMap() const
{
    QVariantMap map(ProjectExplorer::RunConfiguration::toMap());

    map.insert(QLatin1String(Constants::QML_VIEWER_KEY), m_qmlViewerCustomPath);
    map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);
    map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY),  m_scriptFile);
    map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), m_debugServerPort);
    map.insert(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), m_debugServerAddress);
    return map;
}

bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
{
    m_qmlViewerCustomPath = map.value(QLatin1String(Constants::QML_VIEWER_KEY)).toString();
    m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();
    m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString();
    m_debugServerPort = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_PORT_KEY), Constants::QML_DEFAULT_DEBUG_SERVER_PORT).toUInt();
    m_debugServerAddress = map.value(QLatin1String(Constants::QML_DEBUG_SERVER_ADDRESS_KEY), QLatin1String("127.0.0.1")).toString();
    setMainScript(m_scriptFile);

    return RunConfiguration::fromMap(map);
}

void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor)
{
    if (m_usingCurrentFile) {
        bool enable = false;
        if (editor) {
            m_currentFileFilename = editor->file()->fileName();
            if (Core::ICore::instance()->mimeDatabase()->findByFile(mainScript()).matchesType(QLatin1String("application/x-qml")))
                enable = true;
        } else {
            // find a qml file with lowercase filename. This is slow but only done in initialization/other border cases.
            foreach(const QString& filename, m_projectTarget->qmlProject()->files()) {
                const QFileInfo fi(filename);

                if (!filename.isEmpty() && fi.baseName()[0].isLower()
                    && Core::ICore::instance()->mimeDatabase()->findByFile(fi).matchesType(QLatin1String("application/x-qml")))
                {
                    m_currentFileFilename = filename;
                    enable = true;
                    break;
                }

            }
        }

        setEnabled(enable);
    }
}

void QmlProjectRunConfiguration::setEnabled(bool value)
{
    m_isEnabled = value;
    emit isEnabledChanged(m_isEnabled);
}

} // namespace QmlProjectManager
<|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

json_t* global_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
const char* PROJECT_URL(void)
{
	return "https://www.thpatch.net/wiki/Touhou_Patch_Center:Download";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20201208;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
const char* PROJECT_BRANCH(void)
{
	return "stable";
}

void globalconfig_init(void)
{
	json_decref(global_cfg);
	global_cfg = json_load_file_report("config/config.js");
	if (!global_cfg) {
		global_cfg = json_object();
	}
}

int globalconfig_dump(void)
{
	return json_dump_file(global_cfg, "config/config.js", JSON_INDENT(2) | JSON_SORT_KEYS);
}

BOOL globalconfig_get_boolean(const char* key, const BOOL default_value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	errno = 0;
	json_t* value_json = json_object_get(global_cfg, key);
	if (!value_json) {
		errno = ENOENT;
		return default_value;
	}
	return json_boolean_value(value_json);
}

int globalconfig_set_boolean(const char* key, const BOOL value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	json_t* j_value = json_boolean(value);
	if (json_equal(j_value, json_object_get(global_cfg, key))) {
		json_decref(j_value);
		return 0;
	}
	json_object_set_new(global_cfg, key, j_value);
	return globalconfig_dump();
}

long long globalconfig_get_integer(const char* key, const long long default_value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	errno = 0;
	json_t* value_json = json_object_get(global_cfg, key);
	if (!value_json) {
		errno = ENOENT;
		return default_value;
	}
	return json_integer_value(value_json);
}

int globalconfig_set_integer(const char* key, const long long value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	json_t* j_value = json_integer(value);
	if (json_equal(j_value, json_object_get(global_cfg, key))) {
		json_decref(j_value);
		return 0;
	}
	json_object_set_new(global_cfg, key, j_value);
	return globalconfig_dump();
}

void globalconfig_release(void)
{
	json_decref(global_cfg);
	global_cfg = json_incref(NULL);
}

void* __cdecl thcrap_alloc(size_t size) {
	return malloc(size);
}

void __cdecl thcrap_free(void *mem) {
	free(mem);
}
<commit_msg>Update version number<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

json_t* global_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
const char* PROJECT_URL(void)
{
	return "https://www.thpatch.net/wiki/Touhou_Patch_Center:Download";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20210117;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
const char* PROJECT_BRANCH(void)
{
	return "stable";
}

void globalconfig_init(void)
{
	json_decref(global_cfg);
	global_cfg = json_load_file_report("config/config.js");
	if (!global_cfg) {
		global_cfg = json_object();
	}
}

int globalconfig_dump(void)
{
	return json_dump_file(global_cfg, "config/config.js", JSON_INDENT(2) | JSON_SORT_KEYS);
}

BOOL globalconfig_get_boolean(const char* key, const BOOL default_value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	errno = 0;
	json_t* value_json = json_object_get(global_cfg, key);
	if (!value_json) {
		errno = ENOENT;
		return default_value;
	}
	return json_boolean_value(value_json);
}

int globalconfig_set_boolean(const char* key, const BOOL value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	json_t* j_value = json_boolean(value);
	if (json_equal(j_value, json_object_get(global_cfg, key))) {
		json_decref(j_value);
		return 0;
	}
	json_object_set_new(global_cfg, key, j_value);
	return globalconfig_dump();
}

long long globalconfig_get_integer(const char* key, const long long default_value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	errno = 0;
	json_t* value_json = json_object_get(global_cfg, key);
	if (!value_json) {
		errno = ENOENT;
		return default_value;
	}
	return json_integer_value(value_json);
}

int globalconfig_set_integer(const char* key, const long long value)
{
	if (!global_cfg) {
		globalconfig_init();
	}
	json_t* j_value = json_integer(value);
	if (json_equal(j_value, json_object_get(global_cfg, key))) {
		json_decref(j_value);
		return 0;
	}
	json_object_set_new(global_cfg, key, j_value);
	return globalconfig_dump();
}

void globalconfig_release(void)
{
	json_decref(global_cfg);
	global_cfg = json_incref(NULL);
}

void* __cdecl thcrap_alloc(size_t size) {
	return malloc(size);
}

void __cdecl thcrap_free(void *mem) {
	free(mem);
}
<|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Plug-in and module handling
  */

#include "thcrap.h"
#include <vector>

static json_t *funcs = NULL;
static json_t *mod_funcs = NULL;
static json_t *plugins = NULL;

void* func_get(const char *name)
{
	return (void*)json_object_get_hex(funcs, name);
}

int plugin_init(HMODULE hMod)
{
	json_t *funcs_new = json_object();
	int ret = GetExportedFunctions(funcs_new, hMod);
	if(!funcs) {
		funcs = json_object();
	}
	if(!mod_funcs) {
		mod_funcs = json_object();
	}
	if(!ret) {
		json_t *mod_funcs_new = mod_func_build(funcs_new);
		const char *key;
		json_t *val;
		mod_func_run(mod_funcs_new, "init", NULL);
		mod_func_run(mod_funcs_new, "detour", NULL);
		json_object_foreach(mod_funcs_new, key, val) {
			json_t *funcs_old = json_object_get_create(mod_funcs, key, JSON_ARRAY);
			json_array_extend(funcs_old, val);
		}
		json_decref(mod_funcs_new);
	}
	json_object_merge(funcs, funcs_new);
	json_decref(funcs_new);
	return ret;
}

void plugin_load(const char *dir, const char *fn)
{
	// LoadLibraryEx() with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
	// requires an absolute path to not fail with GetLastError() == 87.
	STRLEN_DEC(dir);
	STRLEN_DEC(fn);
	VLA(char, fn_abs, dir_len + fn_len);
	defer(VLA_FREE(fn_abs));

	sprintf(fn_abs, "%s/%s", dir, fn);

	auto plugin = LoadLibraryExU(fn_abs, nullptr,
		LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
	);
	if(!plugin) {
		log_printf("[Plugin] Error loading %s: %d\n", fn_abs, GetLastError());
		return;
	}
	FARPROC func = GetProcAddress(plugin, "thcrap_plugin_init");
	if(func && !func()) {
		log_printf("[Plugin] %s: initialized and active\n", fn);
		plugin_init(plugin);
		json_object_set_new(plugins, fn, json_integer((size_t)plugin));
	} else {
		if(func) {
			log_printf("[Plugin] %s: not used for this game\n", fn);
		}
		FreeLibrary(plugin);
	}
}

int plugins_load(const char *dir)
{
	BOOL ret = 0;
	WIN32_FIND_DATAA w32fd;
	HANDLE hFind = FindFirstFile("*.dll", &w32fd);
	if(hFind == INVALID_HANDLE_VALUE) {
		return 1;
	}
	// Apparently, successful self-updates can cause infinite loops?
	// This is safer anyway.
	std::vector<std::string> dlls;
	if(!json_is_object(plugins)) {
		plugins = json_object();
	}
	while(!ret) {
		// Necessary to avoid the nonsensical "Bad Image" message
		// box if you try to LoadLibrary() a 0-byte file.
		if(w32fd.nFileSizeHigh > 0 || w32fd.nFileSizeLow > 0) {
			// Yes, "*.dll" means "*.dll*" in FindFirstFile.
			// https://blogs.msdn.microsoft.com/oldnewthing/20050720-16/?p=34883
			if(!stricmp(PathFindExtensionA(w32fd.cFileName), ".dll")) {
				dlls.push_back(w32fd.cFileName);
			}
		}
		ret = W32_ERR_WRAP(FindNextFile(hFind, &w32fd));
	}
	for(auto dll : dlls) {
		plugin_load(dir, dll.c_str());
	}
	FindClose(hFind);
	return 0;
}

int plugins_close(void)
{
	const char *key;
	json_t *val;

	funcs = json_decref_safe(funcs);
	mod_funcs = json_decref_safe(mod_funcs);

	log_printf("Removing plug-ins...\n");
	json_object_foreach(plugins, key, val) {
		HINSTANCE hInst = (HINSTANCE)json_integer_value(val);
		if(hInst) {
			FreeLibrary(hInst);
		}
	}
	plugins = json_decref_safe(plugins);
	return 0;
}

json_t* mod_func_build(json_t *funcs)
{
	json_t *ret = NULL;
	const char *infix = "_mod_";
	size_t infix_len = strlen(infix);
	const char *key;
	json_t *val;
	json_object_foreach(funcs, key, val) {
		const char *p = strstr(key, infix);
		if(p) {
			json_t *arr = NULL;
			p += infix_len;
			if(!ret) {
				ret = json_object();
			}
			arr = json_object_get_create(ret, p, JSON_ARRAY);
			json_array_append(arr, val);
		}
	}
	return ret;
}

void mod_func_run(json_t *mod_funcs, const char *pattern, void *param)
{
	json_t *func_array = json_object_get(mod_funcs, pattern);
	size_t i;
	json_t *val;
	json_array_foreach(func_array, i, val) {
		mod_call_type func = (mod_call_type)json_integer_value(val);
		if(func) {
			func(param);
		}
	}
}

void mod_func_run_all(const char *pattern, void *param)
{
	mod_func_run(mod_funcs, pattern, param);
}
<commit_msg>thcrap: Plugins: #include <string>, which would be missing on MinGW/GCC.<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Plug-in and module handling
  */

#include "thcrap.h"
#include <vector>
#include <string>

static json_t *funcs = NULL;
static json_t *mod_funcs = NULL;
static json_t *plugins = NULL;

void* func_get(const char *name)
{
	return (void*)json_object_get_hex(funcs, name);
}

int plugin_init(HMODULE hMod)
{
	json_t *funcs_new = json_object();
	int ret = GetExportedFunctions(funcs_new, hMod);
	if(!funcs) {
		funcs = json_object();
	}
	if(!mod_funcs) {
		mod_funcs = json_object();
	}
	if(!ret) {
		json_t *mod_funcs_new = mod_func_build(funcs_new);
		const char *key;
		json_t *val;
		mod_func_run(mod_funcs_new, "init", NULL);
		mod_func_run(mod_funcs_new, "detour", NULL);
		json_object_foreach(mod_funcs_new, key, val) {
			json_t *funcs_old = json_object_get_create(mod_funcs, key, JSON_ARRAY);
			json_array_extend(funcs_old, val);
		}
		json_decref(mod_funcs_new);
	}
	json_object_merge(funcs, funcs_new);
	json_decref(funcs_new);
	return ret;
}

void plugin_load(const char *dir, const char *fn)
{
	// LoadLibraryEx() with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
	// requires an absolute path to not fail with GetLastError() == 87.
	STRLEN_DEC(dir);
	STRLEN_DEC(fn);
	VLA(char, fn_abs, dir_len + fn_len);
	defer(VLA_FREE(fn_abs));

	sprintf(fn_abs, "%s/%s", dir, fn);

	auto plugin = LoadLibraryExU(fn_abs, nullptr,
		LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
	);
	if(!plugin) {
		log_printf("[Plugin] Error loading %s: %d\n", fn_abs, GetLastError());
		return;
	}
	FARPROC func = GetProcAddress(plugin, "thcrap_plugin_init");
	if(func && !func()) {
		log_printf("[Plugin] %s: initialized and active\n", fn);
		plugin_init(plugin);
		json_object_set_new(plugins, fn, json_integer((size_t)plugin));
	} else {
		if(func) {
			log_printf("[Plugin] %s: not used for this game\n", fn);
		}
		FreeLibrary(plugin);
	}
}

int plugins_load(const char *dir)
{
	BOOL ret = 0;
	WIN32_FIND_DATAA w32fd;
	HANDLE hFind = FindFirstFile("*.dll", &w32fd);
	if(hFind == INVALID_HANDLE_VALUE) {
		return 1;
	}
	// Apparently, successful self-updates can cause infinite loops?
	// This is safer anyway.
	std::vector<std::string> dlls;
	if(!json_is_object(plugins)) {
		plugins = json_object();
	}
	while(!ret) {
		// Necessary to avoid the nonsensical "Bad Image" message
		// box if you try to LoadLibrary() a 0-byte file.
		if(w32fd.nFileSizeHigh > 0 || w32fd.nFileSizeLow > 0) {
			// Yes, "*.dll" means "*.dll*" in FindFirstFile.
			// https://blogs.msdn.microsoft.com/oldnewthing/20050720-16/?p=34883
			if(!stricmp(PathFindExtensionA(w32fd.cFileName), ".dll")) {
				dlls.push_back(w32fd.cFileName);
			}
		}
		ret = W32_ERR_WRAP(FindNextFile(hFind, &w32fd));
	}
	for(auto dll : dlls) {
		plugin_load(dir, dll.c_str());
	}
	FindClose(hFind);
	return 0;
}

int plugins_close(void)
{
	const char *key;
	json_t *val;

	funcs = json_decref_safe(funcs);
	mod_funcs = json_decref_safe(mod_funcs);

	log_printf("Removing plug-ins...\n");
	json_object_foreach(plugins, key, val) {
		HINSTANCE hInst = (HINSTANCE)json_integer_value(val);
		if(hInst) {
			FreeLibrary(hInst);
		}
	}
	plugins = json_decref_safe(plugins);
	return 0;
}

json_t* mod_func_build(json_t *funcs)
{
	json_t *ret = NULL;
	const char *infix = "_mod_";
	size_t infix_len = strlen(infix);
	const char *key;
	json_t *val;
	json_object_foreach(funcs, key, val) {
		const char *p = strstr(key, infix);
		if(p) {
			json_t *arr = NULL;
			p += infix_len;
			if(!ret) {
				ret = json_object();
			}
			arr = json_object_get_create(ret, p, JSON_ARRAY);
			json_array_append(arr, val);
		}
	}
	return ret;
}

void mod_func_run(json_t *mod_funcs, const char *pattern, void *param)
{
	json_t *func_array = json_object_get(mod_funcs, pattern);
	size_t i;
	json_t *val;
	json_array_foreach(func_array, i, val) {
		mod_call_type func = (mod_call_type)json_integer_value(val);
		if(func) {
			func(param);
		}
	}
}

void mod_func_run_all(const char *pattern, void *param)
{
	mod_func_run(mod_funcs, pattern, param);
}
<|endoftext|>


<commit_before>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

#include <unistd.h> // sleep

float cpu_percentage()
{
  string stat_line;
  size_t line_start_pos;
  size_t line_end_pos;
  unsigned long long current_user;
  unsigned long long current_system;
  unsigned long long current_nice;
  unsigned long long current_idle;
  unsigned long long next_user;
  unsigned long long next_system;
  unsigned long long next_nice;
  unsigned long long next_idle;
  unsigned long long diff_user;
  unsigned long long diff_system;
  unsigned long long diff_nice;
  unsigned long long diff_idle;
  istringstream iss;

  ifstream stat_file("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> current_user >> current_nice >> current_system >> current_idle;
  iss.clear();

  sleep(1);

  stat_file.open("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> next_user >> next_nice >> next_system >> next_idle;
  iss.clear();

  diff_user   = next_user - current_user;
  diff_system = next_system - current_system;
  diff_nice   = next_nice - current_nice;
  diff_idle   = next_idle - current_idle;

  return static_cast<float>(diff_user + diff_system + diff_nice)/static_cast<float>(diff_user + diff_system + diff_nice + diff_idle)*100.0;
}

string cpu_string()
{
  string meter = "[          ]";
  int meter_count = 0;
  float percentage;
  ostringstream oss;
  oss.precision( 1 );
  oss.setf( ios::fixed | ios::right );

  percentage = cpu_percentage();
  meter_count = 1;
  while(meter_count*9.99 < percentage)
    {
    meter[meter_count] = '|';
    meter_count++;
    }

  oss << "CPU:";
  oss << meter;
  oss.width( 5 );
  oss << percentage;
  oss << "%";

  return oss.str();
}

string mem_string()
{
  int total_mem;
  size_t line_start_pos;
  size_t line_end_pos;
  istringstream iss;
  ostringstream oss;
  string mem_line;

  ifstream meminfo_file( "/proc/meminfo" );
  getline( meminfo_file, mem_line );
  line_start_pos = mem_line.find_first_of( ':' );
  line_start_pos++;
  line_end_pos = mem_line.find_first_of( 'k' );
  iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> total_mem;

  oss << "MEM: ";
  oss << total_mem / 1024;

  meminfo_file.close();

  return oss.str();
}

int main(int argc, char** argv)
{
  try
  {
  std::cout << mem_string() << ' ' << cpu_string();
  }
  catch(const exception &e)
  {
    cerr << "Error: " << e.what() << endl;
    return 1;
  }

  return 0;
}

<commit_msg>Calculate used memory.<commit_after>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

#include <unistd.h> // sleep

float cpu_percentage()
{
  string stat_line;
  size_t line_start_pos;
  size_t line_end_pos;
  unsigned long long current_user;
  unsigned long long current_system;
  unsigned long long current_nice;
  unsigned long long current_idle;
  unsigned long long next_user;
  unsigned long long next_system;
  unsigned long long next_nice;
  unsigned long long next_idle;
  unsigned long long diff_user;
  unsigned long long diff_system;
  unsigned long long diff_nice;
  unsigned long long diff_idle;
  istringstream iss;

  ifstream stat_file("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> current_user >> current_nice >> current_system >> current_idle;
  iss.clear();

  sleep(1);

  stat_file.open("/proc/stat");
  getline(stat_file, stat_line);
  stat_file.close();

  // skip "cpu"
  line_start_pos = stat_line.find_first_not_of(" ", 3);
  line_end_pos = stat_line.find_first_of(' ', line_start_pos);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);
  line_end_pos = stat_line.find_first_of(' ', line_end_pos + 1);

  iss.str( stat_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> next_user >> next_nice >> next_system >> next_idle;
  iss.clear();

  diff_user   = next_user - current_user;
  diff_system = next_system - current_system;
  diff_nice   = next_nice - current_nice;
  diff_idle   = next_idle - current_idle;

  return static_cast<float>(diff_user + diff_system + diff_nice)/static_cast<float>(diff_user + diff_system + diff_nice + diff_idle)*100.0;
}

string cpu_string()
{
  string meter = "[          ]";
  int meter_count = 0;
  float percentage;
  ostringstream oss;
  oss.precision( 1 );
  oss.setf( ios::fixed | ios::right );

  percentage = cpu_percentage();
  meter_count = 1;
  while(meter_count*9.99 < percentage)
    {
    meter[meter_count] = '|';
    meter_count++;
    }

  oss << "CPU:";
  oss << meter;
  oss.width( 5 );
  oss << percentage;
  oss << "%";

  return oss.str();
}

string mem_string()
{
  unsigned int total_mem;
  unsigned int used_mem;
  unsigned int unused_mem;
  size_t line_start_pos;
  size_t line_end_pos;
  istringstream iss;
  ostringstream oss;
  string mem_line;

  ifstream meminfo_file( "/proc/meminfo" );
  getline( meminfo_file, mem_line );
  line_start_pos = mem_line.find_first_of( ':' );
  line_start_pos++;
  line_end_pos = mem_line.find_first_of( 'k' );
  iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
  iss >> total_mem;

  used_mem = total_mem;

  for( unsigned int i = 0; i < 3; i++ )
    {
    getline( meminfo_file, mem_line );
    line_start_pos = mem_line.find_first_of( ':' );
    line_start_pos++;
    line_end_pos = mem_line.find_first_of( 'k' );
    iss.str( mem_line.substr( line_start_pos, line_end_pos - line_start_pos ) );
    iss >> unused_mem;
    used_mem -= unused_mem;
    }
  meminfo_file.close();

  oss << "Mem: ";
  oss << used_mem / 1024 << '/' << total_mem / 1024;

  return oss.str();
}

int main(int argc, char** argv)
{
  try
  {
  std::cout << mem_string() << ' ' << cpu_string();
  }
  catch(const exception &e)
  {
    cerr << "Error: " << e.what() << endl;
    return 1;
  }

  return 0;
}

<|endoftext|>


<commit_before>#include "globals.hh"
#include "gc.hh"
#include "build.hh"
#include "pathlocks.hh"

#include <boost/shared_ptr.hpp>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

static string gcLockName = "gc.lock";
static string tempRootsDir = "temproots";
static string gcRootsDir = "gcroots";

/* Acquire the global GC lock.  This is used to prevent new Nix
   processes from starting after the temporary root files have been
   read.  To be precise: when they try to create a new temporary root
   file, they will block until the garbage collector has finished /
   yielded the GC lock. */
static int openGCLock(LockType lockType)
{
    Path fnGCLock = (format("%1%/%2%")
        % nixStateDir % gcLockName).str();

    debug(format("acquiring global GC lock `%1%'") % fnGCLock);

    AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600);
    if (fdGCLock == -1)
        throw SysError(format("opening global GC lock `%1%'") % fnGCLock);

    lockFile(fdGCLock, lockType, true);

    /* !!! Restrict read permission on the GC root.  Otherwise any
       process that can open the file for reading can DoS the
       collector. */

    return fdGCLock.borrow();
}

static void createDirs(const Path & path)
{
    if (path == "") return;
    createDirs(dirOf(path));
    if (!pathExists(path))
        if (mkdir(path.c_str(), 0777) == -1)
            throw SysError(format("creating directory `%1%'") % path);
}

void createSymlink(const Path & link, const Path & target, bool careful)
{
    /* Create directories up to `gcRoot'. */
    createDirs(dirOf(link));

    /* Remove the old symlink. */
    if (pathExists(link)) {
        if (careful && (!isLink(link) || !isInStore(readLink(link))))
            throw Error(format("cannot create symlink `%1%'; already exists") % link);
        unlink(link.c_str());
    }

    /* And create the new own. */
    if (symlink(target.c_str(), link.c_str()) == -1)
        throw SysError(format("symlinking `%1%' to `%2%'")
            % link % target);
}

Path addPermRoot(const Path & _storePath, const Path & _gcRoot,
    bool indirect)
{
    Path storePath(canonPath(_storePath));
    Path gcRoot(canonPath(_gcRoot));
    assertStorePath(storePath);

    /* Grab the global GC root.  This prevents the set of permanent
       roots from increasing while a GC is in progress. */
    AutoCloseFD fdGCLock = openGCLock(ltRead);

    if (indirect) {
        string hash = printHash32(hashString(htSHA1, gcRoot));
        Path realRoot = canonPath((format("%1%/%2%/auto/%3%")
            % nixStateDir % gcRootsDir % hash).str());

        createSymlink(gcRoot, storePath, true);
        createSymlink(realRoot, gcRoot, false);
    }

    else {
        Path rootsDir = canonPath((format("%1%/%2%") % nixStateDir % gcRootsDir).str());

        if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/")
            throw Error(format(
                "path `%1%' is not a valid garbage collector root; "
                "it's not in the directory `%2%'")
                % gcRoot % rootsDir);

        createSymlink(gcRoot, storePath, false);
    }

    return gcRoot;
}

/* The file to which we write our temporary roots. */
static Path fnTempRoots;
static AutoCloseFD fdTempRoots;

void addTempRoot(const Path & path)
{
    /* Create the temporary roots file for this process. */
    if (fdTempRoots == -1) {

        while (1) {
            fnTempRoots = (format("%1%/%2%/%3%")
                % nixStateDir % tempRootsDir % getpid()).str();

            AutoCloseFD fdGCLock = openGCLock(ltRead);

            fdTempRoots = open(fnTempRoots.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0600);
            if (fdTempRoots == -1)
                throw SysError(format("opening temporary roots file `%1%'") % fnTempRoots);

            fdGCLock.close();

            debug(format("acquiring read lock on `%1%'") % fnTempRoots);
            lockFile(fdTempRoots, ltRead, true);

            /* Check whether the garbage collector didn't get in our
               way. */
            struct stat st;
            if (fstat(fdTempRoots, &st) == -1)
                throw SysError(format("statting `%1%'") % fnTempRoots);
            if (st.st_size == 0) break;

            /* The garbage collector deleted this file before we could
               get a lock.  (It won't delete the file after we get a
               lock.)  Try again. */
        }

    }

    /* Upgrade the lock to a write lock.  This will cause us to block
       if the garbage collector is holding our lock. */
    debug(format("acquiring write lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltWrite, true);

    string s = path + '\0';
    writeFull(fdTempRoots, (const unsigned char *) s.c_str(), s.size());

    /* Downgrade to a read lock. */
    debug(format("downgrading to read lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltRead, true);
}

void removeTempRoots()
{
    if (fdTempRoots != -1) {
        fdTempRoots.close();
        unlink(fnTempRoots.c_str());
    }
}

typedef shared_ptr<AutoCloseFD> FDPtr;
typedef list<FDPtr> FDs;

static void readTempRoots(PathSet & tempRoots, FDs & fds)
{
    /* Read the `temproots' directory for per-process temporary root
       files. */
    Strings tempRootFiles = readDirectory(
        (format("%1%/%2%") % nixStateDir % tempRootsDir).str());

    for (Strings::iterator i = tempRootFiles.begin();
         i != tempRootFiles.end(); ++i)
    {
        Path path = (format("%1%/%2%/%3%") % nixStateDir % tempRootsDir % *i).str();

        debug(format("reading temporary root file `%1%'") % path);

        FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666)));
        if (*fd == -1) {
            /* It's okay if the file has disappeared. */
            if (errno == ENOENT) continue;
            throw SysError(format("opening temporary roots file `%1%'") % path);
        }

        /* Try to acquire a write lock without blocking.  This can
           only succeed if the owning process has died.  In that case
           we don't care about its temporary roots. */
        if (lockFile(*fd, ltWrite, false)) {
            printMsg(lvlError, format("removing stale temporary roots file `%1%'")
                % path);
            unlink(path.c_str());
            writeFull(*fd, (const unsigned char *) "d", 1);
            continue;
        }

        /* Acquire a read lock.  This will prevent the owning process
           from upgrading to a write lock, therefore it will block in
           addTempRoot(). */
        debug(format("waiting for read lock on `%1%'") % path);
        lockFile(*fd, ltRead, true);

        /* Read the entire file. */
        string contents = readFile(*fd);

        /* Extract the roots. */
        unsigned int pos = 0, end;

        while ((end = contents.find((char) 0, pos)) != string::npos) {
            Path root(contents, pos, end - pos);
            debug(format("got temporary root `%1%'") % root);
            assertStorePath(root);
            tempRoots.insert(root);
            pos = end + 1;
        }

        fds.push_back(fd); /* keep open */
    }
}

static void findRoots(const Path & path, bool recurseSymlinks,
    PathSet & roots)
{
    struct stat st;
    if (lstat(path.c_str(), &st) == -1)
        throw SysError(format("statting `%1%'") % path);

    printMsg(lvlVomit, format("looking at `%1%'") % path);

    if (S_ISDIR(st.st_mode)) {
	Strings names = readDirectory(path);
	for (Strings::iterator i = names.begin(); i != names.end(); ++i)
            findRoots(path + "/" + *i, recurseSymlinks, roots);
    }

    else if (S_ISLNK(st.st_mode)) {
        string target = readLink(path);
        Path target2 = absPath(target, dirOf(path));

        if (isInStore(target2)) {
            debug(format("found root `%1%' in `%2%'")
                % target2 % path);
            roots.insert(toStorePath(target2));
        }

        else if (recurseSymlinks) {
            if (pathExists(target2))
                findRoots(target2, false, roots);
            else {
                printMsg(lvlInfo, format("removing stale link from `%1%' to `%2%'") % path % target2);
                /* Note that we only delete when recursing, i.e., when
                   we are still in the `gcroots' tree.  We never
                   delete stuff outside that tree. */
                unlink(path.c_str());
            }
        }
    }
}

static void dfsVisit(const PathSet & paths, const Path & path,
    PathSet & visited, Paths & sorted)
{
    if (visited.find(path) != visited.end()) return;
    visited.insert(path);

    PathSet references;
    if (isValidPath(path))
        queryReferences(noTxn, path, references);

    for (PathSet::iterator i = references.begin();
         i != references.end(); ++i)
        /* Don't traverse into paths that don't exist.  That can
           happen due to substitutes for non-existent paths. */
        if (*i != path && paths.find(*i) != paths.end())
            dfsVisit(paths, *i, visited, sorted);

    sorted.push_front(path);
}

static Paths topoSort(const PathSet & paths)
{
    Paths sorted;
    PathSet visited;
    for (PathSet::const_iterator i = paths.begin(); i != paths.end(); ++i)
        dfsVisit(paths, *i, visited, sorted);
    return sorted;
}

void collectGarbage(GCAction action, PathSet & result)
{
    result.clear();

    bool gcKeepOutputs = queryBoolSetting("gc-keep-outputs", false);

    /* Acquire the global GC root.  This prevents
       a) New roots from being added.
       b) Processes from creating new temporary root files. */
    AutoCloseFD fdGCLock = openGCLock(ltWrite);

    /* Find the roots.  Since we've grabbed the GC lock, the set of
       permanent roots cannot increase now. */
    Path rootsDir = canonPath((format("%1%/%2%") % nixStateDir % gcRootsDir).str());
    PathSet roots;
    findRoots(rootsDir, true, roots);

    if (action == gcReturnRoots) {
        result = roots;
        return;
    }

    /* Determine the live paths which is just the closure of the
       roots under the `references' relation. */
    PathSet livePaths;
    for (PathSet::const_iterator i = roots.begin(); i != roots.end(); ++i)
        computeFSClosure(canonPath(*i), livePaths);

    if (gcKeepOutputs) {
        /* Hmz, identical to storePathRequisites in nix-store. */
        for (PathSet::iterator i = livePaths.begin();
             i != livePaths.end(); ++i)
            if (isDerivation(*i)) {
                Derivation drv = derivationFromPath(*i);
                for (DerivationOutputs::iterator j = drv.outputs.begin();
                     j != drv.outputs.end(); ++j)
                    if (isValidPath(j->second.path))
                        computeFSClosure(j->second.path, livePaths);
            }
    }

    if (action == gcReturnLive) {
        result = livePaths;
        return;
    }

    /* Read the temporary roots.  This acquires read locks on all
       per-process temporary root files.  So after this point no paths
       can be added to the set of temporary roots. */
    PathSet tempRoots;
    FDs fds;
    readTempRoots(tempRoots, fds);

    /* Close the temporary roots.  Note that we *cannot* do this in
       readTempRoots(), because there we may not have all locks yet,
       meaning that an invalid path can become valid (and thus add to
       the references graph) after we have added it to the closure
       (and computeFSClosure() assumes that the presence of a path
       means that it has already been closed). */
    PathSet tempRootsClosed;
    for (PathSet::iterator i = tempRoots.begin(); i != tempRoots.end(); ++i)
        if (isValidPath(*i))
            computeFSClosure(*i, tempRootsClosed);
        else
            tempRootsClosed.insert(*i);

    /* For testing - see tests/gc-concurrent.sh. */
    if (getenv("NIX_DEBUG_GC_WAIT"))
        sleep(2);

    /* After this point the set of roots or temporary roots cannot
       increase, since we hold locks on everything.  So everything
       that is not currently in in `livePaths' or `tempRootsClosed'
       can be deleted. */

    /* Read the Nix store directory to find all currently existing
       paths. */
    Paths storePaths = readDirectory(nixStore);
    PathSet storePaths2;
    for (Paths::iterator i = storePaths.begin(); i != storePaths.end(); ++i)
        storePaths2.insert(canonPath(nixStore + "/" + *i));

    /* Topologically sort them under the `referers' relation.  That
       is, a < b iff a is in referers(b).  This gives us the order in
       which things can be deleted safely. */
    /* !!! when we have multiple output paths per derivation, this
       will not work anymore because we get cycles. */
    storePaths = topoSort(storePaths2);

    /* Try to delete store paths in the topologically sorted order. */
    for (Paths::iterator i = storePaths.begin(); i != storePaths.end(); ++i) {

        debug(format("considering deletion of `%1%'") % *i);

        if (livePaths.find(*i) != livePaths.end()) {
            debug(format("live path `%1%'") % *i);
            continue;
        }

        if (tempRootsClosed.find(*i) != tempRootsClosed.end()) {
            debug(format("temporary root `%1%'") % *i);
            continue;
        }

        debug(format("dead path `%1%'") % *i);
        result.insert(*i);

        AutoCloseFD fdLock;

        if (action == gcDeleteDead) {

            /* Only delete a lock file if we can acquire a write lock
               on it.  That means that it's either stale, or the
               process that created it hasn't locked it yet.  In the
               latter case the other process will detect that we
               deleted the lock, and retry (see pathlocks.cc). */
            if (i->size() >= 5 && string(*i, i->size() - 5) == ".lock") {

                fdLock = open(i->c_str(), O_RDWR);
                if (fdLock == -1) {
                    if (errno == ENOENT) continue;
                    throw SysError(format("opening lock file `%1%'") % *i);
                }

                if (!lockFile(fdLock, ltWrite, false)) {
                    debug(format("skipping active lock `%1%'") % *i);
                    continue;
                }
            }

            printMsg(lvlInfo, format("deleting `%1%'") % *i);

            /* Okay, it's safe to delete. */
            deleteFromStore(*i);

            if (fdLock != -1)
                /* Write token to stale (deleted) lock file. */
                writeFull(fdLock, (const unsigned char *) "d", 1);
        }
    }
}
<commit_msg>* Implement the `gc-keep-derivations' global configuretion flag.<commit_after>#include "globals.hh"
#include "gc.hh"
#include "build.hh"
#include "pathlocks.hh"

#include <boost/shared_ptr.hpp>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

static string gcLockName = "gc.lock";
static string tempRootsDir = "temproots";
static string gcRootsDir = "gcroots";

/* Acquire the global GC lock.  This is used to prevent new Nix
   processes from starting after the temporary root files have been
   read.  To be precise: when they try to create a new temporary root
   file, they will block until the garbage collector has finished /
   yielded the GC lock. */
static int openGCLock(LockType lockType)
{
    Path fnGCLock = (format("%1%/%2%")
        % nixStateDir % gcLockName).str();

    debug(format("acquiring global GC lock `%1%'") % fnGCLock);

    AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600);
    if (fdGCLock == -1)
        throw SysError(format("opening global GC lock `%1%'") % fnGCLock);

    lockFile(fdGCLock, lockType, true);

    /* !!! Restrict read permission on the GC root.  Otherwise any
       process that can open the file for reading can DoS the
       collector. */

    return fdGCLock.borrow();
}

static void createDirs(const Path & path)
{
    if (path == "") return;
    createDirs(dirOf(path));
    if (!pathExists(path))
        if (mkdir(path.c_str(), 0777) == -1)
            throw SysError(format("creating directory `%1%'") % path);
}

void createSymlink(const Path & link, const Path & target, bool careful)
{
    /* Create directories up to `gcRoot'. */
    createDirs(dirOf(link));

    /* Remove the old symlink. */
    if (pathExists(link)) {
        if (careful && (!isLink(link) || !isInStore(readLink(link))))
            throw Error(format("cannot create symlink `%1%'; already exists") % link);
        unlink(link.c_str());
    }

    /* And create the new own. */
    if (symlink(target.c_str(), link.c_str()) == -1)
        throw SysError(format("symlinking `%1%' to `%2%'")
            % link % target);
}

Path addPermRoot(const Path & _storePath, const Path & _gcRoot,
    bool indirect)
{
    Path storePath(canonPath(_storePath));
    Path gcRoot(canonPath(_gcRoot));
    assertStorePath(storePath);

    /* Grab the global GC root.  This prevents the set of permanent
       roots from increasing while a GC is in progress. */
    AutoCloseFD fdGCLock = openGCLock(ltRead);

    if (indirect) {
        string hash = printHash32(hashString(htSHA1, gcRoot));
        Path realRoot = canonPath((format("%1%/%2%/auto/%3%")
            % nixStateDir % gcRootsDir % hash).str());

        createSymlink(gcRoot, storePath, true);
        createSymlink(realRoot, gcRoot, false);
    }

    else {
        Path rootsDir = canonPath((format("%1%/%2%") % nixStateDir % gcRootsDir).str());

        if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/")
            throw Error(format(
                "path `%1%' is not a valid garbage collector root; "
                "it's not in the directory `%2%'")
                % gcRoot % rootsDir);

        createSymlink(gcRoot, storePath, false);
    }

    return gcRoot;
}

/* The file to which we write our temporary roots. */
static Path fnTempRoots;
static AutoCloseFD fdTempRoots;

void addTempRoot(const Path & path)
{
    /* Create the temporary roots file for this process. */
    if (fdTempRoots == -1) {

        while (1) {
            fnTempRoots = (format("%1%/%2%/%3%")
                % nixStateDir % tempRootsDir % getpid()).str();

            AutoCloseFD fdGCLock = openGCLock(ltRead);

            fdTempRoots = open(fnTempRoots.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0600);
            if (fdTempRoots == -1)
                throw SysError(format("opening temporary roots file `%1%'") % fnTempRoots);

            fdGCLock.close();

            debug(format("acquiring read lock on `%1%'") % fnTempRoots);
            lockFile(fdTempRoots, ltRead, true);

            /* Check whether the garbage collector didn't get in our
               way. */
            struct stat st;
            if (fstat(fdTempRoots, &st) == -1)
                throw SysError(format("statting `%1%'") % fnTempRoots);
            if (st.st_size == 0) break;

            /* The garbage collector deleted this file before we could
               get a lock.  (It won't delete the file after we get a
               lock.)  Try again. */
        }

    }

    /* Upgrade the lock to a write lock.  This will cause us to block
       if the garbage collector is holding our lock. */
    debug(format("acquiring write lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltWrite, true);

    string s = path + '\0';
    writeFull(fdTempRoots, (const unsigned char *) s.c_str(), s.size());

    /* Downgrade to a read lock. */
    debug(format("downgrading to read lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltRead, true);
}

void removeTempRoots()
{
    if (fdTempRoots != -1) {
        fdTempRoots.close();
        unlink(fnTempRoots.c_str());
    }
}

typedef shared_ptr<AutoCloseFD> FDPtr;
typedef list<FDPtr> FDs;

static void readTempRoots(PathSet & tempRoots, FDs & fds)
{
    /* Read the `temproots' directory for per-process temporary root
       files. */
    Strings tempRootFiles = readDirectory(
        (format("%1%/%2%") % nixStateDir % tempRootsDir).str());

    for (Strings::iterator i = tempRootFiles.begin();
         i != tempRootFiles.end(); ++i)
    {
        Path path = (format("%1%/%2%/%3%") % nixStateDir % tempRootsDir % *i).str();

        debug(format("reading temporary root file `%1%'") % path);

        FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666)));
        if (*fd == -1) {
            /* It's okay if the file has disappeared. */
            if (errno == ENOENT) continue;
            throw SysError(format("opening temporary roots file `%1%'") % path);
        }

        /* Try to acquire a write lock without blocking.  This can
           only succeed if the owning process has died.  In that case
           we don't care about its temporary roots. */
        if (lockFile(*fd, ltWrite, false)) {
            printMsg(lvlError, format("removing stale temporary roots file `%1%'")
                % path);
            unlink(path.c_str());
            writeFull(*fd, (const unsigned char *) "d", 1);
            continue;
        }

        /* Acquire a read lock.  This will prevent the owning process
           from upgrading to a write lock, therefore it will block in
           addTempRoot(). */
        debug(format("waiting for read lock on `%1%'") % path);
        lockFile(*fd, ltRead, true);

        /* Read the entire file. */
        string contents = readFile(*fd);

        /* Extract the roots. */
        unsigned int pos = 0, end;

        while ((end = contents.find((char) 0, pos)) != string::npos) {
            Path root(contents, pos, end - pos);
            debug(format("got temporary root `%1%'") % root);
            assertStorePath(root);
            tempRoots.insert(root);
            pos = end + 1;
        }

        fds.push_back(fd); /* keep open */
    }
}

static void findRoots(const Path & path, bool recurseSymlinks,
    PathSet & roots)
{
    struct stat st;
    if (lstat(path.c_str(), &st) == -1)
        throw SysError(format("statting `%1%'") % path);

    printMsg(lvlVomit, format("looking at `%1%'") % path);

    if (S_ISDIR(st.st_mode)) {
	Strings names = readDirectory(path);
	for (Strings::iterator i = names.begin(); i != names.end(); ++i)
            findRoots(path + "/" + *i, recurseSymlinks, roots);
    }

    else if (S_ISLNK(st.st_mode)) {
        string target = readLink(path);
        Path target2 = absPath(target, dirOf(path));

        if (isInStore(target2)) {
            debug(format("found root `%1%' in `%2%'")
                % target2 % path);
            roots.insert(toStorePath(target2));
        }

        else if (recurseSymlinks) {
            if (pathExists(target2))
                findRoots(target2, false, roots);
            else {
                printMsg(lvlInfo, format("removing stale link from `%1%' to `%2%'") % path % target2);
                /* Note that we only delete when recursing, i.e., when
                   we are still in the `gcroots' tree.  We never
                   delete stuff outside that tree. */
                unlink(path.c_str());
            }
        }
    }
}

static void dfsVisit(const PathSet & paths, const Path & path,
    PathSet & visited, Paths & sorted)
{
    if (visited.find(path) != visited.end()) return;
    visited.insert(path);

    PathSet references;
    if (isValidPath(path))
        queryReferences(noTxn, path, references);

    for (PathSet::iterator i = references.begin();
         i != references.end(); ++i)
        /* Don't traverse into paths that don't exist.  That can
           happen due to substitutes for non-existent paths. */
        if (*i != path && paths.find(*i) != paths.end())
            dfsVisit(paths, *i, visited, sorted);

    sorted.push_front(path);
}

static Paths topoSort(const PathSet & paths)
{
    Paths sorted;
    PathSet visited;
    for (PathSet::const_iterator i = paths.begin(); i != paths.end(); ++i)
        dfsVisit(paths, *i, visited, sorted);
    return sorted;
}

void collectGarbage(GCAction action, PathSet & result)
{
    result.clear();

    bool gcKeepOutputs =
        queryBoolSetting("gc-keep-outputs", false);
    bool gcKeepDerivations =
        queryBoolSetting("gc-keep-derivations", true);

    /* Acquire the global GC root.  This prevents
       a) New roots from being added.
       b) Processes from creating new temporary root files. */
    AutoCloseFD fdGCLock = openGCLock(ltWrite);

    /* Find the roots.  Since we've grabbed the GC lock, the set of
       permanent roots cannot increase now. */
    Path rootsDir = canonPath((format("%1%/%2%") % nixStateDir % gcRootsDir).str());
    PathSet roots;
    findRoots(rootsDir, true, roots);

    if (action == gcReturnRoots) {
        result = roots;
        return;
    }

    /* Determine the live paths which is just the closure of the
       roots under the `references' relation. */
    PathSet livePaths;
    for (PathSet::const_iterator i = roots.begin(); i != roots.end(); ++i)
        computeFSClosure(canonPath(*i), livePaths);

    if (gcKeepDerivations) {
        for (PathSet::iterator i = livePaths.begin();
             i != livePaths.end(); ++i)
        {
            Path deriver = queryDeriver(noTxn, *i);
            if (deriver != "")
                computeFSClosure(deriver, livePaths);
        }
    }

    if (gcKeepOutputs) {
        /* Hmz, identical to storePathRequisites in nix-store. */
        for (PathSet::iterator i = livePaths.begin();
             i != livePaths.end(); ++i)
            if (isDerivation(*i)) {
                Derivation drv = derivationFromPath(*i);
                for (DerivationOutputs::iterator j = drv.outputs.begin();
                     j != drv.outputs.end(); ++j)
                    if (isValidPath(j->second.path))
                        computeFSClosure(j->second.path, livePaths);
            }
    }

    if (action == gcReturnLive) {
        result = livePaths;
        return;
    }

    /* Read the temporary roots.  This acquires read locks on all
       per-process temporary root files.  So after this point no paths
       can be added to the set of temporary roots. */
    PathSet tempRoots;
    FDs fds;
    readTempRoots(tempRoots, fds);

    /* Close the temporary roots.  Note that we *cannot* do this in
       readTempRoots(), because there we may not have all locks yet,
       meaning that an invalid path can become valid (and thus add to
       the references graph) after we have added it to the closure
       (and computeFSClosure() assumes that the presence of a path
       means that it has already been closed). */
    PathSet tempRootsClosed;
    for (PathSet::iterator i = tempRoots.begin(); i != tempRoots.end(); ++i)
        if (isValidPath(*i))
            computeFSClosure(*i, tempRootsClosed);
        else
            tempRootsClosed.insert(*i);

    /* For testing - see tests/gc-concurrent.sh. */
    if (getenv("NIX_DEBUG_GC_WAIT"))
        sleep(2);

    /* After this point the set of roots or temporary roots cannot
       increase, since we hold locks on everything.  So everything
       that is not currently in in `livePaths' or `tempRootsClosed'
       can be deleted. */

    /* Read the Nix store directory to find all currently existing
       paths. */
    Paths storePaths = readDirectory(nixStore);
    PathSet storePaths2;
    for (Paths::iterator i = storePaths.begin(); i != storePaths.end(); ++i)
        storePaths2.insert(canonPath(nixStore + "/" + *i));

    /* Topologically sort them under the `referers' relation.  That
       is, a < b iff a is in referers(b).  This gives us the order in
       which things can be deleted safely. */
    /* !!! when we have multiple output paths per derivation, this
       will not work anymore because we get cycles. */
    storePaths = topoSort(storePaths2);

    /* Try to delete store paths in the topologically sorted order. */
    for (Paths::iterator i = storePaths.begin(); i != storePaths.end(); ++i) {

        debug(format("considering deletion of `%1%'") % *i);

        if (livePaths.find(*i) != livePaths.end()) {
            debug(format("live path `%1%'") % *i);
            continue;
        }

        if (tempRootsClosed.find(*i) != tempRootsClosed.end()) {
            debug(format("temporary root `%1%'") % *i);
            continue;
        }

        debug(format("dead path `%1%'") % *i);
        result.insert(*i);

        AutoCloseFD fdLock;

        if (action == gcDeleteDead) {

            /* Only delete a lock file if we can acquire a write lock
               on it.  That means that it's either stale, or the
               process that created it hasn't locked it yet.  In the
               latter case the other process will detect that we
               deleted the lock, and retry (see pathlocks.cc). */
            if (i->size() >= 5 && string(*i, i->size() - 5) == ".lock") {

                fdLock = open(i->c_str(), O_RDWR);
                if (fdLock == -1) {
                    if (errno == ENOENT) continue;
                    throw SysError(format("opening lock file `%1%'") % *i);
                }

                if (!lockFile(fdLock, ltWrite, false)) {
                    debug(format("skipping active lock `%1%'") % *i);
                    continue;
                }
            }

            printMsg(lvlInfo, format("deleting `%1%'") % *i);

            /* Okay, it's safe to delete. */
            deleteFromStore(*i);

            if (fdLock != -1)
                /* Write token to stale (deleted) lock file. */
                writeFull(fdLock, (const unsigned char *) "d", 1);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Simplify.<commit_after><|endoftext|>