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

#include "LIEF/ELF/Binary.hpp"
#include "LIEF/Abstract/Binary.hpp"

#include "pyELF.hpp"

template<class T>
using no_const_getter = T (Binary::*)(void);

template<class T, class P>
using no_const_func = T (Binary::*)(P);

void init_ELF_Binary_class(py::module& m) {

  // Binary object
  py::class_<Binary, LIEF::Binary>(m, "Binary", "ELF binary representation")
    .def(py::init<const std::string&, ELF_CLASS>())

    .def_property_readonly("type",
        &Binary::type,
        "Return the binary's " RST_CLASS_REF(lief.ELF.ELF_CLASS) "")

    .def_property_readonly("header",
        static_cast<no_const_getter<Header&>>(&Binary::get_header),
        "Return " RST_CLASS_REF(lief.ELF.Header) " object",
        py::return_value_policy::reference_internal)

    .def_property_readonly("sections",
        static_cast<no_const_getter<it_sections>>(&Binary::get_sections),
        "Return an iterator to binary's " RST_CLASS_REF(lief.ELF.Section) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("segments",
        static_cast<no_const_getter<it_segments>>(&Binary::get_segments),
        "Return an interator to binary's " RST_CLASS_REF(lief.ELF.Segment) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_entries",
        static_cast<no_const_getter<it_dynamic_entries>>(&Binary::get_dynamic_entries),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.DynamicEntry) " entries as a list",
        py::return_value_policy::reference_internal)

    .def_property_readonly("static_symbols",
        static_cast<no_const_getter<it_symbols>>(&Binary::get_static_symbols),
        "Return an iterator to static  " RST_CLASS_REF(lief.ELF.Symbol) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_symbols",
        static_cast<no_const_getter<it_symbols>>(&Binary::get_dynamic_symbols),
        "Return an iterator to dynamic  " RST_CLASS_REF(lief.ELF.Symbol) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("exported_symbols",
        static_cast<no_const_getter<it_exported_symbols>>(&Binary::get_exported_symbols),
        "Return dynamic " RST_CLASS_REF(lief.ELF.Symbol) " which are exported",
        py::return_value_policy::reference_internal)

    .def_property_readonly("imported_symbols",
        static_cast<no_const_getter<it_imported_symbols>>(&Binary::get_imported_symbols),
        "Return dynamic  " RST_CLASS_REF(lief.ELF.Symbol) " which are imported",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_relocations",
        static_cast<no_const_getter<it_dynamic_relocations>>(&Binary::get_dynamic_relocations),
        "Return an iterator over PLT/GOT " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("pltgot_relocations",
        static_cast<no_const_getter<it_pltgot_relocations>>(&Binary::get_pltgot_relocations),
        "Return an iterator over dynamics " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("object_relocations",
        static_cast<no_const_getter<it_object_relocations>>(&Binary::get_object_relocations),
        "Return an iterator over object " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("relocations",
        static_cast<no_const_getter<it_relocations>>(&Binary::get_relocations),
        "Return an iterator over **all** " RST_CLASS_REF(lief.ELF.Relocation) "s",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version",
        static_cast<no_const_getter<it_symbols_version>>(&Binary::get_symbols_version),
        "Return an iterator " RST_CLASS_REF(lief.ELF.SymbolVersion) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version_requirement",
        static_cast<no_const_getter<it_symbols_version_requirement>>(&Binary::get_symbols_version_requirement),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.SymbolVersionRequirement) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version_definition",
        static_cast<no_const_getter<it_symbols_version_definition>>(&Binary::get_symbols_version_definition),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.SymbolVersionDefinition) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("use_gnu_hash",
        &Binary::use_gnu_hash,
        "``True`` if GNU hash is used")

    .def_property_readonly("gnu_hash",
        &Binary::get_gnu_hash,
        "Return the " RST_CLASS_REF(lief.ELF.GnuHash) " object\n\n"
        "Hash are used by the loader to speed up symbols resolving (GNU Version)",
        py::return_value_policy::reference_internal)

    .def_property_readonly("use_sysv_hash",
        &Binary::use_sysv_hash,
        "``True`` if SYSV hash is used")

    .def_property_readonly("sysv_hash",
        &Binary::get_sysv_hash,
        "Return the " RST_CLASS_REF(lief.ELF.SysvHash) " object\n\n"
        "Hash are used by the loader to speed up symbols resolving (SYSV version)",
        py::return_value_policy::reference_internal)

   .def_property_readonly("imagebase",
        &Binary::get_imagebase,
       "Return the program image base. (e.g. ``0x400000``)")

   .def_property_readonly("virtual_size",
        &Binary::get_virtual_size,
       "Return the binary's size when mapped in memory")

   .def_property_readonly("is_pie",
        &Binary::is_pie,
       "``True`` if the binary is a ``pie`` one")

   .def_property_readonly("has_interpreter",
        &Binary::has_interpreter,
       "``True`` if the binary uses a loader")

   .def_property_readonly("interpreter",
        &Binary::get_interpreter,
       "Return ELF interprer (loader) if any. (e.g. ``/lib64/ld-linux-x86-64.so.2``)")

    .def("section_from_offset",
        static_cast<no_const_func<Section&, uint64_t>>(&Binary::section_from_offset),
        "Return binary's " RST_CLASS_REF(lief.ELF.Section) " which holds the offset",
        "offset"_a,
        py::return_value_policy::reference)

    .def("section_from_virtual_address",
        static_cast<no_const_func<Section&, uint64_t>>(&Binary::section_from_virtual_address),
        "Return binary's " RST_CLASS_REF(lief.ELF.Section) " which holds the given virtual address",
        "address"_a,
        py::return_value_policy::reference)

    .def("segment_from_virtual_address",
        static_cast<no_const_func<Segment&, uint64_t>>(&Binary::segment_from_virtual_address),
        "Return binary's " RST_CLASS_REF(lief.ELF.Segment) " which holds the address",
        "address"_a,
        py::return_value_policy::reference)

    .def("segment_from_offset",
        static_cast<no_const_func<Segment&, uint64_t>>(&Binary::segment_from_offset),
        "Return binary's " RST_CLASS_REF(lief.ELF.Segment) " which holds the offset",
        "offset"_a,
        py::return_value_policy::reference)

    .def("dynamic_entry_from_tag",
        static_cast<no_const_func<DynamicEntry&, DYNAMIC_TAGS>>(&Binary::dynamic_entry_from_tag),
        "Return first binary's " RST_CLASS_REF(lief.ELF.DynamicEntry) " given its " RST_CLASS_REF(lief.ELF.DYNAMIC_TAGS) "",
        "tag"_a,
        py::return_value_policy::reference)

    .def("has_dynamic_entry",
        &Binary::has_dynamic_entry,
        "Check if the " RST_CLASS_REF(lief.ELF.DynamicEntry) " associated with the given " RST_CLASS_REF(lief.ELF.DYNAMIC_TAGS) " exists",
        "tag"_a)

    .def("patch_pltgot",
        static_cast<void (Binary::*) (const std::string&, uint64_t)>(&Binary::patch_pltgot),
        "Patch the imported symbol's name with the ``address``",
        "symbol_name"_a, "address"_a)

    .def("patch_pltgot",
        static_cast<void (Binary::*) (const Symbol&, uint64_t)>(&Binary::patch_pltgot),
        "Patch the imported " RST_CLASS_REF(lief.ELF.Symbol) " with the ``address``",
        "symbol"_a, "address"_a)

    .def("has_section",
        &Binary::has_section,
        "Check if a section with the given name exists in the binary",
        "section_name"_a)

    .def("get_section",
        static_cast<no_const_func<Section&, const std::string&>>(&Binary::get_section),
        "Return the " RST_CLASS_REF(lief.ELF.Section) " with the given ``name``",
        "section_name"_a,
        py::return_value_policy::reference)

    .def("add_static_symbol",
        &Binary::add_static_symbol,
        "Add a **static** " RST_CLASS_REF(lief.ELF.Symbol) " to the binary",
        "symbol"_a,
        py::return_value_policy::reference)

    .def("virtual_address_to_offset",
        &Binary::virtual_address_to_offset,
        "Convert the virtual address to an offset in the binary",
        "virtual_address"_a)

    .def("add_section",
        &Binary::add_section,
        "Add the given " RST_CLASS_REF(lief.ELF.Section) " to the binary. \n\n"
        "If the section must not be loaded in memory, you have to set the ``loaded`` parameter to ``False`` (default: ``True``)",
        "section"_a, py::arg("loaded") = true,
        py::return_value_policy::reference)

    .def("add_segment",
        &Binary::add_segment,
        "Add a segment in the binary",
        py::arg("segment"), py::arg_v("base", 0x400000), py::arg_v("force_note", false),
        py::return_value_policy::reference)

    .def("insert_content",
        &Binary::insert_content,
        "Add some data in the binary and return the (``offset``, ``size``) of the inserted content\n\n"
        ".. warning:: This method should be used only for **libraries**\n\n",
        "content"_a)

    .def_property_readonly("has_notes",
        &Binary::has_notes,
        "``True`` if the binary contains notes")

    .def_property_readonly("notes",
        static_cast<no_const_getter<it_notes>>(&Binary::notes),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.Note) " entries as a list",
        py::return_value_policy::reference_internal)

    .def("strip",
        &Binary::strip,
        "Strip the binary")

    .def("permute_dynamic_symbols",
        &Binary::permute_dynamic_symbols,
        "Apply the given permutation on the dynamic symbols table",
        "permutation"_a)

    .def("write",
        &Binary::write,
        "Rebuild the binary and write it in a file",
        "output"_a,
        py::return_value_policy::reference_internal)

    .def("__str__",
        [] (const Binary& binary)
        {
          std::ostringstream stream;
          stream << binary;
          std::string str = stream.str();
          return str;
        });
}
<commit_msg>Fix typo<commit_after>/* Copyright 2017 R. Thomas
 * Copyright 2017 Quarkslab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <algorithm>

#include "LIEF/ELF/Binary.hpp"
#include "LIEF/Abstract/Binary.hpp"

#include "pyELF.hpp"

template<class T>
using no_const_getter = T (Binary::*)(void);

template<class T, class P>
using no_const_func = T (Binary::*)(P);

void init_ELF_Binary_class(py::module& m) {

  // Binary object
  py::class_<Binary, LIEF::Binary>(m, "Binary", "ELF binary representation")
    .def(py::init<const std::string&, ELF_CLASS>())

    .def_property_readonly("type",
        &Binary::type,
        "Return the binary's " RST_CLASS_REF(lief.ELF.ELF_CLASS) "")

    .def_property_readonly("header",
        static_cast<no_const_getter<Header&>>(&Binary::get_header),
        "Return " RST_CLASS_REF(lief.ELF.Header) " object",
        py::return_value_policy::reference_internal)

    .def_property_readonly("sections",
        static_cast<no_const_getter<it_sections>>(&Binary::get_sections),
        "Return an iterator to binary's " RST_CLASS_REF(lief.ELF.Section) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("segments",
        static_cast<no_const_getter<it_segments>>(&Binary::get_segments),
        "Return an interator to binary's " RST_CLASS_REF(lief.ELF.Segment) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_entries",
        static_cast<no_const_getter<it_dynamic_entries>>(&Binary::get_dynamic_entries),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.DynamicEntry) " entries as a list",
        py::return_value_policy::reference_internal)

    .def_property_readonly("static_symbols",
        static_cast<no_const_getter<it_symbols>>(&Binary::get_static_symbols),
        "Return an iterator to static  " RST_CLASS_REF(lief.ELF.Symbol) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_symbols",
        static_cast<no_const_getter<it_symbols>>(&Binary::get_dynamic_symbols),
        "Return an iterator to dynamic  " RST_CLASS_REF(lief.ELF.Symbol) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("exported_symbols",
        static_cast<no_const_getter<it_exported_symbols>>(&Binary::get_exported_symbols),
        "Return dynamic " RST_CLASS_REF(lief.ELF.Symbol) " which are exported",
        py::return_value_policy::reference_internal)

    .def_property_readonly("imported_symbols",
        static_cast<no_const_getter<it_imported_symbols>>(&Binary::get_imported_symbols),
        "Return dynamic  " RST_CLASS_REF(lief.ELF.Symbol) " which are imported",
        py::return_value_policy::reference_internal)

    .def_property_readonly("dynamic_relocations",
        static_cast<no_const_getter<it_dynamic_relocations>>(&Binary::get_dynamic_relocations),
        "Return an iterator over PLT/GOT " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("pltgot_relocations",
        static_cast<no_const_getter<it_pltgot_relocations>>(&Binary::get_pltgot_relocations),
        "Return an iterator over dynamics " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("object_relocations",
        static_cast<no_const_getter<it_object_relocations>>(&Binary::get_object_relocations),
        "Return an iterator over object " RST_CLASS_REF(lief.ELF.Relocation) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("relocations",
        static_cast<no_const_getter<it_relocations>>(&Binary::get_relocations),
        "Return an iterator over **all** " RST_CLASS_REF(lief.ELF.Relocation) " s",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version",
        static_cast<no_const_getter<it_symbols_version>>(&Binary::get_symbols_version),
        "Return an iterator " RST_CLASS_REF(lief.ELF.SymbolVersion) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version_requirement",
        static_cast<no_const_getter<it_symbols_version_requirement>>(&Binary::get_symbols_version_requirement),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.SymbolVersionRequirement) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("symbols_version_definition",
        static_cast<no_const_getter<it_symbols_version_definition>>(&Binary::get_symbols_version_definition),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.SymbolVersionDefinition) "",
        py::return_value_policy::reference_internal)

    .def_property_readonly("use_gnu_hash",
        &Binary::use_gnu_hash,
        "``True`` if GNU hash is used")

    .def_property_readonly("gnu_hash",
        &Binary::get_gnu_hash,
        "Return the " RST_CLASS_REF(lief.ELF.GnuHash) " object\n\n"
        "Hash are used by the loader to speed up symbols resolving (GNU Version)",
        py::return_value_policy::reference_internal)

    .def_property_readonly("use_sysv_hash",
        &Binary::use_sysv_hash,
        "``True`` if SYSV hash is used")

    .def_property_readonly("sysv_hash",
        &Binary::get_sysv_hash,
        "Return the " RST_CLASS_REF(lief.ELF.SysvHash) " object\n\n"
        "Hash are used by the loader to speed up symbols resolving (SYSV version)",
        py::return_value_policy::reference_internal)

   .def_property_readonly("imagebase",
        &Binary::get_imagebase,
       "Return the program image base. (e.g. ``0x400000``)")

   .def_property_readonly("virtual_size",
        &Binary::get_virtual_size,
       "Return the binary's size when mapped in memory")

   .def_property_readonly("is_pie",
        &Binary::is_pie,
       "``True`` if the binary is a ``pie`` one")

   .def_property_readonly("has_interpreter",
        &Binary::has_interpreter,
       "``True`` if the binary uses a loader")

   .def_property_readonly("interpreter",
        &Binary::get_interpreter,
       "Return ELF interprer (loader) if any. (e.g. ``/lib64/ld-linux-x86-64.so.2``)")

    .def("section_from_offset",
        static_cast<no_const_func<Section&, uint64_t>>(&Binary::section_from_offset),
        "Return binary's " RST_CLASS_REF(lief.ELF.Section) " which holds the offset",
        "offset"_a,
        py::return_value_policy::reference)

    .def("section_from_virtual_address",
        static_cast<no_const_func<Section&, uint64_t>>(&Binary::section_from_virtual_address),
        "Return binary's " RST_CLASS_REF(lief.ELF.Section) " which holds the given virtual address",
        "address"_a,
        py::return_value_policy::reference)

    .def("segment_from_virtual_address",
        static_cast<no_const_func<Segment&, uint64_t>>(&Binary::segment_from_virtual_address),
        "Return binary's " RST_CLASS_REF(lief.ELF.Segment) " which holds the address",
        "address"_a,
        py::return_value_policy::reference)

    .def("segment_from_offset",
        static_cast<no_const_func<Segment&, uint64_t>>(&Binary::segment_from_offset),
        "Return binary's " RST_CLASS_REF(lief.ELF.Segment) " which holds the offset",
        "offset"_a,
        py::return_value_policy::reference)

    .def("dynamic_entry_from_tag",
        static_cast<no_const_func<DynamicEntry&, DYNAMIC_TAGS>>(&Binary::dynamic_entry_from_tag),
        "Return first binary's " RST_CLASS_REF(lief.ELF.DynamicEntry) " given its " RST_CLASS_REF(lief.ELF.DYNAMIC_TAGS) "",
        "tag"_a,
        py::return_value_policy::reference)

    .def("has_dynamic_entry",
        &Binary::has_dynamic_entry,
        "Check if the " RST_CLASS_REF(lief.ELF.DynamicEntry) " associated with the given " RST_CLASS_REF(lief.ELF.DYNAMIC_TAGS) " exists",
        "tag"_a)

    .def("patch_pltgot",
        static_cast<void (Binary::*) (const std::string&, uint64_t)>(&Binary::patch_pltgot),
        "Patch the imported symbol's name with the ``address``",
        "symbol_name"_a, "address"_a)

    .def("patch_pltgot",
        static_cast<void (Binary::*) (const Symbol&, uint64_t)>(&Binary::patch_pltgot),
        "Patch the imported " RST_CLASS_REF(lief.ELF.Symbol) " with the ``address``",
        "symbol"_a, "address"_a)

    .def("has_section",
        &Binary::has_section,
        "Check if a section with the given name exists in the binary",
        "section_name"_a)

    .def("get_section",
        static_cast<no_const_func<Section&, const std::string&>>(&Binary::get_section),
        "Return the " RST_CLASS_REF(lief.ELF.Section) " with the given ``name``",
        "section_name"_a,
        py::return_value_policy::reference)

    .def("add_static_symbol",
        &Binary::add_static_symbol,
        "Add a **static** " RST_CLASS_REF(lief.ELF.Symbol) " to the binary",
        "symbol"_a,
        py::return_value_policy::reference)

    .def("virtual_address_to_offset",
        &Binary::virtual_address_to_offset,
        "Convert the virtual address to an offset in the binary",
        "virtual_address"_a)

    .def("add_section",
        &Binary::add_section,
        "Add the given " RST_CLASS_REF(lief.ELF.Section) " to the binary. \n\n"
        "If the section must not be loaded in memory, you have to set the ``loaded`` parameter to ``False`` (default: ``True``)",
        "section"_a, py::arg("loaded") = true,
        py::return_value_policy::reference)

    .def("add_segment",
        &Binary::add_segment,
        "Add a segment in the binary",
        py::arg("segment"), py::arg_v("base", 0x400000), py::arg_v("force_note", false),
        py::return_value_policy::reference)

    .def("insert_content",
        &Binary::insert_content,
        "Add some data in the binary and return the (``offset``, ``size``) of the inserted content\n\n"
        ".. warning:: This method should be used only for **libraries**\n\n",
        "content"_a)

    .def_property_readonly("has_notes",
        &Binary::has_notes,
        "``True`` if the binary contains notes")

    .def_property_readonly("notes",
        static_cast<no_const_getter<it_notes>>(&Binary::notes),
        "Return an iterator to " RST_CLASS_REF(lief.ELF.Note) " entries as a list",
        py::return_value_policy::reference_internal)

    .def("strip",
        &Binary::strip,
        "Strip the binary")

    .def("permute_dynamic_symbols",
        &Binary::permute_dynamic_symbols,
        "Apply the given permutation on the dynamic symbols table",
        "permutation"_a)

    .def("write",
        &Binary::write,
        "Rebuild the binary and write it in a file",
        "output"_a,
        py::return_value_policy::reference_internal)

    .def("__str__",
        [] (const Binary& binary)
        {
          std::ostringstream stream;
          stream << binary;
          std::string str = stream.str();
          return str;
        });
}
<|endoftext|>


<commit_before>/*
 * Task.cc
 *
 *  Created on: Feb 27, 2014
 */

#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{

volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 2;

Task::Task(void (*entry_point)(void), int nargs, void * arg) {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
	this->_tid = Task::__tid_counter++;
	getcontext(&(this->context));
	this->context.uc_link          = (ucontext_t*) &(Task::__running->context);
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}

Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
	this->_tid = Task::__tid_counter++;
	getcontext(&(this->context));
	this->context.uc_link          = (ucontext_t*) &(Task::__running->context);
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}

Task::Task() {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	this->_tid = 0;
}

Task::~Task() {
	delete this->_stack;
}

void Task::pass_to(Task *t, State s) {
	this->_state = s;
	Task::__running = t;
	t->_state = Task::RUNNING;
	swapcontext(&(this->context), &(t->context));
}

void Task::init() {
	Task::__tid_counter = 2;
	Task::__main = new Task();
	Task::__running = Task::__main;
	Task::__running->_state = Task::RUNNING;
}

void Task::exit(int code) {
	this->pass_to(Task::__main, Task::FINISHING);
}

} /* namespace BOOOS */
<commit_msg>Fix the Task class to pass the creation and destruction test<commit_after>/*
 * Task.cc
 *
 *  Created on: Feb 27, 2014
 */

#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{

volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 1;

Task::Task(void (*entry_point)(void), int nargs, void * arg) {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
	this->_tid = ++Task::__tid_counter;
	getcontext(&(this->context));
	this->context.uc_link          = (ucontext_t*) &(Task::__running->context);
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}

Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
	this->_tid = ++Task::__tid_counter;
	getcontext(&(this->context));
	this->context.uc_link          = (ucontext_t*) &(Task::__running->context);
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}

Task::Task() {
	this->_state = Task::READY;
	this->_stack = new char[Task::STACK_SIZE];
    this->context.uc_stack.ss_sp   = this->_stack;
    this->context.uc_stack.ss_size = Task::STACK_SIZE;
	this->_tid = 0;
}

Task::~Task() {
	delete this->_stack;
}

void Task::pass_to(Task *t, State s) {
	this->_state = s;
	Task::__running = t;
	t->_state = Task::RUNNING;
	swapcontext(&(this->context), &(t->context));
}

void Task::init() {
	Task::__tid_counter = 1;
	Task::__main = new Task();
	Task::__running = Task::__main;
	Task::__running->_state = Task::RUNNING;
}

void Task::exit(int code) {
	this->pass_to(Task::__main, Task::FINISHING);
}

} /* namespace BOOOS */
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

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

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

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

namespace Ogre {
#ifndef OGRE_STATIC_LIB
    Codec *mEXRCodec;

    //-----------------------------------------------------------------------
    extern "C" _OgreEXRPluginExport void dllStartPlugin(void)
    {
        mEXRCodec = new EXRCodec;
        Codec::registerCodec( mEXRCodec );
    }
    extern "C" _OgreEXRPluginExport void dllStopPlugin(void)
    {
        Codec::unregisterCodec( mEXRCodec );
        delete mEXRCodec;
    }

}
#endif
<commit_msg>Fixed build error when compiling as static lib.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

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

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

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

#ifndef OGRE_STATIC_LIB
namespace Ogre {
    Codec *mEXRCodec;

    //-----------------------------------------------------------------------
    extern "C" _OgreEXRPluginExport void dllStartPlugin(void)
    {
        mEXRCodec = new EXRCodec;
        Codec::registerCodec( mEXRCodec );
    }
    extern "C" _OgreEXRPluginExport void dllStopPlugin(void)
    {
        Codec::unregisterCodec( mEXRCodec );
        delete mEXRCodec;
    }

}
#endif
<|endoftext|>


<commit_before>/*
    Copyright 2013 KU Leuven, Dept. Electrical Engineering, Medical Image Computing
    Herestraat 49 box 7003, 3000 Leuven, Belgium

    Written by Daan Christiaens, 01/07/13.

    This file is part of the Global Tractography module for MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "externalenergy.h"

#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "math/SH.h"
#include "algo/loop.h"

//#include "math/lsnonneg.h"

namespace MR {
  namespace DWI {
    namespace Tractography {
      namespace GT {

        ExternalEnergyComputer::ExternalEnergyComputer(Stats& stat, const Image<float>& dwimage, const Properties& props)
          : EnergyComputer(stat),
            dwi(dwimage),
            T(Transform(dwimage).scanner2voxel),
            lmax(props.Lmax), ncols(Math::SH::NforL(lmax)), nf(props.resp_ISO.size()),
            beta(props.beta), mu(props.ppot*M_sqrt4PI), dE(0.0)
        {
          DEBUG("Initialise computation of external energy.");
          // Create images --------------------------------------------------------------
          Header header (dwimage);
          header.datatype() = DataType::Float32;
          header.size(3) = ncols;
          tod = Image<float>::scratch(header, "TOD image");

          if (nf > 0) {
            WARN("No isotropic response functions provided; using single-tissue white matter model.");
            header.size(3) = nf;
            fiso = Image<float>::scratch(header, "isotropic fractions");
          }

          header.set_ndim(3);
          eext = Image<float>::scratch(header, "external energy");

          // Set kernel matrices --------------------------------------------------------
          auto grad = DWI::get_DW_scheme(dwimage);
          nrows = grad.rows();
          DWI::Shells shells (grad);

          if (props.resp_WM.rows() != shells.count())
            FAIL("WM kernel size does not match the no. b-values in the image.");
          for (size_t j = 0; j < props.resp_ISO.size(); j++) {
            if (props.resp_ISO[j].size() != shells.count())
              FAIL("Isotropic kernel size does not match the no. b-values in the image.");
          }

          K.resize(nrows, ncols);
          K.setZero();
          Ak.resize(nrows, nf+1);
          Ak.setZero();

          Eigen::VectorXd delta_vec (ncols);
          Eigen::VectorXd wmr_sh (lmax/2+1), wmr_rh (lmax/2+1);
          wmr_sh.setZero();
          Eigen::Vector3d unit_dir;
          double wmr0;

          for (size_t s = 0; s < shells.count(); s++)
          {
            for (int l = 0; l <= lmax/2; l++)
              wmr_sh[l] = (l < props.resp_WM.cols()) ? props.resp_WM(s, l) : 0.0;
            wmr_rh = Math::SH::SH2RH(wmr_sh);
            wmr0 = props.resp_WM(s,0) / std::sqrt(4*M_PI);

            for (size_t r : shells[s].get_volumes())
            {
              // K
              unit_dir << grad(r,0), grad(r,1), grad(r,2);
              double n = unit_dir.norm();
              if (n > 0.0)
                unit_dir /= n;
              Math::SH::delta(delta_vec, unit_dir, lmax);
              Math::SH::sconv(delta_vec, wmr_rh, delta_vec);
              K.row(r) = delta_vec;
              // Ak
              Ak(r,0) = wmr0;
              for (size_t j = 0; j < props.resp_ISO.size(); j++)
                Ak(r,j+1) = props.resp_ISO[j][s];
            }
          }
          K *= props.weight;

          // Allocate temporary memory --------------------------------------------------
          y.resize(nrows);
          t.resize(ncols);
          d.resize(ncols);
          fk.resize(nf+1);

          // Set NNLS solver ------------------------------------------------------------
          nnls = Math::ICLS::Problem<double>(Ak, Eigen::MatrixXd::Identity(nf+1, nf+1));

          // Reset energy ---------------------------------------------------------------
          resetEnergy();
        }

        void ExternalEnergyComputer::resetEnergy()
        {
          DEBUG("Reset external energy.");
          double e;
          dE = 0.0;
          for (auto l = Loop(dwi, 0, 3) (dwi, tod, eext); l; ++l)
          {
            y = dwi.row(3).cast<double>();
            t = tod.row(3).cast<double>();
            e = calcEnergy();
            eext.value() = e;
            dE += e;
          }
          stats.incEextTotal(dE - stats.getEextTotal());
          dE = 0.0;
        }

        void ExternalEnergyComputer::acceptChanges()
        {
          for (int k = 0; k != changes_vox.size(); ++k)
          {
            assign_pos_of(changes_vox[k], 0, 3).to(tod, eext);
            assert(!is_out_of_bounds(tod));
            tod.row(3) = changes_tod[k].cast<float>();
            eext.value() = changes_eext[k];
            if (fiso.valid()) {
              assign_pos_of(changes_vox[k], 0, 3).to(fiso);
              fiso.row(3) = changes_fiso[k].cast<float>();
            }
          }
          stats.incEextTotal(dE);
          clearChanges();
        }

        void ExternalEnergyComputer::clearChanges()
        {
          changes_vox.clear();
          changes_tod.clear();
          changes_fiso.clear();
          changes_eext.clear();
          dE = 0.0;
        }

        void ExternalEnergyComputer::add(const Point_t &pos, const Point_t &dir, const double factor)
        {
          Point_t p = T.cast<float>() * pos;
          Point_t v = Point_t(Math::floor<float>(p[0]), Math::floor<float>(p[1]), Math::floor<float>(p[2]));
          Point_t w = Point_t(hanning(p[0]-v[0]), hanning(p[1]-v[1]), hanning(p[2]-v[2]));

          Math::SH::delta(d, dir, lmax);

          Eigen::Vector3i x = v.cast<int>();
          add2vox(x, factor*(1.-w[0])*(1.-w[1])*(1.-w[2]));
          x[2]++;
          add2vox(x, factor*(1.-w[0])*(1.-w[1])*w[2]);
          x[1]++;
          add2vox(x, factor*(1.-w[0])*w[1]*w[2]);
          x[2]--;
          add2vox(x, factor*(1.-w[0])*w[1]*(1.-w[2]));
          x[0]++;
          add2vox(x, factor*w[0]*w[1]*(1.-w[2]));
          x[2]++;
          add2vox(x, factor*w[0]*w[1]*w[2]);
          x[1]--;
          add2vox(x, factor*w[0]*(1.-w[1])*w[2]);
          x[2]--;
          add2vox(x, factor*w[0]*(1.-w[1])*(1.-w[2]));
        }

        void ExternalEnergyComputer::add2vox(const Eigen::Vector3i& vox, const double w)
        {
          if (w == 0.0)
            return;
          assign_pos_of(vox, 0, 3).to(tod);
          if (is_out_of_bounds(tod))
            return;
          t = w * d;
          for (int k = 0; k != changes_vox.size(); ++k) {
            if (changes_vox[k] == vox) {
              changes_tod[k] += t;
              return;
            }
          }
          changes_vox.push_back(vox);
          t += tod.row(3).cast<double>();
          changes_tod.push_back(t);
        }

        double ExternalEnergyComputer::eval()
        {
          dE = 0.0;
          double e;
          for (int k = 0; k != changes_vox.size(); ++k)
          {
            assign_pos_of(changes_vox[k], 0, 3).to(dwi, eext);
            assert(!is_out_of_bounds(dwi));
            y = dwi.row(3).cast<double>();
            t = changes_tod[k];
            e = calcEnergy();
            changes_fiso.push_back(fk.tail(nf));
            dE += e;
            dE -= eext.value();
            changes_eext.push_back(e);
          }
          return dE / stats.getText();
        }

        double ExternalEnergyComputer::calcEnergy()
        {
          y.noalias() -= K * t;
          Math::ICLS::Solver<double> nnls_solver (nnls);
          nnls_solver(fk, y);
          y.noalias() -= Ak.rightCols(nf) * fk.tail(nf);
          return y.squaredNorm() / nrows + mu * t[0];     // MSE + L1 regularizer
        }

      }
    }
  }
}

<commit_msg>Fix mistake introduced in 33207e7.<commit_after>/*
    Copyright 2013 KU Leuven, Dept. Electrical Engineering, Medical Image Computing
    Herestraat 49 box 7003, 3000 Leuven, Belgium

    Written by Daan Christiaens, 01/07/13.

    This file is part of the Global Tractography module for MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "externalenergy.h"

#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "math/SH.h"
#include "algo/loop.h"

//#include "math/lsnonneg.h"

namespace MR {
  namespace DWI {
    namespace Tractography {
      namespace GT {

        ExternalEnergyComputer::ExternalEnergyComputer(Stats& stat, const Image<float>& dwimage, const Properties& props)
          : EnergyComputer(stat),
            dwi(dwimage),
            T(Transform(dwimage).scanner2voxel),
            lmax(props.Lmax), ncols(Math::SH::NforL(lmax)), nf(props.resp_ISO.size()),
            beta(props.beta), mu(props.ppot*M_sqrt4PI), dE(0.0)
        {
          DEBUG("Initialise computation of external energy.");

          // Create images --------------------------------------------------------------
          Header header (dwimage);
          header.datatype() = DataType::Float32;
          header.size(3) = ncols;
          tod = Image<float>::scratch(header, "TOD image");

          if (nf > 0) {
            header.size(3) = nf;
            fiso = Image<float>::scratch(header, "isotropic fractions");
          } else {
            WARN("No isotropic response functions provided; using single-tissue white matter model.");
          }

          header.set_ndim(3);
          eext = Image<float>::scratch(header, "external energy");

          // Set kernel matrices --------------------------------------------------------
          auto grad = DWI::get_DW_scheme(dwimage);
          nrows = grad.rows();
          DWI::Shells shells (grad);

          if (props.resp_WM.rows() != shells.count())
            FAIL("WM kernel size does not match the no. b-values in the image.");
          for (size_t j = 0; j < props.resp_ISO.size(); j++) {
            if (props.resp_ISO[j].size() != shells.count())
              FAIL("Isotropic kernel size does not match the no. b-values in the image.");
          }

          K.resize(nrows, ncols);
          K.setZero();
          Ak.resize(nrows, nf+1);
          Ak.setZero();

          Eigen::VectorXd delta_vec (ncols);
          Eigen::VectorXd wmr_sh (lmax/2+1), wmr_rh (lmax/2+1);
          wmr_sh.setZero();
          Eigen::Vector3d unit_dir;
          double wmr0;

          for (size_t s = 0; s < shells.count(); s++)
          {
            for (int l = 0; l <= lmax/2; l++)
              wmr_sh[l] = (l < props.resp_WM.cols()) ? props.resp_WM(s, l) : 0.0;
            wmr_rh = Math::SH::SH2RH(wmr_sh);
            wmr0 = props.resp_WM(s,0) / std::sqrt(4*M_PI);

            for (size_t r : shells[s].get_volumes())
            {
              // K
              unit_dir << grad(r,0), grad(r,1), grad(r,2);
              double n = unit_dir.norm();
              if (n > 0.0)
                unit_dir /= n;
              Math::SH::delta(delta_vec, unit_dir, lmax);
              Math::SH::sconv(delta_vec, wmr_rh, delta_vec);
              K.row(r) = delta_vec;
              // Ak
              Ak(r,0) = wmr0;
              for (size_t j = 0; j < props.resp_ISO.size(); j++)
                Ak(r,j+1) = props.resp_ISO[j][s];
            }
          }
          K *= props.weight;

          // Allocate temporary memory --------------------------------------------------
          y.resize(nrows);
          t.resize(ncols);
          d.resize(ncols);
          fk.resize(nf+1);

          // Set NNLS solver ------------------------------------------------------------
          nnls = Math::ICLS::Problem<double>(Ak, Eigen::MatrixXd::Identity(nf+1, nf+1));

          // Reset energy ---------------------------------------------------------------
          resetEnergy();
        }

        void ExternalEnergyComputer::resetEnergy()
        {
          DEBUG("Reset external energy.");
          double e;
          dE = 0.0;
          for (auto l = Loop(dwi, 0, 3) (dwi, tod, eext); l; ++l)
          {
            y = dwi.row(3).cast<double>();
            t = tod.row(3).cast<double>();
            e = calcEnergy();
            eext.value() = e;
            dE += e;
          }
          stats.incEextTotal(dE - stats.getEextTotal());
          dE = 0.0;
        }

        void ExternalEnergyComputer::acceptChanges()
        {
          for (int k = 0; k != changes_vox.size(); ++k)
          {
            assign_pos_of(changes_vox[k], 0, 3).to(tod, eext);
            assert(!is_out_of_bounds(tod));
            tod.row(3) = changes_tod[k].cast<float>();
            eext.value() = changes_eext[k];
            if (fiso.valid()) {
              assign_pos_of(changes_vox[k], 0, 3).to(fiso);
              fiso.row(3) = changes_fiso[k].cast<float>();
            }
          }
          stats.incEextTotal(dE);
          clearChanges();
        }

        void ExternalEnergyComputer::clearChanges()
        {
          changes_vox.clear();
          changes_tod.clear();
          changes_fiso.clear();
          changes_eext.clear();
          dE = 0.0;
        }

        void ExternalEnergyComputer::add(const Point_t &pos, const Point_t &dir, const double factor)
        {
          Point_t p = T.cast<float>() * pos;
          Point_t v = Point_t(Math::floor<float>(p[0]), Math::floor<float>(p[1]), Math::floor<float>(p[2]));
          Point_t w = Point_t(hanning(p[0]-v[0]), hanning(p[1]-v[1]), hanning(p[2]-v[2]));

          Math::SH::delta(d, dir, lmax);

          Eigen::Vector3i x = v.cast<int>();
          add2vox(x, factor*(1.-w[0])*(1.-w[1])*(1.-w[2]));
          x[2]++;
          add2vox(x, factor*(1.-w[0])*(1.-w[1])*w[2]);
          x[1]++;
          add2vox(x, factor*(1.-w[0])*w[1]*w[2]);
          x[2]--;
          add2vox(x, factor*(1.-w[0])*w[1]*(1.-w[2]));
          x[0]++;
          add2vox(x, factor*w[0]*w[1]*(1.-w[2]));
          x[2]++;
          add2vox(x, factor*w[0]*w[1]*w[2]);
          x[1]--;
          add2vox(x, factor*w[0]*(1.-w[1])*w[2]);
          x[2]--;
          add2vox(x, factor*w[0]*(1.-w[1])*(1.-w[2]));
        }

        void ExternalEnergyComputer::add2vox(const Eigen::Vector3i& vox, const double w)
        {
          if (w == 0.0)
            return;
          assign_pos_of(vox, 0, 3).to(tod);
          if (is_out_of_bounds(tod))
            return;
          t = w * d;
          for (int k = 0; k != changes_vox.size(); ++k) {
            if (changes_vox[k] == vox) {
              changes_tod[k] += t;
              return;
            }
          }
          changes_vox.push_back(vox);
          t += tod.row(3).cast<double>();
          changes_tod.push_back(t);
        }

        double ExternalEnergyComputer::eval()
        {
          dE = 0.0;
          double e;
          for (int k = 0; k != changes_vox.size(); ++k)
          {
            assign_pos_of(changes_vox[k], 0, 3).to(dwi, eext);
            assert(!is_out_of_bounds(dwi));
            y = dwi.row(3).cast<double>();
            t = changes_tod[k];
            e = calcEnergy();
            changes_fiso.push_back(fk.tail(nf));
            dE += e;
            dE -= eext.value();
            changes_eext.push_back(e);
          }
          return dE / stats.getText();
        }

        double ExternalEnergyComputer::calcEnergy()
        {
          y.noalias() -= K * t;
          Math::ICLS::Solver<double> nnls_solver (nnls);
          nnls_solver(fk, y);
          y.noalias() -= Ak.rightCols(nf) * fk.tail(nf);
          return y.squaredNorm() / nrows + mu * t[0];     // MSE + L1 regularizer
        }

      }
    }
  }
}

<|endoftext|>


<commit_before>// $Header$

void reve_quad_test()
{
  TRandom r(0);

  gStyle->SetPalette(1, 0);

  Reve::QuadSet* q = new Reve::QuadSet("Pepe");
  q->Reset(Reve::QuadSet::QT_AxisAligned, kFALSE, 32);
  for (Int_t i=0; i<128; ++i) {
    q->AddQuad(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10),
	       r.Uniform(-1, 1), r.Uniform(-1, 1));
    q->QuadValue(r.Uniform(0, 130));
  }
  q->RefitPlex();

  gReve->AddRenderElement(q);
  gReve->Redraw3D();
}
<commit_msg>new function<commit_after>// $Header$

Reve::QuadSet* reve_quad_test(Float_t x=0, Float_t y=0, Float_t z=0)
{
  TRandom r(0);

  gStyle->SetPalette(1, 0);

  Reve::QuadSet* q = new Reve::QuadSet("Pepe");
  q->Reset(Reve::QuadSet::QT_AxisAligned, kFALSE, 32);
  for (Int_t i=0; i<10; ++i) {
    q->AddQuad(r.Uniform(-10, 10), r.Uniform(-10, 10), r.Uniform(-10, 10),
	       r.Uniform(-1, 1), r.Uniform(-1, 1));
    q->QuadValue(r.Uniform(0, 130));
  }
  q->RefitPlex();

  Reve::ZTrans& t = q->RefHMTrans();
  t.SetPos(x, y, z);

  gReve->AddRenderElement(q);
  gReve->Redraw3D();

  return q;
}

Reve::QuadSet* reve_quad_test_circ()
{
  TRandom r(0);

  gStyle->SetPalette(1, 0);

  Reve::QuadSet* q = new Reve::QuadSet("Pepe");
  q->Reset(Reve::QuadSet::QT_AxisAligned, kFALSE, 32);

  Float_t R = 10, dW = 1, dH = .5;
  for (Int_t i=0; i<12; ++i) {
    Float_t x = R * TMath::Cos(TMath::TwoPi()*i/12);
    Float_t y = R * TMath::Sin(TMath::TwoPi()*i/12);
    q->AddQuad(x-dW, y-dH, r.Uniform(-1, 1), 2*dW, 2*dH);
    q->QuadValue(r.Uniform(0, 130));
  }
  q->RefitPlex();

  Reve::ZTrans& t = q->RefHMTrans();
  t.SetPos(0, 0, 300);

  gReve->AddRenderElement(q);
  gReve->Redraw3D();

  return q;
}
<|endoftext|>


<commit_before>/**
 * @file	main.cpp
 * @brief 	This JVMTI agent monitors applications for changes to the SecurityManager.
 *
 * The Java SecurityManager is responsible for enforcing a security policy for the thread
 * it is assigned to. The SecurityManager is stored in java.lang.System's security field.
 * This agent sets up a watch on that field and prints out the source file, function name,
 * and line number of the code that initiates any changes to it.
 */
#include <jvmti.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>
#include <boost/program_options.hpp>

void JNICALL VMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread);
bool GetOptions();
void check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str);
jvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass);
jvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID);
void JNICALL FieldModification(jvmtiEnv *jvmti_env, JNIEnv* jni_env,
                jthread thread, jmethodID method, jlocation location,
                jclass field_klass, jobject object, jfieldID field,
                char signature_type, jvalue new_value);

enum smf_mode_t {MONITOR, ENFORCE};

struct options {
  smf_mode_t mode;
};

options opt;

log4cpp::Category* logger = NULL;

JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* jvm, char* options, void* reserved) {
	jvmtiEnv* jvmti = NULL;
	jvmtiCapabilities capabilities;
	jvmtiError error;
	jvmtiEventCallbacks callbacks;

	memset(&capabilities, 0, sizeof(capabilities));
	memset(&callbacks, 0, sizeof(callbacks));

	// Start the logger
	// TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)
	log4cpp::PropertyConfigurator::configure("smf_agent/log4cpp.properties");
	logger = &log4cpp::Category::getRoot();

	if (logger == NULL) {
		printf("Failed to get logger. Terminating...");
		return -1;
	}

	// Get the options
	if (!GetOptions()) {
		return -1;
	}

	// Get JVMTI environment
	jint env_error = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_0);
	if (env_error != JNI_OK || jvmti == NULL) {
		logger->fatal("Failed to get JVMTI environment.");
		return env_error;
	}

	// Enable capability to get source code line numbers and source file
	capabilities.can_get_line_numbers = 1;
	capabilities.can_get_source_file_name = 1;

	// Enable capability to receive events for field modifications and the event itself
	capabilities.can_generate_field_modification_events = 1;

	error = jvmti->AddCapabilities(&capabilities);
	check_jvmti_error(jvmti, error, "Unable to get necessary JVMTI capabilities.");

	error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, NULL);
    check_jvmti_error(jvmti, error, "Unable to set JVMTI_EVENT_FIELD_MODIFICATION.");

	// Enable VMInit event so that we know when the JVM is initialized and we
	// can finish the rest of the setup
	error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
    check_jvmti_error(jvmti, error, "Unable to set JVMTI_EVENT_VM_INIT.");

	callbacks.VMInit = &VMInit;

	// Set a callback to receive events when the security field of System is set.
	// This will let us see when the security manager is being changed.
	callbacks.FieldModification = &FieldModification;

	error = jvmti->SetEventCallbacks(&callbacks, (jint)sizeof(callbacks));
	check_jvmti_error(jvmti, error, "Unable to register callback for field modification events.");

	return JNI_OK;
}

JNIEXPORT void JNICALL Agent_OnUnload(JavaVM* jvm)
{
	log4cpp::Category::shutdown();
}

void JNICALL VMInit(jvmtiEnv *jvmti, JNIEnv* jni_env, jthread thread) {
	jclass system_class;
	jfieldID securityID;
	jvmtiError error;

	// Get the security field of the System class (holds the SecurityManager) and
	// set a modification watch on it
	error = GetClassBySignature(jvmti, "Ljava/lang/System;", &system_class);
	check_jvmti_error(jvmti, error, "Unable to get System class.");

	error = GetFieldIDByName(jvmti, system_class, "security", &securityID);
	check_jvmti_error(jvmti, error, "Unable to get security field of the System class.");

	error = jvmti->SetFieldModificationWatch(system_class, securityID);
	check_jvmti_error(jvmti, error, "Unable to set a watch on modifications of security field of System class.");
}

/**
 * @brief	reads the smf properties file and populates the global opt struct with the correct values
 *
 * @retval	true if all of the options in the properties are valid, false and a fatal log message otherwise
 */
bool GetOptions() {
	// TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)
	std::string mode;

	std::ifstream settings_file("smf_agent/smf.properties");
	boost::program_options::options_description desc("Options");
	desc.add_options()
		("mode", boost::program_options::value<std::string>(&mode), "mode");
	boost::program_options::variables_map vm = boost::program_options::variables_map();

	boost::program_options::store(boost::program_options::parse_config_file(settings_file , desc), vm);
	boost::program_options::notify(vm);
	settings_file.close();

	if (strcasecmp(mode.c_str(), "MONITOR") == 0) {
		opt.mode = MONITOR;
	} else if (strcasecmp(mode.c_str(), "ENFORCE") == 0) {
		opt.mode = ENFORCE;
	} else {
		logger->fatal("Option value unknown: %s. Terminating...");
		return false;
	}

	return true;
}

void log_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)
{
    char* errnum_str = NULL;

    jvmti->GetErrorName(errnum, &errnum_str);

    logger->error("JVMTI: %d(%s): %s\n", errnum, errnum_str == NULL ? "Unknown" : errnum_str,
		str == NULL ? "" : str);

	jvmti->Deallocate((unsigned char*)errnum_str);
}

void check_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)
{
    if (errnum != JVMTI_ERROR_NONE)
        log_jvmti_error(jvmti, errnum, str);
}

/**
 * @brief	looks up and returns the reference for a class based on a user specified Java type signature
 *
 * @param	[in] the JVMTI environment used to access the JVMTI API
 * @param	[in] the Java type signature for the class we'd like to retrieve a reference to
 * @param	[out] a pointer that will be set to reference the class whose signature was specified
 *
 * @retval	a JVMTI error code if one is returned by any of the JVMTI API calls
 */
jvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass) {
	jint class_count = 0;
	jclass* classes = NULL;
	jvmtiError error;

	error = jvmti->GetLoadedClasses(&class_count, &classes);
	if (error != JVMTI_ERROR_NONE)
		return error;

	for (int i = 0; i < class_count; i++) {
		char* class_signature = NULL;

		error = jvmti->GetClassSignature(classes[i], &class_signature, NULL);
		if (error != JVMTI_ERROR_NONE)
			return error;

		if (strcmp(class_signature, signature) == 0) {
			*klass = classes[i];
			break;
		}

		jvmti->Deallocate((unsigned char*)class_signature);
	}

	jvmti->Deallocate((unsigned char*)classes);

	return JVMTI_ERROR_NONE;
}

/**
 * @brief	looks up and returns the ID for a field in a class based on a user specified field name and class
 *
 * @param	[in] the JVMTI environment used to access the JVMTI API
 * @param	[in] the Java class we want to retrieve a field ID from
 * @param	[in] the name of the field whose ID we want to retrieve
 * @param	[out] a pointer to a jfieldID that will be set to the named field's ID
 *
 * @retval	a JVMTI error code if one is returned by any of the JVMTI API calls
 */
jvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID) {
	jint field_count = 0;
	jfieldID* fields = NULL;
	jvmtiError error;

	error = jvmti->GetClassFields(klass, &field_count, &fields);
	if (error != JVMTI_ERROR_NONE)
		return error;

	for (int i = 0; i < field_count; i++) {
		char* field_name = NULL;

		error = jvmti->GetFieldName(klass, fields[i], &field_name, NULL, NULL);
		if (error != JVMTI_ERROR_NONE)
			return error;

		if (strcmp(field_name, name) == 0) {
			*fieldID = fields[i];
			break;
		}

		jvmti->Deallocate((unsigned char*)field_name);
	}

	jvmti->Deallocate((unsigned char*)fields);

	return JVMTI_ERROR_NONE;
}

void JNICALL FieldModification(jvmtiEnv* jvmti, JNIEnv* jni_env,
                jthread thread, jmethodID method, jlocation location,
                jclass field_klass, jobject object, jfieldID field,
                char signature_type, jvalue new_value) {

	jvmtiError error;
	jvmtiFrameInfo caller_frame;
	jint frame_count = 0;
	jint line_count = 0;
	jvmtiLineNumberEntry* line_table = NULL;
	jint line_number = 0;
	char* method_name = NULL;
	jclass caller_class = NULL;
	char* source_file_name = NULL;
	JavaVM* jvm;

	// Get caller (we have to do this because we are in setSecurityManager when
	// this method is called);
	error = jvmti->GetStackTrace(thread, 2, 1, &caller_frame, &frame_count);
	check_jvmti_error(jvmti, error, "Unable to get stack frame.");

	// Get caller's line number
	error = jvmti->GetLineNumberTable(caller_frame.method, &line_count, &line_table);
	check_jvmti_error(jvmti, error, "Unable to get line number for SecurityManager change.");

	for (int i = 0; i < line_count; i++) {
		if (line_table[i].start_location > caller_frame.location)
			break;

		line_number = line_table[i].line_number;
	}

	// Get caller's method name
	error = jvmti->GetMethodName(caller_frame.method, &method_name, NULL, NULL);
	check_jvmti_error(jvmti, error, "Unable to method name.");

	// Get the caller's class and source file name
	error = jvmti->GetMethodDeclaringClass(caller_frame.method, &caller_class);
	check_jvmti_error(jvmti, error, "Unable to get caller class.");

	error = jvmti->GetSourceFileName(caller_class, &source_file_name);

	// If new_value is full a null SecurityManager raise a red flag
	if ((long)new_value.j == 0) {
		if (opt.mode == MONITOR) {
			logger->warn("The SecurityManager is being disabled!!!\n");
		} else if (opt.mode == ENFORCE) {
			logger->fatal("The SecurityManager is being disabled. Terminating the running application...");
			jni_env->GetJavaVM(&jvm);
			// TODO: Why is this core dumping? Is there a better way? Does it work on Windows?
			jvm->DestroyJavaVM();
		}
	} else {
		//jclass new_manager = jni_env->GetObjectClass(new_value.l);
		// TODO: This is where we may do something with the new manager in the plugin
	}

	logger->warn("SecurityManager Changed:\n%s, %s, %d\n\n", source_file_name, method_name, line_number);

	jvmti->Deallocate((unsigned char*)line_table);
	jvmti->Deallocate((unsigned char*)method_name);
	jvmti->Deallocate((unsigned char*)source_file_name);
}
<commit_msg>Added macro to redefine strcasecmp to stricmp on Windows.<commit_after>/**
 * @file	main.cpp
 * @brief 	This JVMTI agent monitors applications for changes to the SecurityManager.
 *
 * The Java SecurityManager is responsible for enforcing a security policy for the thread
 * it is assigned to. The SecurityManager is stored in java.lang.System's security field.
 * This agent sets up a watch on that field and prints out the source file, function name,
 * and line number of the code that initiates any changes to it.
 */
#include <jvmti.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>
#include <boost/program_options.hpp>

#if defined(_WIN32) || defined(_WIN64)
  #define strcasecmp _stricmp
#endif

void JNICALL VMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread);
bool GetOptions();
void check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str);
jvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass);
jvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID);
void JNICALL FieldModification(jvmtiEnv *jvmti_env, JNIEnv* jni_env,
                jthread thread, jmethodID method, jlocation location,
                jclass field_klass, jobject object, jfieldID field,
                char signature_type, jvalue new_value);

enum smf_mode_t {MONITOR, ENFORCE};

struct options {
  smf_mode_t mode;
};

options opt;

log4cpp::Category* logger = NULL;

JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* jvm, char* options, void* reserved) {
	jvmtiEnv* jvmti = NULL;
	jvmtiCapabilities capabilities;
	jvmtiError error;
	jvmtiEventCallbacks callbacks;

	memset(&capabilities, 0, sizeof(capabilities));
	memset(&callbacks, 0, sizeof(callbacks));

	// Start the logger
	// TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)
	log4cpp::PropertyConfigurator::configure("smf_agent/log4cpp.properties");
	logger = &log4cpp::Category::getRoot();

	if (logger == NULL) {
		printf("Failed to get logger. Terminating...");
		return -1;
	}

	// Get the options
	if (!GetOptions()) {
		return -1;
	}

	// Get JVMTI environment
	jint env_error = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_0);
	if (env_error != JNI_OK || jvmti == NULL) {
		logger->fatal("Failed to get JVMTI environment.");
		return env_error;
	}

	// Enable capability to get source code line numbers and source file
	capabilities.can_get_line_numbers = 1;
	capabilities.can_get_source_file_name = 1;

	// Enable capability to receive events for field modifications and the event itself
	capabilities.can_generate_field_modification_events = 1;

	error = jvmti->AddCapabilities(&capabilities);
	check_jvmti_error(jvmti, error, "Unable to get necessary JVMTI capabilities.");

	error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, NULL);
    check_jvmti_error(jvmti, error, "Unable to set JVMTI_EVENT_FIELD_MODIFICATION.");

	// Enable VMInit event so that we know when the JVM is initialized and we
	// can finish the rest of the setup
	error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
    check_jvmti_error(jvmti, error, "Unable to set JVMTI_EVENT_VM_INIT.");

	callbacks.VMInit = &VMInit;

	// Set a callback to receive events when the security field of System is set.
	// This will let us see when the security manager is being changed.
	callbacks.FieldModification = &FieldModification;

	error = jvmti->SetEventCallbacks(&callbacks, (jint)sizeof(callbacks));
	check_jvmti_error(jvmti, error, "Unable to register callback for field modification events.");

	return JNI_OK;
}

JNIEXPORT void JNICALL Agent_OnUnload(JavaVM* jvm)
{
	log4cpp::Category::shutdown();
}

void JNICALL VMInit(jvmtiEnv *jvmti, JNIEnv* jni_env, jthread thread) {
	jclass system_class;
	jfieldID securityID;
	jvmtiError error;

	// Get the security field of the System class (holds the SecurityManager) and
	// set a modification watch on it
	error = GetClassBySignature(jvmti, "Ljava/lang/System;", &system_class);
	check_jvmti_error(jvmti, error, "Unable to get System class.");

	error = GetFieldIDByName(jvmti, system_class, "security", &securityID);
	check_jvmti_error(jvmti, error, "Unable to get security field of the System class.");

	error = jvmti->SetFieldModificationWatch(system_class, securityID);
	check_jvmti_error(jvmti, error, "Unable to set a watch on modifications of security field of System class.");
}

/**
 * @brief	reads the smf properties file and populates the global opt struct with the correct values
 *
 * @retval	true if all of the options in the properties are valid, false and a fatal log message otherwise
 */
bool GetOptions() {
	// TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)
	std::string mode;

	std::ifstream settings_file("smf_agent/smf.properties");
	boost::program_options::options_description desc("Options");
	desc.add_options()
		("mode", boost::program_options::value<std::string>(&mode), "mode");
	boost::program_options::variables_map vm = boost::program_options::variables_map();

	boost::program_options::store(boost::program_options::parse_config_file(settings_file , desc), vm);
	boost::program_options::notify(vm);
	settings_file.close();

	if (strcasecmp(mode.c_str(), "MONITOR") == 0) {
		opt.mode = MONITOR;
	} else if (strcasecmp(mode.c_str(), "ENFORCE") == 0) {
		opt.mode = ENFORCE;
	} else {
		logger->fatal("Option value unknown: %s. Terminating...");
		return false;
	}

	return true;
}

void log_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)
{
    char* errnum_str = NULL;

    jvmti->GetErrorName(errnum, &errnum_str);

    logger->error("JVMTI: %d(%s): %s\n", errnum, errnum_str == NULL ? "Unknown" : errnum_str,
		str == NULL ? "" : str);

	jvmti->Deallocate((unsigned char*)errnum_str);
}

void check_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)
{
    if (errnum != JVMTI_ERROR_NONE)
        log_jvmti_error(jvmti, errnum, str);
}

/**
 * @brief	looks up and returns the reference for a class based on a user specified Java type signature
 *
 * @param	[in] the JVMTI environment used to access the JVMTI API
 * @param	[in] the Java type signature for the class we'd like to retrieve a reference to
 * @param	[out] a pointer that will be set to reference the class whose signature was specified
 *
 * @retval	a JVMTI error code if one is returned by any of the JVMTI API calls
 */
jvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass) {
	jint class_count = 0;
	jclass* classes = NULL;
	jvmtiError error;

	error = jvmti->GetLoadedClasses(&class_count, &classes);
	if (error != JVMTI_ERROR_NONE)
		return error;

	for (int i = 0; i < class_count; i++) {
		char* class_signature = NULL;

		error = jvmti->GetClassSignature(classes[i], &class_signature, NULL);
		if (error != JVMTI_ERROR_NONE)
			return error;

		if (strcmp(class_signature, signature) == 0) {
			*klass = classes[i];
			break;
		}

		jvmti->Deallocate((unsigned char*)class_signature);
	}

	jvmti->Deallocate((unsigned char*)classes);

	return JVMTI_ERROR_NONE;
}

/**
 * @brief	looks up and returns the ID for a field in a class based on a user specified field name and class
 *
 * @param	[in] the JVMTI environment used to access the JVMTI API
 * @param	[in] the Java class we want to retrieve a field ID from
 * @param	[in] the name of the field whose ID we want to retrieve
 * @param	[out] a pointer to a jfieldID that will be set to the named field's ID
 *
 * @retval	a JVMTI error code if one is returned by any of the JVMTI API calls
 */
jvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID) {
	jint field_count = 0;
	jfieldID* fields = NULL;
	jvmtiError error;

	error = jvmti->GetClassFields(klass, &field_count, &fields);
	if (error != JVMTI_ERROR_NONE)
		return error;

	for (int i = 0; i < field_count; i++) {
		char* field_name = NULL;

		error = jvmti->GetFieldName(klass, fields[i], &field_name, NULL, NULL);
		if (error != JVMTI_ERROR_NONE)
			return error;

		if (strcmp(field_name, name) == 0) {
			*fieldID = fields[i];
			break;
		}

		jvmti->Deallocate((unsigned char*)field_name);
	}

	jvmti->Deallocate((unsigned char*)fields);

	return JVMTI_ERROR_NONE;
}

void JNICALL FieldModification(jvmtiEnv* jvmti, JNIEnv* jni_env,
                jthread thread, jmethodID method, jlocation location,
                jclass field_klass, jobject object, jfieldID field,
                char signature_type, jvalue new_value) {

	jvmtiError error;
	jvmtiFrameInfo caller_frame;
	jint frame_count = 0;
	jint line_count = 0;
	jvmtiLineNumberEntry* line_table = NULL;
	jint line_number = 0;
	char* method_name = NULL;
	jclass caller_class = NULL;
	char* source_file_name = NULL;
	JavaVM* jvm;

	// Get caller (we have to do this because we are in setSecurityManager when
	// this method is called);
	error = jvmti->GetStackTrace(thread, 2, 1, &caller_frame, &frame_count);
	check_jvmti_error(jvmti, error, "Unable to get stack frame.");

	// Get caller's line number
	error = jvmti->GetLineNumberTable(caller_frame.method, &line_count, &line_table);
	check_jvmti_error(jvmti, error, "Unable to get line number for SecurityManager change.");

	for (int i = 0; i < line_count; i++) {
		if (line_table[i].start_location > caller_frame.location)
			break;

		line_number = line_table[i].line_number;
	}

	// Get caller's method name
	error = jvmti->GetMethodName(caller_frame.method, &method_name, NULL, NULL);
	check_jvmti_error(jvmti, error, "Unable to method name.");

	// Get the caller's class and source file name
	error = jvmti->GetMethodDeclaringClass(caller_frame.method, &caller_class);
	check_jvmti_error(jvmti, error, "Unable to get caller class.");

	error = jvmti->GetSourceFileName(caller_class, &source_file_name);

	// If new_value is full a null SecurityManager raise a red flag
	if ((long)new_value.j == 0) {
		if (opt.mode == MONITOR) {
			logger->warn("The SecurityManager is being disabled!!!\n");
		} else if (opt.mode == ENFORCE) {
			logger->fatal("The SecurityManager is being disabled. Terminating the running application...");
			jni_env->GetJavaVM(&jvm);
			// TODO: Why is this core dumping? Is there a better way? Does it work on Windows?
			jvm->DestroyJavaVM();
		}
	} else {
		//jclass new_manager = jni_env->GetObjectClass(new_value.l);
		// TODO: This is where we may do something with the new manager in the plugin
	}

	logger->warn("SecurityManager Changed:\n%s, %s, %d\n\n", source_file_name, method_name, line_number);

	jvmti->Deallocate((unsigned char*)line_table);
	jvmti->Deallocate((unsigned char*)method_name);
	jvmti->Deallocate((unsigned char*)source_file_name);
}
<|endoftext|>


<commit_before>//===-- RegisterContextLinux_x86_64.cpp ------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//

#include <vector>
#include "RegisterContextPOSIX_x86.h"
#include "RegisterContextLinux_i386.h"
#include "RegisterContextLinux_x86_64.h"

using namespace lldb_private;
using namespace lldb;

typedef struct _GPR
{
    uint64_t r15;
    uint64_t r14;
    uint64_t r13;
    uint64_t r12;
    uint64_t rbp;
    uint64_t rbx;
    uint64_t r11;
    uint64_t r10;
    uint64_t r9;
    uint64_t r8;
    uint64_t rax;
    uint64_t rcx;
    uint64_t rdx;
    uint64_t rsi;
    uint64_t rdi;
    uint64_t orig_ax;
    uint64_t rip;
    uint64_t cs;
    uint64_t rflags;
    uint64_t rsp;
    uint64_t ss;
    uint64_t fs_base;
    uint64_t gs_base;
    uint64_t ds;
    uint64_t es;
    uint64_t fs;
    uint64_t gs;
} GPR;

struct UserArea
{
    GPR      gpr;           // General purpose registers.
    int32_t  fpvalid;       // True if FPU is being used.
    int32_t  pad0;
    FXSAVE   i387;          // General purpose floating point registers (see FPR for extended register sets).
    uint64_t tsize;         // Text segment size.
    uint64_t dsize;         // Data segment size.
    uint64_t ssize;         // Stack segment size.
    uint64_t start_code;    // VM address of text.
    uint64_t start_stack;   // VM address of stack bottom (top in rsp).
    int64_t  signal;        // Signal causing core dump.
    int32_t  reserved;      // Unused.
    int32_t  pad1;
    uint64_t ar0;           // Location of GPR's.
    FXSAVE*  fpstate;       // Location of FPR's.
    uint64_t magic;         // Identifier for core dumps.
    char     u_comm[32];    // Command causing core dump.
    uint64_t u_debugreg[8]; // Debug registers (DR0 - DR7).
    uint64_t error_code;    // CPU error code.
    uint64_t fault_address; // Control register CR3.
};

#define DR_SIZE sizeof(((UserArea*)NULL)->u_debugreg[0])
#define DR_OFFSET(reg_index) \
    (LLVM_EXTENSION offsetof(UserArea, u_debugreg[reg_index]))

//---------------------------------------------------------------------------
// Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 structure.
//---------------------------------------------------------------------------
#define DECLARE_REGISTER_INFOS_X86_64_STRUCT
#include "RegisterInfos_x86_64.h"
#undef DECLARE_REGISTER_INFOS_X86_64_STRUCT

static std::vector<lldb_private::RegisterInfo>&
GetPrivateRegisterInfoVector ()
{
    static std::vector<lldb_private::RegisterInfo> g_register_infos;
    return g_register_infos;
}

static const RegisterInfo *
GetRegisterInfo_i386(const lldb_private::ArchSpec &arch)
{
    static std::vector<lldb_private::RegisterInfo> g_register_infos (GetPrivateRegisterInfoVector ());

    // Allocate RegisterInfo only once
    if (g_register_infos.empty())
    {
        // Copy the register information from base class
        std::unique_ptr<RegisterContextLinux_i386> reg_interface(new RegisterContextLinux_i386 (arch));
        const RegisterInfo *base_info = reg_interface->GetRegisterInfo();
        g_register_infos.insert(g_register_infos.end(), &base_info[0], &base_info[k_num_registers_i386]);

        //---------------------------------------------------------------------------
        // Include RegisterInfos_x86_64 to update the g_register_infos structure
        //  with x86_64 offsets.
        //---------------------------------------------------------------------------
        #define UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS
        #include "RegisterInfos_x86_64.h"
        #undef UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS
    }

    return &g_register_infos[0];
}

static const RegisterInfo *
GetRegisterInfoPtr (const ArchSpec &target_arch)
{
    switch (target_arch.GetMachine())
    {
        case llvm::Triple::x86:
            return GetRegisterInfo_i386 (target_arch);
        case llvm::Triple::x86_64:
            return g_register_infos_x86_64;
        default:
            assert(false && "Unhandled target architecture.");
            return nullptr;
    }
}

static uint32_t
GetRegisterInfoCount (const ArchSpec &target_arch)
{
    switch (target_arch.GetMachine())
    {
        case llvm::Triple::x86:
            {
                assert (!GetPrivateRegisterInfoVector ().empty () && "i386 register info not yet filled.");
                return static_cast<uint32_t> (GetPrivateRegisterInfoVector ().size ());
            }
        case llvm::Triple::x86_64:
            return static_cast<uint32_t> (sizeof (g_register_infos_x86_64) / sizeof (g_register_infos_x86_64 [0]));
        default:
            assert(false && "Unhandled target architecture.");
            return 0;
    }
}

RegisterContextLinux_x86_64::RegisterContextLinux_x86_64(const ArchSpec &target_arch) :
    lldb_private::RegisterInfoInterface(target_arch),
    m_register_info_p (GetRegisterInfoPtr (target_arch)),
    m_register_info_count (GetRegisterInfoCount (target_arch))
{
}

size_t
RegisterContextLinux_x86_64::GetGPRSize() const
{
    return sizeof(GPR);
}

const RegisterInfo *
RegisterContextLinux_x86_64::GetRegisterInfo() const
{
    return m_register_info_p;
}

uint32_t
RegisterContextLinux_x86_64::GetRegisterCount () const
{
    return m_register_info_count;
}
<commit_msg>Fix incorrect Linux i386 register info initialization on x86_64.<commit_after>//===-- RegisterContextLinux_x86_64.cpp ------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//

#include <vector>
#include "RegisterContextPOSIX_x86.h"
#include "RegisterContextLinux_i386.h"
#include "RegisterContextLinux_x86_64.h"

using namespace lldb_private;
using namespace lldb;

typedef struct _GPR
{
    uint64_t r15;
    uint64_t r14;
    uint64_t r13;
    uint64_t r12;
    uint64_t rbp;
    uint64_t rbx;
    uint64_t r11;
    uint64_t r10;
    uint64_t r9;
    uint64_t r8;
    uint64_t rax;
    uint64_t rcx;
    uint64_t rdx;
    uint64_t rsi;
    uint64_t rdi;
    uint64_t orig_ax;
    uint64_t rip;
    uint64_t cs;
    uint64_t rflags;
    uint64_t rsp;
    uint64_t ss;
    uint64_t fs_base;
    uint64_t gs_base;
    uint64_t ds;
    uint64_t es;
    uint64_t fs;
    uint64_t gs;
} GPR;

struct UserArea
{
    GPR      gpr;           // General purpose registers.
    int32_t  fpvalid;       // True if FPU is being used.
    int32_t  pad0;
    FXSAVE   i387;          // General purpose floating point registers (see FPR for extended register sets).
    uint64_t tsize;         // Text segment size.
    uint64_t dsize;         // Data segment size.
    uint64_t ssize;         // Stack segment size.
    uint64_t start_code;    // VM address of text.
    uint64_t start_stack;   // VM address of stack bottom (top in rsp).
    int64_t  signal;        // Signal causing core dump.
    int32_t  reserved;      // Unused.
    int32_t  pad1;
    uint64_t ar0;           // Location of GPR's.
    FXSAVE*  fpstate;       // Location of FPR's.
    uint64_t magic;         // Identifier for core dumps.
    char     u_comm[32];    // Command causing core dump.
    uint64_t u_debugreg[8]; // Debug registers (DR0 - DR7).
    uint64_t error_code;    // CPU error code.
    uint64_t fault_address; // Control register CR3.
};

#define DR_SIZE sizeof(((UserArea*)NULL)->u_debugreg[0])
#define DR_OFFSET(reg_index) \
    (LLVM_EXTENSION offsetof(UserArea, u_debugreg[reg_index]))

//---------------------------------------------------------------------------
// Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 structure.
//---------------------------------------------------------------------------
#define DECLARE_REGISTER_INFOS_X86_64_STRUCT
#include "RegisterInfos_x86_64.h"
#undef DECLARE_REGISTER_INFOS_X86_64_STRUCT

static std::vector<lldb_private::RegisterInfo>&
GetPrivateRegisterInfoVector ()
{
    static std::vector<lldb_private::RegisterInfo> g_register_infos;
    return g_register_infos;
}

static const RegisterInfo *
GetRegisterInfo_i386(const lldb_private::ArchSpec &arch)
{
    std::vector<lldb_private::RegisterInfo> &g_register_infos = GetPrivateRegisterInfoVector ();

    // Allocate RegisterInfo only once
    if (g_register_infos.empty())
    {
        // Copy the register information from base class
        std::unique_ptr<RegisterContextLinux_i386> reg_interface(new RegisterContextLinux_i386 (arch));
        const RegisterInfo *base_info = reg_interface->GetRegisterInfo();
        g_register_infos.insert(g_register_infos.end(), &base_info[0], &base_info[k_num_registers_i386]);

        //---------------------------------------------------------------------------
        // Include RegisterInfos_x86_64 to update the g_register_infos structure
        //  with x86_64 offsets.
        //---------------------------------------------------------------------------
        #define UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS
        #include "RegisterInfos_x86_64.h"
        #undef UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS
    }

    return &g_register_infos[0];
}

static const RegisterInfo *
GetRegisterInfoPtr (const ArchSpec &target_arch)
{
    switch (target_arch.GetMachine())
    {
        case llvm::Triple::x86:
            return GetRegisterInfo_i386 (target_arch);
        case llvm::Triple::x86_64:
            return g_register_infos_x86_64;
        default:
            assert(false && "Unhandled target architecture.");
            return nullptr;
    }
}

static uint32_t
GetRegisterInfoCount (const ArchSpec &target_arch)
{
    switch (target_arch.GetMachine())
    {
        case llvm::Triple::x86:
            {
                assert (!GetPrivateRegisterInfoVector ().empty () && "i386 register info not yet filled.");
                return static_cast<uint32_t> (GetPrivateRegisterInfoVector ().size ());
            }
        case llvm::Triple::x86_64:
            return static_cast<uint32_t> (sizeof (g_register_infos_x86_64) / sizeof (g_register_infos_x86_64 [0]));
        default:
            assert(false && "Unhandled target architecture.");
            return 0;
    }
}

RegisterContextLinux_x86_64::RegisterContextLinux_x86_64(const ArchSpec &target_arch) :
    lldb_private::RegisterInfoInterface(target_arch),
    m_register_info_p (GetRegisterInfoPtr (target_arch)),
    m_register_info_count (GetRegisterInfoCount (target_arch))
{
}

size_t
RegisterContextLinux_x86_64::GetGPRSize() const
{
    return sizeof(GPR);
}

const RegisterInfo *
RegisterContextLinux_x86_64::GetRegisterInfo() const
{
    return m_register_info_p;
}

uint32_t
RegisterContextLinux_x86_64::GetRegisterCount () const
{
    return m_register_info_count;
}
<|endoftext|>


<commit_before><commit_msg>Document bug number for flakyness report.<commit_after><|endoftext|>


<commit_before><commit_msg>AbstractAccountParametersWidget: Reset parameters with disabled widgets to their default values when submitting changes<commit_after><|endoftext|>


<commit_before><commit_msg>Generated from n10_e9024_tp023_spider_u223_01<commit_after><|endoftext|>


<commit_before><commit_msg>Add memdiags implementation for superfast operations<commit_after><|endoftext|>


<commit_before><commit_msg>Fix path validation<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <Windows.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
/*
mineBot.cpp
T.Lloyd

An attempt at an openCV minesweeper bot...

*/
using namespace cv;
using namespace std;

#define until for
#define endOfTime (;;)

BOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){
	HDC mineHDC, mineCompat;
	HBITMAP mineBit;
	BITMAP b;
	BITMAPINFOHEADER mineH;
	if (mineHandle == NULL){
		cout << "Game Not Found\n";
		return FALSE;
	}
	mineHDC = GetDC(mineHandle);
	mineCompat = CreateCompatibleDC(mineHDC);
	if (!mineCompat){
		cout << "Error creating compatible DC\n";
		return FALSE;
	}
	//SetStretchBltMode(mineCompat, HALFTONE);
	SetStretchBltMode(mineCompat, HALFTONE);

	mineBit = CreateCompatibleBitmap(mineHDC, width, height);
	if (mineBit == NULL){
		cout << "Bitmap Creation Failed!\n";
		return FALSE;
	}
	mineH.biSize = sizeof(BITMAPINFOHEADER);
	mineH.biPlanes = 1;
	mineH.biWidth = width;
	mineH.biHeight = -height;
	mineH.biBitCount = 32;
	mineH.biCompression = BI_RGB;

	SelectObject(mineCompat, mineBit);
	if (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){
		cout << "Error Stretch BLT\n";
		return FALSE;
	}

	//BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY);
	//GetObject(mineBit, sizeof(BITMAP), &b);
	//GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);
	GetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);

	DeleteObject(mineBit);
	DeleteDC(mineCompat);
	ReleaseDC(mineHandle, mineHDC);

	return TRUE;
}

BOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){
	//Frame,Template,Result,Number of squares
	Mat greysrc = f.clone();
	Mat greyTemp = t.clone();
	cvtColor(f, greysrc, COLOR_BGR2GRAY);
	cvtColor(t, greyTemp, COLOR_BGR2GRAY);

	matchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED);
	normalize(r, r, 0, 1, NORM_MINMAX, -1, Mat());

	double minVal;
	double maxVal;
	Point minLoc;
	Point maxLoc;
	Point matchLoc;
	Point prevMatchLoc;
	squares.clear();
	bool edge = FALSE;
	int dup = 0; //count duplicates
	for (int i = 0, j = 0; i < 81; i++){
		//minesweeper has gradient so only detects two of the squares.
		minMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
		//if (maxVal > 0.87){
		if ((maxVal > threshold)){
			matchLoc = maxLoc;
			for (int k = 0; k < squares.size(); k++){
				if (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){
					//cout << "!";
					dup++;
				}
			}
			if (matchLoc.x > 30){
				edge = TRUE;
			}
			else{
				edge = FALSE;
			}
				//cout << "Duplicates=" << dup << "\n";
				//dup = 0;
				if ((dup == 0)&&(edge==TRUE)){
					squares.push_back(matchLoc);
					rectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0);
					rectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0);
				}
			//}
			//}
		}
	}
	greysrc.release();
	greyTemp.release();
	//cout << "Vector Size=" << squares.size() << "\n";
	return TRUE;
}
int main(void){
	std::cout << "mineBot\nT.Lloyd\n";
	Mat frame;
	HWND mineHandle = FindWindow(NULL,L"Minesweeper");
	if (mineHandle == NULL){
		cout << "Game Not Found\n";
		return -1;
	}
	else{
		cout << "Game Successfully Found!\n";
	}
	namedWindow("Win", 1);
	RECT winSize;

	int height, width;
	int unpressed = 0;
	GetClientRect(mineHandle, &winSize);
	height = winSize.bottom;
	width = winSize.right;

	frame.create(height, width, CV_8UC4);
	Point pt;
	pt.x = 0;
	pt.y = 0;

	Mat temp = imread("Images//square2.jpg", CV_LOAD_IMAGE_COLOR);
	Mat oneTemp = imread("Images//one3.jpg", CV_LOAD_IMAGE_COLOR);
	Mat twoTemp = imread("Images//two.jpg", CV_LOAD_IMAGE_COLOR);
	Mat threeTemp = imread("Images//three.jpg", CV_LOAD_IMAGE_COLOR);
	Mat fourTemp = imread("Images//four.jpg", CV_LOAD_IMAGE_COLOR);
	//cvtColor(temp, temp, CV_8UC4,0);
	//Mat result;
	//Mat oneResult;
	captureFrame(frame, mineHandle, height, width);
	//imwrite("Images//Master.jpg", frame);
	//result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);
	char grid[9][9] = {0};
	vector <vector<Point>> gridPoints;
	vector<Point> unsquare;
	vector<Point> oneSquares;
	vector<Point> twoSquares;
	vector<Point> threeSquares;
	vector<Point> fourSquares;
	Mat unPressedMat;
	Mat oneMat;
	Mat twoMat;
	Mat threeMat;
	Mat fourMat;
	until endOfTime{
		if (captureFrame(frame, mineHandle,height,width)==TRUE){
			if (!frame.empty()){
				//matchTemplate(frame, temp, result, TM_CCOEFF_NORMED);
				Mat result;
				result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);
				//unPressedMat = frame.clone();
				countSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255));
				cout << "Unpressed Squares: " << unsquare.size() << "\n";
				result.release();
				if (unsquare.size() != 81){
					Mat oneResult;
					oneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0));
					cout << "One Squares: " << oneSquares.size() << "\n";
					oneResult.release();

					Mat twoResult;
					twoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 0, 0));
					cout << "Two Squares: " << twoSquares.size() << "\n";
					twoResult.release();

					Mat threeResult;
					threeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 0));
					cout << "Three Squares: " << threeSquares.size() << "\n";
					threeResult.release();

					Mat fourResult;
					fourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0));
					cout << "Four Squares: " << fourSquares.size() << "\n";
					fourResult.release();
				}
				imshow("Win", frame);
				//imshow("One", oneMat);
				Sleep(2000);
			}
		}
		if (waitKey(30) >= 0) break;
	}
	return 0;
}<commit_msg>Added grid sorting algorithm for arranging the grid points in order<commit_after>#include <iostream>
#include <Windows.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <algorithm>
/*
mineBot.cpp
T.Lloyd

An attempt at an openCV minesweeper bot...

*/
using namespace cv;
using namespace std;

#define until for
#define endOfTime (;;)

BOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){
	HDC mineHDC, mineCompat;
	HBITMAP mineBit;
	BITMAP b;
	BITMAPINFOHEADER mineH;
	if (mineHandle == NULL){
		cout << "Game Not Found\n";
		return FALSE;
	}
	mineHDC = GetDC(mineHandle);
	mineCompat = CreateCompatibleDC(mineHDC);
	if (!mineCompat){
		cout << "Error creating compatible DC\n";
		return FALSE;
	}
	//SetStretchBltMode(mineCompat, HALFTONE);
	SetStretchBltMode(mineCompat, HALFTONE);

	mineBit = CreateCompatibleBitmap(mineHDC, width, height);
	if (mineBit == NULL){
		cout << "Bitmap Creation Failed!\n";
		return FALSE;
	}
	mineH.biSize = sizeof(BITMAPINFOHEADER);
	mineH.biPlanes = 1;
	mineH.biWidth = width;
	mineH.biHeight = -height;
	mineH.biBitCount = 32;
	mineH.biCompression = BI_RGB;

	SelectObject(mineCompat, mineBit);
	if (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){
		cout << "Error Stretch BLT\n";
		return FALSE;
	}

	//BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY);
	//GetObject(mineBit, sizeof(BITMAP), &b);
	//GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);
	GetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);

	DeleteObject(mineBit);
	DeleteDC(mineCompat);
	ReleaseDC(mineHandle, mineHDC);

	return TRUE;
}

BOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){
	//Frame,Template,Result,Number of squares
	Mat greysrc = f.clone();
	Mat greyTemp = t.clone();
	cvtColor(f, greysrc, COLOR_BGR2GRAY);
	cvtColor(t, greyTemp, COLOR_BGR2GRAY);

	matchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED);
	normalize(r, r, 0, 1, NORM_MINMAX, -1, Mat());

	double minVal;
	double maxVal;
	Point minLoc;
	Point maxLoc;
	Point matchLoc;
	Point prevMatchLoc;
	squares.clear();
	bool edge = FALSE;
	int dup = 0; //count duplicates
	for (int i = 0, j = 0; i < 81; i++){
		//minesweeper has gradient so only detects two of the squares.
		minMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
		//if (maxVal > 0.87){
		if ((maxVal > threshold)){
			matchLoc = maxLoc;
			for (int k = 0; k < squares.size(); k++){
				if (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){
					//cout << "!";
					dup++;
				}
			}
			if (matchLoc.x > 30){
				edge = TRUE;
			}
			else{
				edge = FALSE;
			}
				//cout << "Duplicates=" << dup << "\n";
				//dup = 0;
				if ((dup == 0)&&(edge==TRUE)){
					squares.push_back(matchLoc);
					rectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0);
					rectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0);
				}
			//}
			//}
		}
	}
	greysrc.release();
	greyTemp.release();
	//cout << "Vector Size=" << squares.size() << "\n";
	return TRUE;
}

void printSquares(vector<Point> &p){
	for (int k = 0; k < p.size(); k++){
		cout << "(" << p[k].x << "," << p[k].y << ")\n";
	}
}

bool sortX(Point p1, Point p2){return (p1.x < p2.x);}
bool sortY(Point p1, Point p2){ return (p1.y < p2.y); }

int main(void){
	std::cout << "mineBot\nT.Lloyd\n";
	Mat frame;
	HWND mineHandle = FindWindow(NULL,L"Minesweeper");
	if (mineHandle == NULL){
		cout << "Game Not Found\n";
		return -1;
	}
	else{
		cout << "Game Successfully Found!\n";
	}
	namedWindow("Win", 1);
	RECT winSize;

	int height, width;
	int unpressed = 0;
	GetClientRect(mineHandle, &winSize);
	height = winSize.bottom;
	width = winSize.right;

	frame.create(height, width, CV_8UC4);
	Point pt;
	pt.x = 0;
	pt.y = 0;

	Mat temp = imread("Images//square2.jpg", CV_LOAD_IMAGE_COLOR);
	Mat oneTemp = imread("Images//one3.jpg", CV_LOAD_IMAGE_COLOR);
	Mat twoTemp = imread("Images//two.jpg", CV_LOAD_IMAGE_COLOR);
	Mat threeTemp = imread("Images//three.jpg", CV_LOAD_IMAGE_COLOR);
	Mat fourTemp = imread("Images//four.jpg", CV_LOAD_IMAGE_COLOR);
	//cvtColor(temp, temp, CV_8UC4,0);
	//Mat result;
	//Mat oneResult;

	//----------------------------------------------------------------------------
	//Initial read to define co-ordinates

	Mat gridResult;
	vector<Point> gridMap;
	vector<Point> sgridMap;
	captureFrame(frame, mineHandle, height, width);
	gridResult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);
	//unPressedMat = frame.clone();
	countSquares(frame, temp, gridResult, 0.920, gridMap, Scalar(0, 255, 255));
	cout << "Unpressed Squares: " << gridResult.size() << "\n";
	printSquares(gridMap);
	cv::imshow("Win", frame);
	Point max;
	Point min;
	max.x = 0;
	max.y = 0;
	min.x = width;
	min.y = height;
	//Finding max and min

	//9x9 Grid Sorting Algorithm
	std::sort(gridMap.begin(), gridMap.end(),sortX);
	for (int i = 0; i < 9; i++){
		std::sort(gridMap.begin()+(i*9), gridMap.begin() + ((i+1)*9), sortY);
	}
	printSquares(gridMap);
//	for (int i = 0; i < gridMap.size; i++){

//	}
	Sleep(1000 * 5);
	//----------------------------------------------------------------------------

	//imwrite("Images//Master.jpg", frame);
	//result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);
	char grid[9][9] = {0};
	vector<Point> unsquare;
	vector<Point> oneSquares;
	vector<Point> twoSquares;
	vector<Point> threeSquares;
	vector<Point> fourSquares;
	Mat unPressedMat;
	Mat oneMat;
	Mat twoMat;
	Mat threeMat;
	Mat fourMat;
	until endOfTime{
		if (captureFrame(frame, mineHandle,height,width)==TRUE){
			if (!frame.empty()){
				//matchTemplate(frame, temp, result, TM_CCOEFF_NORMED);
				Mat result;
				result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);
				//unPressedMat = frame.clone();
				countSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255));
				cout << "Unpressed Squares: " << unsquare.size() << "\n";
				printSquares(unsquare);
				result.release();
				if (unsquare.size() != 81){
					Mat oneResult;
					oneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0));
					cout << "One Squares: " << oneSquares.size() << "\n";
					oneResult.release();

					Mat twoResult;
					twoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 0, 0));
					cout << "Two Squares: " << twoSquares.size() << "\n";
					twoResult.release();

					Mat threeResult;
					threeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 0));
					cout << "Three Squares: " << threeSquares.size() << "\n";
					threeResult.release();

					Mat fourResult;
					fourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1);
					//oneMat = frame.clone();
					countSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0));
					cout << "Four Squares: " << fourSquares.size() << "\n";
					fourResult.release();
				}
				cv::imshow("Win", frame);
				//imshow("One", oneMat);
				Sleep(2000);
			}
		}
		if (waitKey(30) >= 0) break;
	}
	return 0;
}<|endoftext|>