<commit_before>#define BOOST_LOG_DYN_LINK
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/log/trivial.hpp>

#include <openssl/evp.h>

#include "chunky.hpp"

template<typename T>
class WebSocket {
public:
   typedef boost::system::error_code error_code;

   enum MessageType {
      continuation = 0x0,
      text         = 0x1,
      binary       = 0x2,
      close        = 0x8,
      ping         = 0x9,
      pong         = 0xa,
      fin          = 0x80
   };

   WebSocket(const std::shared_ptr<T>& stream)
      : stream_(stream) {
   }

   std::shared_ptr<T> stream() { return stream_; }

   // void handler(const error_code& error, uint8_t code, size_t nBytes)
   template<typename MutableBufferSequence, typename ReadHandler>
   void async_receive(const MutableBufferSequence& buffers, ReadHandler handler) {
   }

   template<typename ReadHandler>
   void async_receive(boost::asio::streambuf& streambuf, ReadHandler handler) {
   }

   void read_frame() {
      auto header = std::make_shared<std::array<char, 14> >();
      boost::asio::async_read(
         *stream(), boost::asio::mutable_buffers_1(&(*header)[0], 2),
         [=](const boost::system::error_code& error, size_t) {
            if (error) {
               BOOST_LOG_TRIVIAL(error) << error.message();
               return;
            }

            size_t nLengthBytes = 0;
            size_t nPayloadBytes = (*header)[1] & 0x7f;
            switch (nPayloadBytes) {
            case 126:
               nLengthBytes = 2;
               nPayloadBytes = 0;
               break;
            case 127:
               nLengthBytes = 4;
               nPayloadBytes = 0;
               break;
            }

            const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0;
            char* mask = &(*header)[2 + nLengthBytes];
            std::fill(mask, mask + nMaskBytes, 0);

            boost::asio::async_read(
               *stream(), boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes),
               [=](const boost::system::error_code& error, size_t) mutable {
                  if (error) {
                     BOOST_LOG_TRIVIAL(error) << error.message();
                     return;
                  }

                  for (size_t i = 0; i < nLengthBytes; ++i) {
                     nPayloadBytes <<= 8;
                     nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]);
                  }

                  auto payload = std::make_shared<std::vector<char> >(nPayloadBytes);
                  boost::asio::async_read(
                     *stream(), boost::asio::buffer(*payload),
                     [=](const boost::system::error_code& error, size_t) {
                        if (error) {
                           BOOST_LOG_TRIVIAL(error) << error.message();
                           return;
                        }

                        size_t cindex = 0;
                        for (char& c : *payload)
                           c ^= mask[cindex++ & 0x3];

                        handle_frame((*header)[0], std::move(payload));
                     });
               });
         });

   }

   void handle_ping(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
   }

   void handle_close(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
   }

   void handle_frame(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
      if (type == (fin | ping))
         handle_ping(type, payload);
      else if (type == (fin | close))
         handle_close(type, payload);

      BOOST_LOG_TRIVIAL(info) << boost::format("0x%0x %s")
         % static_cast<unsigned int>(type)
         % std::string(payload->begin(), payload->end());

      read_frame();
   }

   template<typename ConstBufferSequence, typename WriteHandler>
   void async_send(uint8_t meta, const ConstBufferSequence& buffers, WriteHandler&& handler) {
      auto header = std::make_shared<std::vector<char> >(generate_header(meta, buffers));
      boost::asio::async_write(
         *stream(), boost::asio::buffer(*header),
         [=](const error_code& error, size_t) {
            if (error) {
               handler(error, 0);
               return;
            }

            header.get();
            boost::asio::async_write(
               *stream(), buffers,
               [=](const error_code& error, size_t) {
                  if (error) {
                     handler(error, 0);
                     return;
                  }

                  handler(error, boost::asio::buffer_size(buffers));
               });
         });
   }

   template<typename ConstBufferSequence>
   size_t send(uint8_t meta, const ConstBufferSequence& buffers, error_code& error) {
      auto header = generate_header(meta, buffers);
      boost::asio::write(*stream(), boost::asio::buffer(header), error);
      if (error)
         return 0;

      return boost::asio::write(*stream(), buffers, error);
   }

private:
   std::shared_ptr<T> stream_;
   boost::asio::streambuf streambuf_;

   template<typename ConstBufferSequence>
   std::vector<char> generate_header(uint8_t meta, const ConstBufferSequence& buffers) {
      std::vector<char> header;
      header.push_back(static_cast<char>(meta));

      const size_t bufferSize = boost::asio::buffer_size(buffers);
      if (bufferSize < 126) {
         header.push_back(static_cast<char>(bufferSize));
      }
      else if (bufferSize < 65536) {
         header.push_back(static_cast<char>(126));
         header.push_back(static_cast<char>((bufferSize >> 8) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 0) & 0xff));
      }
      else {
         header.push_back(static_cast<char>(127));
         header.push_back(static_cast<char>((bufferSize >> 56) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 48) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 40) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 32) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 24) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 16) & 0xff));
         header.push_back(static_cast<char>((bufferSize >>  8) & 0xff));
         header.push_back(static_cast<char>((bufferSize >>  0) & 0xff));
      }

      return header;
   }
};

template<typename T>
static std::string encode64(T bgn, T end) {
    using namespace boost::archive::iterators;
    typedef base64_from_binary<transform_width<T, 6, 8>> Iterator;
    std::string result((Iterator(bgn)), (Iterator(end)));
    result.resize((result.size() + 3) & ~size_t(3), '=');
    return result;
}

static void handle_connection(const std::shared_ptr<chunky::TCP>& tcp) {
   typedef WebSocket<chunky::TCP> WS;

   BOOST_LOG_TRIVIAL(info) << "creating WebSocket";
   auto ws = std::make_shared<WS>(tcp);

   boost::system::error_code error;
   ws->send(WS::fin | WS::text, boost::asio::buffer(std::string("synchronous send")), error);

   static const std::string s("asynchronous send");
   ws->async_send(
      WS::fin | WS::text, boost::asio::buffer(s),
      [=](const boost::system::error_code& error, size_t) {
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         ws.get();
      });

   ws->read_frame();

   while (true)
      std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
   chunky::SimpleHTTPServer server;
   server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) {
         http->response_status() = 200;
         http->response_headers()["Content-Type"] = "text/html";

         static const std::string html =
            "<!DOCTYPE html>"
            "<title>chunky WebSocket</title>"
            "
chunky WebSocket
"
            "\n";

         boost::system::error_code error;
         boost::asio::write(*http, boost::asio::buffer(html), error);
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         http->finish(error);
      });

   server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) {
         BOOST_LOG_TRIVIAL(info) << boost::format("%s %s")
            % http->request_method()
            % http->request_resource();
         for (const auto& value : http->request_headers())
            BOOST_LOG_TRIVIAL(info) << boost::format("%s: %s")
               % value.first
               % value.second;

         http->response_status() = 101; // Switching Protocols
         http->response_headers()["Upgrade"] = "websocket";
         http->response_headers()["Connection"] = "Upgrade";

         // Compute Sec-WebSocket-Accept header value.
         EVP_MD_CTX sha1;
         EVP_DigestInit(&sha1, EVP_sha1());
         auto key = http->request_headers().find("Sec-WebSocket-Key");
         if (key != http->request_headers().end())
            EVP_DigestUpdate(&sha1, key->second.data(), key->second.size());

         static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
         EVP_DigestUpdate(&sha1, suffix.data(), suffix.size());

         unsigned int digestSize;
         unsigned char digest[EVP_MAX_MD_SIZE];
         EVP_DigestFinal(&sha1, digest, &digestSize);

         http->response_headers()["Sec-WebSocket-Accept"] = encode64(digest, digest + digestSize);

         boost::system::error_code error;
         http->finish();
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         handle_connection(http->stream());
      });

   // Set the optional logging callback.
   server.set_logger([](const std::string& message) {
         BOOST_LOG_TRIVIAL(info) << message;
      });

   // Run the server on all IPv4 and IPv6 interfaces.
   using boost::asio::ip::tcp;
   server.listen(tcp::endpoint(tcp::v4(), 8800));
   server.listen(tcp::endpoint(tcp::v6(), 8800));
   server.run();
   BOOST_LOG_TRIVIAL(info) << "listening on port 8800";

   // Accept new connections for 60 seconds. After that, the server
   // destructor will block until all existing TCP connections are
   // completed. Note that browsers may leave a connection open for
   // several minutes.
   std::this_thread::sleep_for(std::chrono::seconds(60));
   BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)";
   return 0;
}
<commit_msg>Send frame in a single write.<commit_after>#define BOOST_LOG_DYN_LINK
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/log/trivial.hpp>

#include <openssl/evp.h>

#include "chunky.hpp"

template<typename T>
class WebSocket {
public:
   typedef boost::system::error_code error_code;

   enum MessageType {
      continuation = 0x0,
      text         = 0x1,
      binary       = 0x2,
      close        = 0x8,
      ping         = 0x9,
      pong         = 0xa,
      fin          = 0x80
   };

   WebSocket(const std::shared_ptr<T>& stream)
      : stream_(stream) {
   }

   std::shared_ptr<T> stream() { return stream_; }

   void read_frame() {
      auto header = std::make_shared<std::array<char, 14> >();
      boost::asio::async_read(
         *stream(), boost::asio::mutable_buffers_1(&(*header)[0], 2),
         [=](const boost::system::error_code& error, size_t) {
            if (error) {
               BOOST_LOG_TRIVIAL(error) << error.message();
               return;
            }

            size_t nLengthBytes = 0;
            size_t nPayloadBytes = (*header)[1] & 0x7f;
            switch (nPayloadBytes) {
            case 126:
               nLengthBytes = 2;
               nPayloadBytes = 0;
               break;
            case 127:
               nLengthBytes = 4;
               nPayloadBytes = 0;
               break;
            }

            const size_t nMaskBytes = ((*header)[1] & 0x80) ? 4 : 0;
            char* mask = &(*header)[2 + nLengthBytes];
            std::fill(mask, mask + nMaskBytes, 0);

            boost::asio::async_read(
               *stream(), boost::asio::mutable_buffers_1(&(*header)[2], nLengthBytes + nMaskBytes),
               [=](const boost::system::error_code& error, size_t) mutable {
                  if (error) {
                     BOOST_LOG_TRIVIAL(error) << error.message();
                     return;
                  }

                  for (size_t i = 0; i < nLengthBytes; ++i) {
                     nPayloadBytes <<= 8;
                     nPayloadBytes |= static_cast<uint8_t>((*header)[2 + i]);
                  }

                  auto payload = std::make_shared<std::vector<char> >(nPayloadBytes);
                  boost::asio::async_read(
                     *stream(), boost::asio::buffer(*payload),
                     [=](const boost::system::error_code& error, size_t) {
                        if (error) {
                           BOOST_LOG_TRIVIAL(error) << error.message();
                           return;
                        }

                        size_t cindex = 0;
                        for (char& c : *payload)
                           c ^= mask[cindex++ & 0x3];

                        handle_frame((*header)[0], std::move(payload));
                     });
               });
         });

   }

   void handle_ping(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
   }

   void handle_close(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
   }

   void handle_frame(uint8_t type, const std::shared_ptr<std::vector<char> >& payload) {
      if (type == (fin | ping))
         handle_ping(type, payload);
      else if (type == (fin | close))
         handle_close(type, payload);

      BOOST_LOG_TRIVIAL(info) << boost::format("0x%0x %s")
         % static_cast<unsigned int>(type)
         % std::string(payload->begin(), payload->end());

      read_frame();
   }

   template<typename ConstBufferSequence, typename WriteHandler>
   void async_send(uint8_t meta, const ConstBufferSequence& buffers, WriteHandler&& handler) {
      // Build the frame header.
      auto header = std::make_shared<std::vector<char> >(generate_header(meta, buffers));

      // Assemble the frame from the header and payload.
      std::vector<boost::asio::const_buffer> frame;
      frame.emplace_back(header->data(), header->size());
      for (const auto& buffer : buffers)
         frame.emplace_back(buffer);

      boost::asio::async_write(
         *stream(), frame,
         [=](const error_code& error, size_t) {
            if (error) {
               handler(error, 0);
               return;
            }

            header.get();
            handler(error, boost::asio::buffer_size(buffers));
         });
   }

   template<typename ConstBufferSequence>
   size_t send(uint8_t meta, const ConstBufferSequence& buffers, error_code& error) {
      auto header = generate_header(meta, buffers);
      boost::asio::write(*stream(), boost::asio::buffer(header), error);
      if (error)
         return 0;

      return boost::asio::write(*stream(), buffers, error);
   }

private:
   std::shared_ptr<T> stream_;
   boost::asio::streambuf streambuf_;

   template<typename ConstBufferSequence>
   std::vector<char> generate_header(uint8_t meta, const ConstBufferSequence& buffers) {
      std::vector<char> header;
      header.push_back(static_cast<char>(meta));

      const size_t bufferSize = boost::asio::buffer_size(buffers);
      if (bufferSize < 126) {
         header.push_back(static_cast<char>(bufferSize));
      }
      else if (bufferSize < 65536) {
         header.push_back(static_cast<char>(126));
         header.push_back(static_cast<char>((bufferSize >> 8) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 0) & 0xff));
      }
      else {
         header.push_back(static_cast<char>(127));
         header.push_back(static_cast<char>((bufferSize >> 56) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 48) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 40) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 32) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 24) & 0xff));
         header.push_back(static_cast<char>((bufferSize >> 16) & 0xff));
         header.push_back(static_cast<char>((bufferSize >>  8) & 0xff));
         header.push_back(static_cast<char>((bufferSize >>  0) & 0xff));
      }

      return header;
   }
};

template<typename T>
static std::string encode64(T bgn, T end) {
    using namespace boost::archive::iterators;
    typedef base64_from_binary<transform_width<T, 6, 8>> Iterator;
    std::string result((Iterator(bgn)), (Iterator(end)));
    result.resize((result.size() + 3) & ~size_t(3), '=');
    return result;
}

static void handle_connection(const std::shared_ptr<chunky::TCP>& tcp) {
   typedef WebSocket<chunky::TCP> WS;

   BOOST_LOG_TRIVIAL(info) << "creating WebSocket";
   auto ws = std::make_shared<WS>(tcp);

   boost::system::error_code error;
   ws->send(WS::fin | WS::text, boost::asio::buffer(std::string("synchronous send")), error);

   static const std::string s("asynchronous send");
   ws->async_send(
      WS::fin | WS::text, boost::asio::buffer(s),
      [=](const boost::system::error_code& error, size_t) {
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         ws.get();
      });

   ws->read_frame();

   while (true)
      std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
   chunky::SimpleHTTPServer server;
   server.add_handler("/", [](const std::shared_ptr<chunky::HTTP>& http) {
         http->response_status() = 200;
         http->response_headers()["Content-Type"] = "text/html";

         static const std::string html =
            "<!DOCTYPE html>"
            "<title>chunky WebSocket</title>"
            "
chunky WebSocket
"
            "\n";

         boost::system::error_code error;
         boost::asio::write(*http, boost::asio::buffer(html), error);
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         http->finish(error);
      });

   server.add_handler("/ws", [](const std::shared_ptr<chunky::HTTP>& http) {
         BOOST_LOG_TRIVIAL(info) << boost::format("%s %s")
            % http->request_method()
            % http->request_resource();
         for (const auto& value : http->request_headers())
            BOOST_LOG_TRIVIAL(info) << boost::format("%s: %s")
               % value.first
               % value.second;

         http->response_status() = 101; // Switching Protocols
         http->response_headers()["Upgrade"] = "websocket";
         http->response_headers()["Connection"] = "Upgrade";

         // Compute Sec-WebSocket-Accept header value.
         EVP_MD_CTX sha1;
         EVP_DigestInit(&sha1, EVP_sha1());
         auto key = http->request_headers().find("Sec-WebSocket-Key");
         if (key != http->request_headers().end())
            EVP_DigestUpdate(&sha1, key->second.data(), key->second.size());

         static const std::string suffix("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
         EVP_DigestUpdate(&sha1, suffix.data(), suffix.size());

         unsigned int digestSize;
         unsigned char digest[EVP_MAX_MD_SIZE];
         EVP_DigestFinal(&sha1, digest, &digestSize);

         http->response_headers()["Sec-WebSocket-Accept"] = encode64(digest, digest + digestSize);

         boost::system::error_code error;
         http->finish();
         if (error) {
            BOOST_LOG_TRIVIAL(error) << error.message();
            return;
         }

         handle_connection(http->stream());
      });

   // Set the optional logging callback.
   server.set_logger([](const std::string& message) {
         BOOST_LOG_TRIVIAL(info) << message;
      });

   // Run the server on all IPv4 and IPv6 interfaces.
   using boost::asio::ip::tcp;
   server.listen(tcp::endpoint(tcp::v4(), 8800));
   server.listen(tcp::endpoint(tcp::v6(), 8800));
   server.run();
   BOOST_LOG_TRIVIAL(info) << "listening on port 8800";

   // Accept new connections for 60 seconds. After that, the server
   // destructor will block until all existing TCP connections are
   // completed. Note that browsers may leave a connection open for
   // several minutes.
   std::this_thread::sleep_for(std::chrono::seconds(60));
   BOOST_LOG_TRIVIAL(info) << "exiting (blocks until existing connections close)";
   return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream> // TODO Remove
#include <cmake.h>
#include <algorithm>
#include <stdio.h>
#include <Context.h>
#include <Hooks.h>
#include <text.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
Hooks::Hooks ()
{
}

////////////////////////////////////////////////////////////////////////////////
Hooks::~Hooks ()
{
}

////////////////////////////////////////////////////////////////////////////////
void Hooks::initialize ()
{
  // Scan <rc.data.location>/hooks
  Directory d (context.config.get ("data.location"));
  d += "hooks";
  if (d.is_directory () &&
      d.readable ())
  {
    _scripts = d.list ();
    std::sort (_scripts.begin (), _scripts.end ());
  }
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       On launch, after data structures are initiliazed, before
//                    data is loaded.
// Data fed to stdin: None
// Exit code:         0: Success, proceed
//                    !0: Failure, terminate
// Output handled:    0:  context.header ()
//                    !0: context.error ()
void Hooks::onLaunch ()
{
  context.timer_hooks.start ();

  std::vector <std::string> matchingScripts = scripts ("on-launch");
  std::vector <std::string>::iterator i;
  for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)
  {
    std::string output;
    int status = execute (*i, "", output);

    std::vector <std::string> lines;
    split (lines, output, '\n');
    std::vector <std::string>::iterator line;

    if (status == 0)
    {
      for (line = lines.begin (); line != lines.end (); ++line)
      {
        if (line->length () && (*line)[0] == '{')
        {
          Task newTask (*line);
          context.tdb2.add (newTask);
        }
        else
          context.header (*line);
      }
    }
    else
    {
      for (line = lines.begin (); line != lines.end (); ++line)
        context.error (*line);

      throw 0;  // This is how hooks silently terminate processing.
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       On exit, after processing is complete, before output is
//                    displayed.
// Data fed to stdin: None
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  context.footnote ()
//                    !0: context.error ()
void Hooks::onExit ()
{
  context.timer_hooks.start ();

  std::vector <std::string> matchingScripts = scripts ("on-exit");
  std::vector <std::string>::iterator i;
  for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)
  {
    std::string output;
    int status = execute (*i, "", output);

    std::vector <std::string> lines;
    split (lines, output, '\n');
    std::vector <std::string>::iterator line;

    if (status == 0)
    {
      for (line = lines.begin (); line != lines.end (); ++line)
      {
        if (line->length () && (*line)[0] == '{')
        {
          Task newTask (*line);
          context.tdb2.add (newTask);
        }
        else
          context.footnote (*line);
      }
    }
    else
    {
      for (line = lines.begin (); line != lines.end (); ++line)
        context.error (*line);
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       A task is created, before it is committed.
// Data fed to stdin: task JSON
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  modified JSON
//                        context.footnote ()
//                    !0: context.error ()
void Hooks::onAdd (Task& after)
{
  context.timer_hooks.start ();

  std::vector <std::string>::iterator i;
  for (i = _scripts.begin (); i != _scripts.end (); ++i)
  {
    if (i->find ("/on-add") != std::string::npos)
    {
      File script (*i);
      if (script.executable ())
      {
        std::string input = after.composeJSON ();
        std::string output;
        int status = execute (*i, input, output);

        std::vector <std::string> lines;
        split (lines, output, '\n');
        std::vector <std::string>::iterator line;

        if (status == 0)
        {
          for (line = lines.begin (); line != lines.end (); ++line)
            context.footnote (*line);
        }
        else
        {
          for (line = lines.begin (); line != lines.end (); ++line)
            context.error (*line);

          throw 0;  // This is how hooks silently terminate processing.
        }
      }
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       A task is modified, before it is committed.
// Data fed to stdin: before JSON
//                    after JSON
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  modified after JSON
//                        context.footnote ()
//                    !0: context.error ()
void Hooks::onModify (const Task& before, Task& after)
{
  context.timer_hooks.start ();

  std::vector <std::string>::iterator i;
  for (i = _scripts.begin (); i != _scripts.end (); ++i)
  {
    if (i->find ("/on-modify") != std::string::npos)
    {
      File script (*i);
      if (script.executable ())
      {
        std::string afterJSON = after.composeJSON ();
        std::string input = before.composeJSON ()
                          + "\n"
                          + afterJSON;
        std::string output;
        int status = execute (*i, input, output);

        std::vector <std::string> lines;
        split (lines, output, '\n');
        std::vector <std::string>::iterator line;

        if (status == 0)
        {
          after = Task (afterJSON);
          for (line = lines.begin (); line != lines.end (); ++line)
            context.footnote (*line);
        }
        else
        {
          for (line = lines.begin (); line != lines.end (); ++line)
            context.error (*line);

          throw 0;  // This is how hooks silently terminate processing.
        }
      }
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Hooks::scripts (const std::string& event)
{
  std::vector <std::string> matching;
  std::vector <std::string>::iterator i;
  for (i = _scripts.begin (); i != _scripts.end (); ++i)
  {
    if (i->find ("/" + event) != std::string::npos)
    {
      File script (*i);
      if (script.executable ())
        matching.push_back (*i);
    }
  }

  return matching;
}

////////////////////////////////////////////////////////////////////////////////
int Hooks::execute (
  const std::string& command,
  const std::string& input,
  std::string& output)
{
  int status = -1;
  FILE* fp = popen (command.c_str (), "r+");
  if (fp)
  {
    // Write input to fp.
    if (input != "")
    {
      fputs (input.c_str (), fp);
      fflush (fp);
    }

    // Read output from fp.
    output = "";
    char* line = NULL;
    size_t len = 0;
    while (getline (&line, &len, fp) != -1)
    {
      output += line;
      free (line);
      line = NULL;
    }

    fflush (fp);
    status = pclose (fp);
    context.debug (format ("Hooks::execute {1} (status {2})", command, status));
  }

  return status;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Hooks<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream> // TODO Remove
#include <cmake.h>
#include <algorithm>
#include <stdio.h>
#include <Context.h>
#include <Hooks.h>
#include <text.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
Hooks::Hooks ()
{
}

////////////////////////////////////////////////////////////////////////////////
Hooks::~Hooks ()
{
}

////////////////////////////////////////////////////////////////////////////////
void Hooks::initialize ()
{
  // Scan <rc.data.location>/hooks
  Directory d (context.config.get ("data.location"));
  d += "hooks";
  if (d.is_directory () &&
      d.readable ())
  {
    _scripts = d.list ();
    std::sort (_scripts.begin (), _scripts.end ());
  }
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       On launch, after data structures are initiliazed, before
//                    data is loaded.
// Data fed to stdin: None
// Exit code:         0: Success, proceed
//                    !0: Failure, terminate
// Output handled:    0:  context.header ()
//                    !0: context.error ()
void Hooks::onLaunch ()
{
  context.timer_hooks.start ();

  std::vector <std::string> matchingScripts = scripts ("on-launch");
  std::vector <std::string>::iterator i;
  for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)
  {
    std::string output;
    int status = execute (*i, "", output);

    std::vector <std::string> lines;
    split (lines, output, '\n');
    std::vector <std::string>::iterator line;

    if (status == 0)
    {
      for (line = lines.begin (); line != lines.end (); ++line)
      {
        if (line->length () && (*line)[0] == '{')
        {
          Task newTask (*line);
          context.tdb2.add (newTask);
        }
        else
          context.header (*line);
      }
    }
    else
    {
      for (line = lines.begin (); line != lines.end (); ++line)
        context.error (*line);

      throw 0;  // This is how hooks silently terminate processing.
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       On exit, after processing is complete, before output is
//                    displayed.
// Data fed to stdin: None
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  context.footnote ()
//                    !0: context.error ()
void Hooks::onExit ()
{
  context.timer_hooks.start ();

  std::vector <std::string> matchingScripts = scripts ("on-exit");
  std::vector <std::string>::iterator i;
  for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)
  {
    std::string output;
    int status = execute (*i, "", output);

    std::vector <std::string> lines;
    split (lines, output, '\n');
    std::vector <std::string>::iterator line;

    if (status == 0)
    {
      for (line = lines.begin (); line != lines.end (); ++line)
      {
        if (line->length () && (*line)[0] == '{')
        {
          Task newTask (*line);
          context.tdb2.add (newTask);
        }
        else
          context.footnote (*line);
      }
    }
    else
    {
      for (line = lines.begin (); line != lines.end (); ++line)
        context.error (*line);
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       A task is created, before it is committed.
// Data fed to stdin: task JSON
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  modified JSON
//                        context.footnote ()
//                    !0: context.error ()
void Hooks::onAdd (Task& after)
{
  context.timer_hooks.start ();

  std::vector <std::string> matchingScripts = scripts ("on-add");
  std::vector <std::string>::iterator i;
  for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)
  {
    std::string input = after.composeJSON () + "\n";
    std::string output;
    int status = execute (*i, input, output);

    std::vector <std::string> lines;
    split (lines, output, '\n');
    std::vector <std::string>::iterator line;

    if (status == 0)
    {
      bool first = true;
      for (line = lines.begin (); line != lines.end (); ++line)
      {
        if (line->length () && (*line)[0] == '{')
        {
          Task newTask (*line);

          if (first)
          {
            after = newTask;
            first = false;
          }
          else
            context.tdb2.add (newTask);
        }
        else
          context.footnote (*line);
      }
    }
    else
    {
      for (line = lines.begin (); line != lines.end (); ++line)
        context.error (*line);

      throw 0;  // This is how hooks silently terminate processing.
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
// Occurs when:       A task is modified, before it is committed.
// Data fed to stdin: before JSON
//                    after JSON
// Exit code:         0: Success
//                    !0: Failure
// Output handled:    0:  modified after JSON
//                        context.footnote ()
//                    !0: context.error ()
void Hooks::onModify (const Task& before, Task& after)
{
  context.timer_hooks.start ();

  std::vector <std::string>::iterator i;
  for (i = _scripts.begin (); i != _scripts.end (); ++i)
  {
    if (i->find ("/on-modify") != std::string::npos)
    {
      File script (*i);
      if (script.executable ())
      {
        std::string afterJSON = after.composeJSON ();
        std::string input = before.composeJSON ()
                          + "\n"
                          + afterJSON;
        std::string output;
        int status = execute (*i, input, output);

        std::vector <std::string> lines;
        split (lines, output, '\n');
        std::vector <std::string>::iterator line;

        if (status == 0)
        {
          after = Task (afterJSON);
          for (line = lines.begin (); line != lines.end (); ++line)
            context.footnote (*line);
        }
        else
        {
          for (line = lines.begin (); line != lines.end (); ++line)
            context.error (*line);

          throw 0;  // This is how hooks silently terminate processing.
        }
      }
    }
  }

  context.timer_hooks.stop ();
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Hooks::scripts (const std::string& event)
{
  std::vector <std::string> matching;
  std::vector <std::string>::iterator i;
  for (i = _scripts.begin (); i != _scripts.end (); ++i)
  {
    if (i->find ("/" + event) != std::string::npos)
    {
      File script (*i);
      if (script.executable ())
        matching.push_back (*i);
    }
  }

  return matching;
}

////////////////////////////////////////////////////////////////////////////////
int Hooks::execute (
  const std::string& command,
  const std::string& input,
  std::string& output)
{
  int status = -1;
  FILE* fp = popen (command.c_str (), "r+");
  if (fp)
  {
    // Write input to fp.
    if (input != "")
    {
      fputs (input.c_str (), fp);
      fflush (fp);
    }

    // Read output from fp.
    output = "";
    char* line = NULL;
    size_t len = 0;
    while (getline (&line, &len, fp) != -1)
    {
      output += line;
      free (line);
      line = NULL;
    }

    fflush (fp);
    status = pclose (fp);
    context.debug (format ("Hooks::execute {1} (status {2})", command, status));
  }

  return status;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include "NOD/DiscBase.hpp"
#include "NOD/IFileIO.hpp"
#include "NOD/DirectoryEnumerator.hpp"
#include "NOD/NOD.hpp"

#include <stdio.h>
#include <errno.h>

#ifndef _WIN32
#include <unistd.h>
#endif

#include <algorithm>

namespace NOD
{

void DiscBase::IPartition::parseFST(IPartReadStream& s)
{
    std::unique_ptr<uint8_t[]> fst(new uint8_t[m_fstSz]);
    s.seek(m_fstOff);
    s.read(fst.get(), m_fstSz);

    const FSTNode* nodes = (FSTNode*)fst.get();

    /* Root node indicates the count of all contained nodes */
    uint32_t nodeCount = nodes[0].getLength();
    const char* names = (char*)fst.get() + 12 * nodeCount;
    m_nodes.clear();
    m_nodes.reserve(nodeCount);

    /* Construct nodes */
    for (uint32_t n=0 ; n<nodeCount ; ++n)
    {
        const FSTNode& node = nodes[n];
        m_nodes.emplace_back(*this, node, n ? names + node.getNameOffset() : "");
    }

    /* Setup dir-child iterators */
    for (std::vector<Node>::iterator it=m_nodes.begin();
         it != m_nodes.end();
         ++it)
    {
        Node& node = *it;
        if (node.m_kind == Node::Kind::Directory)
        {
            node.m_childrenBegin = it + 1;
            node.m_childrenEnd = m_nodes.begin() + node.m_discLength;
        }
    }
}

void DiscBase::IPartition::parseDOL(IPartReadStream& s)
{
    /* Read Dol header */
    DOLHeader dolHeader;
    s.read(&dolHeader, sizeof(DOLHeader));

    /* Calculate Dol size */
    uint32_t dolSize = SBig(dolHeader.textOff[0]);
    for (uint32_t i = 0 ; i < 7 ; i++)
        dolSize += SBig(dolHeader.textSizes[i]);
    for (uint32_t i = 0 ; i < 11 ; i++)
        dolSize += SBig(dolHeader.dataSizes[i]);

    m_dolSz = dolSize;
}

bool DiscBase::IPartition::Node::extractToDirectory(const SystemString& basePath,
                                                    const ExtractionContext& ctx) const
{
    SystemStringView nameView(getName());
    SystemString path = basePath + _S("/") + nameView.sys_str();

    if (m_kind == Kind::Directory)
    {
        if (ctx.verbose && ctx.progressCB && !getName().empty())
            ctx.progressCB(getName());
        if (Mkdir(path.c_str(), 0755) && errno != EEXIST)
        {
            LogModule.report(LogVisor::Error, _S("unable to mkdir '%s'"), path.c_str());
            return false;
        }
        for (Node& subnode : *this)
            if (!subnode.extractToDirectory(path, ctx))
                return false;
    }
    else if (m_kind == Kind::File)
    {
        Sstat theStat;
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB(getName());

        if (ctx.force || Stat(path.c_str(), &theStat))
        {
            std::unique_ptr<IPartReadStream> rs = beginReadStream();
            std::unique_ptr<IFileIO::IWriteStream> ws = NewFileIO(path)->beginWriteStream();
            ws->copyFromDisc(*rs, m_discLength);
        }
    }
    return true;
}

bool DiscBase::IPartition::extractToDirectory(const SystemString& path,
                                              const ExtractionContext& ctx)
{
    Sstat theStat;
    if (Mkdir(path.c_str(), 0755) && errno != EEXIST)
    {
        LogModule.report(LogVisor::Error, _S("unable to mkdir '%s'"), path.c_str());
        return false;
    }

    /* Extract Apploader */
    SystemString apploaderPath = path + _S("/apploader.bin");
    if (ctx.force || Stat(apploaderPath.c_str(), &theStat))
    {
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB("apploader.bin");
        std::unique_ptr<uint8_t[]> buf = getApploaderBuf();
        NewFileIO(apploaderPath)->beginWriteStream()->write(buf.get(), m_apploaderSz);
    }

    /* Extract Dol */
    SystemString dolPath = path + _S("/boot.dol");
    if (ctx.force || Stat(dolPath.c_str(), &theStat))
    {
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB("boot.dol");
        std::unique_ptr<uint8_t[]> buf = getDOLBuf();
        NewFileIO(dolPath)->beginWriteStream()->write(buf.get(), m_dolSz);
    }

    /* Extract Filesystem */
    return m_nodes[0].extractToDirectory(path, ctx);
}

static uint64_t GetInode(const SystemChar* path)
{
    uint64_t inode;
#if _WIN32
    HANDLE fp = CreateFileW(path,
                            GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            nullptr,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            nullptr);
    if (!fp)
        LogModule.report(LogVisor::FatalError, _S("unable to open %s"), path);
    BY_HANDLE_FILE_INFORMATION info;
    if (!GetFileInformationByHandle(fp, &info))
        LogModule.report(LogVisor::FatalError, _S("unable to GetFileInformationByHandle %s"), path);
    inode = uint64_t(info.nFileIndexHigh) << 32;
    inode |= uint64_t(info.nFileIndexLow);
    CloseHandle(fp);
#else
    struct stat st;
    if (stat(path, &st))
        LogModule.report(LogVisor::FatalError, _S("unable to stat %s"), path);
    inode = uint64_t(st.st_ino);
#endif
    return inode;
}

static bool IsSystemFile(const SystemString& name)
{
    if (name.size() < 4)
        return false;

    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".dol")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".rel")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".rso")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".sel")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".bnr")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".elf")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".wad")))
        return true;

    return false;
}

void DiscBuilderBase::PartitionBuilderBase::recursiveBuildNodes(bool system, const SystemChar* dirIn,
                                                                uint64_t dolInode)
{
    DirectoryEnumerator dEnum(dirIn, DirectoryEnumerator::Mode::DirsThenFilesSorted, false, false, true);
    for (const DirectoryEnumerator::Entry& e : dEnum)
    {
        if (e.m_isDir)
        {
            size_t dirNodeIdx = m_buildNodes.size();
            recursiveBuildNodes(system, e.m_path.c_str(), dolInode);
        }
        else
        {
            bool isSys = IsSystemFile(e.m_name);
            if (system ^ isSys)
                continue;

            if (dolInode == GetInode(e.m_path.c_str()))
                continue;

            size_t fileSz = ROUND_UP_32(e.m_fileSz);
            uint64_t fileOff = userAllocate(fileSz);
            m_fileOffsetsSizes[e.m_path] = std::make_pair(fileOff, fileSz);
            std::unique_ptr<IFileIO::IWriteStream> ws = m_parent.getFileIO().beginWriteStream(fileOff);
            FILE* fp = Fopen(e.m_path.c_str(), _S("rb"), FileLockType::Read);
            if (!fp)
                LogModule.report(LogVisor::FatalError, _S("unable to open '%s' for reading"), e.m_path.c_str());
            char buf[0x8000];
            size_t xferSz = 0;
            ++m_parent.m_progressIdx;
            while (xferSz < e.m_fileSz)
            {
                size_t rdSz = fread(buf, 1, NOD::min(size_t(0x8000ul), e.m_fileSz - xferSz), fp);
                if (!rdSz)
                    break;
                ws->write(buf, rdSz);
                xferSz += rdSz;
                m_parent.m_progressCB(m_parent.m_progressIdx, e.m_name, xferSz);
            }
            fclose(fp);
            for (size_t i=0 ; i<fileSz-xferSz ; ++i)
                ws->write("\xff", 1);
        }
    }
}

void DiscBuilderBase::PartitionBuilderBase::recursiveBuildFST(const SystemChar* dirIn, uint64_t dolInode,
                                                              std::function<void(void)> incParents)
{
    DirectoryEnumerator dEnum(dirIn, DirectoryEnumerator::Mode::DirsThenFilesSorted, false, false, true);
    for (const DirectoryEnumerator::Entry& e : dEnum)
    {
        if (e.m_isDir)
        {
            size_t dirNodeIdx = m_buildNodes.size();
            m_buildNodes.emplace_back(true, m_buildNameOff, 0, dirNodeIdx+1);
            addBuildName(e.m_name);
            incParents();
            recursiveBuildFST(e.m_path.c_str(), dolInode, [&](){m_buildNodes[dirNodeIdx].incrementLength(); incParents();});
        }
        else
        {
            if (dolInode == GetInode(e.m_path.c_str()))
            {
                m_buildNodes.emplace_back(false, m_buildNameOff, packOffset(m_dolOffset), m_dolSize);
                addBuildName(e.m_name);
                incParents();
                continue;
            }

            std::pair<uint64_t,uint64_t> fileOffSz = m_fileOffsetsSizes.at(e.m_path);
            m_buildNodes.emplace_back(false, m_buildNameOff, packOffset(fileOffSz.first), fileOffSz.second);
            addBuildName(e.m_name);
            incParents();
        }
    }
}

bool DiscBuilderBase::PartitionBuilderBase::buildFromDirectory(const SystemChar* dirIn,
                                                            const SystemChar* dolIn,
                                                            const SystemChar* apploaderIn)
{
    if (!dirIn || !dolIn || !apploaderIn)
        LogModule.report(LogVisor::FatalError, _S("all arguments must be supplied to buildFromDirectory()"));

    /* Clear file */
    m_parent.getFileIO().beginWriteStream();
    ++m_parent.m_progressIdx;
    m_parent.m_progressCB(m_parent.m_progressIdx, _S("Preparing output image"), -1);

    /* Add root node */
    m_buildNodes.emplace_back(true, m_buildNameOff, 0, 1);
    addBuildName(_S("<root>"));

    /* Write DOL first (ensures that it's within a 32-bit offset for Wii apploaders) */
    {
        Sstat dolStat;
        if (Stat(dolIn, &dolStat))
            LogModule.report(LogVisor::FatalError, _S("unable to stat %s"), dolIn);
        size_t fileSz = ROUND_UP_32(dolStat.st_size);
        uint64_t fileOff = userAllocate(fileSz);
        m_dolOffset = fileOff;
        m_dolSize = fileSz;
        std::unique_ptr<IFileIO::IWriteStream> ws = m_parent.getFileIO().beginWriteStream(fileOff);
        FILE* fp = Fopen(dolIn, _S("rb"), FileLockType::Read);
        if (!fp)
            LogModule.report(LogVisor::FatalError, _S("unable to open '%s' for reading"), dolIn);
        char buf[8192];
        size_t xferSz = 0;
        SystemString dolName(dolIn);
        ++m_parent.m_progressIdx;
        while (xferSz < dolStat.st_size)
        {
            size_t rdSz = fread(buf, 1, std::min(size_t(8192), size_t(dolStat.st_size - xferSz)), fp);
            if (!rdSz)
                break;
            ws->write(buf, rdSz);
            xferSz += rdSz;
            m_parent.m_progressCB(m_parent.m_progressIdx, dolName, xferSz);
        }
        fclose(fp);
        for (size_t i=0 ; i<fileSz-xferSz ; ++i)
            ws->write("\xff", 1);
    }

    /* Gather files in root directory */
    uint64_t dolInode = GetInode(dolIn);
    recursiveBuildNodes(true, dirIn, dolInode);
    recursiveBuildNodes(false, dirIn, dolInode);
    recursiveBuildFST(dirIn, dolInode, [&](){m_buildNodes[0].incrementLength();});

    return true;
}

}
<commit_msg>Replace errant std::min call<commit_after>#include "NOD/DiscBase.hpp"
#include "NOD/IFileIO.hpp"
#include "NOD/DirectoryEnumerator.hpp"
#include "NOD/NOD.hpp"

#include <stdio.h>
#include <errno.h>

#ifndef _WIN32
#include <unistd.h>
#endif

#include <algorithm>

namespace NOD
{

void DiscBase::IPartition::parseFST(IPartReadStream& s)
{
    std::unique_ptr<uint8_t[]> fst(new uint8_t[m_fstSz]);
    s.seek(m_fstOff);
    s.read(fst.get(), m_fstSz);

    const FSTNode* nodes = (FSTNode*)fst.get();

    /* Root node indicates the count of all contained nodes */
    uint32_t nodeCount = nodes[0].getLength();
    const char* names = (char*)fst.get() + 12 * nodeCount;
    m_nodes.clear();
    m_nodes.reserve(nodeCount);

    /* Construct nodes */
    for (uint32_t n=0 ; n<nodeCount ; ++n)
    {
        const FSTNode& node = nodes[n];
        m_nodes.emplace_back(*this, node, n ? names + node.getNameOffset() : "");
    }

    /* Setup dir-child iterators */
    for (std::vector<Node>::iterator it=m_nodes.begin();
         it != m_nodes.end();
         ++it)
    {
        Node& node = *it;
        if (node.m_kind == Node::Kind::Directory)
        {
            node.m_childrenBegin = it + 1;
            node.m_childrenEnd = m_nodes.begin() + node.m_discLength;
        }
    }
}

void DiscBase::IPartition::parseDOL(IPartReadStream& s)
{
    /* Read Dol header */
    DOLHeader dolHeader;
    s.read(&dolHeader, sizeof(DOLHeader));

    /* Calculate Dol size */
    uint32_t dolSize = SBig(dolHeader.textOff[0]);
    for (uint32_t i = 0 ; i < 7 ; i++)
        dolSize += SBig(dolHeader.textSizes[i]);
    for (uint32_t i = 0 ; i < 11 ; i++)
        dolSize += SBig(dolHeader.dataSizes[i]);

    m_dolSz = dolSize;
}

bool DiscBase::IPartition::Node::extractToDirectory(const SystemString& basePath,
                                                    const ExtractionContext& ctx) const
{
    SystemStringView nameView(getName());
    SystemString path = basePath + _S("/") + nameView.sys_str();

    if (m_kind == Kind::Directory)
    {
        if (ctx.verbose && ctx.progressCB && !getName().empty())
            ctx.progressCB(getName());
        if (Mkdir(path.c_str(), 0755) && errno != EEXIST)
        {
            LogModule.report(LogVisor::Error, _S("unable to mkdir '%s'"), path.c_str());
            return false;
        }
        for (Node& subnode : *this)
            if (!subnode.extractToDirectory(path, ctx))
                return false;
    }
    else if (m_kind == Kind::File)
    {
        Sstat theStat;
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB(getName());

        if (ctx.force || Stat(path.c_str(), &theStat))
        {
            std::unique_ptr<IPartReadStream> rs = beginReadStream();
            std::unique_ptr<IFileIO::IWriteStream> ws = NewFileIO(path)->beginWriteStream();
            ws->copyFromDisc(*rs, m_discLength);
        }
    }
    return true;
}

bool DiscBase::IPartition::extractToDirectory(const SystemString& path,
                                              const ExtractionContext& ctx)
{
    Sstat theStat;
    if (Mkdir(path.c_str(), 0755) && errno != EEXIST)
    {
        LogModule.report(LogVisor::Error, _S("unable to mkdir '%s'"), path.c_str());
        return false;
    }

    /* Extract Apploader */
    SystemString apploaderPath = path + _S("/apploader.bin");
    if (ctx.force || Stat(apploaderPath.c_str(), &theStat))
    {
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB("apploader.bin");
        std::unique_ptr<uint8_t[]> buf = getApploaderBuf();
        NewFileIO(apploaderPath)->beginWriteStream()->write(buf.get(), m_apploaderSz);
    }

    /* Extract Dol */
    SystemString dolPath = path + _S("/boot.dol");
    if (ctx.force || Stat(dolPath.c_str(), &theStat))
    {
        if (ctx.verbose && ctx.progressCB)
            ctx.progressCB("boot.dol");
        std::unique_ptr<uint8_t[]> buf = getDOLBuf();
        NewFileIO(dolPath)->beginWriteStream()->write(buf.get(), m_dolSz);
    }

    /* Extract Filesystem */
    return m_nodes[0].extractToDirectory(path, ctx);
}

static uint64_t GetInode(const SystemChar* path)
{
    uint64_t inode;
#if _WIN32
    HANDLE fp = CreateFileW(path,
                            GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            nullptr,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            nullptr);
    if (!fp)
        LogModule.report(LogVisor::FatalError, _S("unable to open %s"), path);
    BY_HANDLE_FILE_INFORMATION info;
    if (!GetFileInformationByHandle(fp, &info))
        LogModule.report(LogVisor::FatalError, _S("unable to GetFileInformationByHandle %s"), path);
    inode = uint64_t(info.nFileIndexHigh) << 32;
    inode |= uint64_t(info.nFileIndexLow);
    CloseHandle(fp);
#else
    struct stat st;
    if (stat(path, &st))
        LogModule.report(LogVisor::FatalError, _S("unable to stat %s"), path);
    inode = uint64_t(st.st_ino);
#endif
    return inode;
}

static bool IsSystemFile(const SystemString& name)
{
    if (name.size() < 4)
        return false;

    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".dol")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".rel")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".rso")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".sel")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".bnr")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".elf")))
        return true;
    if (!StrCaseCmp((&*(name.cend() - 4)), _S(".wad")))
        return true;

    return false;
}

void DiscBuilderBase::PartitionBuilderBase::recursiveBuildNodes(bool system, const SystemChar* dirIn,
                                                                uint64_t dolInode)
{
    DirectoryEnumerator dEnum(dirIn, DirectoryEnumerator::Mode::DirsThenFilesSorted, false, false, true);
    for (const DirectoryEnumerator::Entry& e : dEnum)
    {
        if (e.m_isDir)
        {
            size_t dirNodeIdx = m_buildNodes.size();
            recursiveBuildNodes(system, e.m_path.c_str(), dolInode);
        }
        else
        {
            bool isSys = IsSystemFile(e.m_name);
            if (system ^ isSys)
                continue;

            if (dolInode == GetInode(e.m_path.c_str()))
                continue;

            size_t fileSz = ROUND_UP_32(e.m_fileSz);
            uint64_t fileOff = userAllocate(fileSz);
            m_fileOffsetsSizes[e.m_path] = std::make_pair(fileOff, fileSz);
            std::unique_ptr<IFileIO::IWriteStream> ws = m_parent.getFileIO().beginWriteStream(fileOff);
            FILE* fp = Fopen(e.m_path.c_str(), _S("rb"), FileLockType::Read);
            if (!fp)
                LogModule.report(LogVisor::FatalError, _S("unable to open '%s' for reading"), e.m_path.c_str());
            char buf[0x8000];
            size_t xferSz = 0;
            ++m_parent.m_progressIdx;
            while (xferSz < e.m_fileSz)
            {
                size_t rdSz = fread(buf, 1, NOD::min(size_t(0x8000ul), e.m_fileSz - xferSz), fp);
                if (!rdSz)
                    break;
                ws->write(buf, rdSz);
                xferSz += rdSz;
                m_parent.m_progressCB(m_parent.m_progressIdx, e.m_name, xferSz);
            }
            fclose(fp);
            for (size_t i=0 ; i<fileSz-xferSz ; ++i)
                ws->write("\xff", 1);
        }
    }
}

void DiscBuilderBase::PartitionBuilderBase::recursiveBuildFST(const SystemChar* dirIn, uint64_t dolInode,
                                                              std::function<void(void)> incParents)
{
    DirectoryEnumerator dEnum(dirIn, DirectoryEnumerator::Mode::DirsThenFilesSorted, false, false, true);
    for (const DirectoryEnumerator::Entry& e : dEnum)
    {
        if (e.m_isDir)
        {
            size_t dirNodeIdx = m_buildNodes.size();
            m_buildNodes.emplace_back(true, m_buildNameOff, 0, dirNodeIdx+1);
            addBuildName(e.m_name);
            incParents();
            recursiveBuildFST(e.m_path.c_str(), dolInode, [&](){m_buildNodes[dirNodeIdx].incrementLength(); incParents();});
        }
        else
        {
            if (dolInode == GetInode(e.m_path.c_str()))
            {
                m_buildNodes.emplace_back(false, m_buildNameOff, packOffset(m_dolOffset), m_dolSize);
                addBuildName(e.m_name);
                incParents();
                continue;
            }

            std::pair<uint64_t,uint64_t> fileOffSz = m_fileOffsetsSizes.at(e.m_path);
            m_buildNodes.emplace_back(false, m_buildNameOff, packOffset(fileOffSz.first), fileOffSz.second);
            addBuildName(e.m_name);
            incParents();
        }
    }
}

bool DiscBuilderBase::PartitionBuilderBase::buildFromDirectory(const SystemChar* dirIn,
                                                            const SystemChar* dolIn,
                                                            const SystemChar* apploaderIn)
{
    if (!dirIn || !dolIn || !apploaderIn)
        LogModule.report(LogVisor::FatalError, _S("all arguments must be supplied to buildFromDirectory()"));

    /* Clear file */
    m_parent.getFileIO().beginWriteStream();
    ++m_parent.m_progressIdx;
    m_parent.m_progressCB(m_parent.m_progressIdx, _S("Preparing output image"), -1);

    /* Add root node */
    m_buildNodes.emplace_back(true, m_buildNameOff, 0, 1);
    addBuildName(_S("<root>"));

    /* Write DOL first (ensures that it's within a 32-bit offset for Wii apploaders) */
    {
        Sstat dolStat;
        if (Stat(dolIn, &dolStat))
            LogModule.report(LogVisor::FatalError, _S("unable to stat %s"), dolIn);
        size_t fileSz = ROUND_UP_32(dolStat.st_size);
        uint64_t fileOff = userAllocate(fileSz);
        m_dolOffset = fileOff;
        m_dolSize = fileSz;
        std::unique_ptr<IFileIO::IWriteStream> ws = m_parent.getFileIO().beginWriteStream(fileOff);
        FILE* fp = Fopen(dolIn, _S("rb"), FileLockType::Read);
        if (!fp)
            LogModule.report(LogVisor::FatalError, _S("unable to open '%s' for reading"), dolIn);
        char buf[8192];
        size_t xferSz = 0;
        SystemString dolName(dolIn);
        ++m_parent.m_progressIdx;
        while (xferSz < dolStat.st_size)
        {
            size_t rdSz = fread(buf, 1, NOD::min(size_t(8192), dolStat.st_size - xferSz), fp);
            if (!rdSz)
                break;
            ws->write(buf, rdSz);
            xferSz += rdSz;
            m_parent.m_progressCB(m_parent.m_progressIdx, dolName, xferSz);
        }
        fclose(fp);
        for (size_t i=0 ; i<fileSz-xferSz ; ++i)
            ws->write("\xff", 1);
    }

    /* Gather files in root directory */
    uint64_t dolInode = GetInode(dolIn);
    recursiveBuildNodes(true, dirIn, dolInode);
    recursiveBuildNodes(false, dirIn, dolInode);
    recursiveBuildFST(dirIn, dolInode, [&](){m_buildNodes[0].incrementLength();});

    return true;
}

}
<|endoftext|>


<commit_before>//===- Block.cpp - MLIR Block Class ---------------------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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 "mlir/IR/Block.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Operation.h"
using namespace mlir;

//===----------------------------------------------------------------------===//
// BlockArgument
//===----------------------------------------------------------------------===//

/// Returns the number of this argument.
unsigned BlockArgument::getArgNumber() {
  // Arguments are not stored in place, so we have to find it within the list.
  auto argList = getOwner()->getArguments();
  return std::distance(argList.begin(), llvm::find(argList, this));
}

//===----------------------------------------------------------------------===//
// Block
//===----------------------------------------------------------------------===//

Block::~Block() {
  assert(!verifyInstOrder() && "Expected valid operation ordering.");
  clear();

  for (auto *arg : arguments)
    if (!arg->use_empty())
      arg->user_begin()->dump();

  llvm::DeleteContainerPointers(arguments);
}

Region *Block::getParent() { return parentValidInstOrderPair.getPointer(); }

/// Returns the closest surrounding operation that contains this block or
/// nullptr if this block is unlinked.
Operation *Block::getParentOp() {
  return getParent() ? getParent()->getParentOp() : nullptr;
}

/// Return if this block is the entry block in the parent region.
bool Block::isEntryBlock() { return this == &getParent()->front(); }

/// Insert this block (which must not already be in a region) right before the
/// specified block.
void Block::insertBefore(Block *block) {
  assert(!getParent() && "already inserted into a block!");
  assert(block->getParent() && "cannot insert before a block without a parent");
  block->getParent()->getBlocks().insert(Region::iterator(block), this);
}

/// Unlink this Block from its parent Region and delete it.
void Block::erase() {
  assert(getParent() && "Block has no parent");
  getParent()->getBlocks().erase(this);
}

/// Returns 'op' if 'op' lies in this block, or otherwise finds the
/// ancestor operation of 'op' that lies in this block. Returns nullptr if
/// the latter fails.
Operation *Block::findAncestorInstInBlock(Operation &op) {
  // Traverse up the operation hierarchy starting from the owner of operand to
  // find the ancestor operation that resides in the block of 'forInst'.
  auto *currInst = &op;
  while (currInst->getBlock() != this) {
    currInst = currInst->getParentOp();
    if (!currInst)
      return nullptr;
  }
  return currInst;
}

/// This drops all operand uses from operations within this block, which is
/// an essential step in breaking cyclic dependences between references when
/// they are to be deleted.
void Block::dropAllReferences() {
  for (Operation &i : *this)
    i.dropAllReferences();
}

void Block::dropAllDefinedValueUses() {
  for (auto *arg : getArguments())
    arg->dropAllUses();
  for (auto &op : *this)
    op.dropAllDefinedValueUses();
  dropAllUses();
}

/// Returns true if the ordering of the child operations is valid, false
/// otherwise.
bool Block::isInstOrderValid() { return parentValidInstOrderPair.getInt(); }

/// Invalidates the current ordering of operations.
void Block::invalidateInstOrder() {
  // Validate the current ordering.
  assert(!verifyInstOrder());
  parentValidInstOrderPair.setInt(false);
}

/// Verifies the current ordering of child operations. Returns false if the
/// order is valid, true otherwise.
bool Block::verifyInstOrder() {
  // The order is already known to be invalid.
  if (!isInstOrderValid())
    return false;
  // The order is valid if there are less than 2 operations.
  if (operations.empty() || std::next(operations.begin()) == operations.end())
    return false;

  Operation *prev = nullptr;
  for (auto &i : *this) {
    // The previous operation must have a smaller order index than the next as
    // it appears earlier in the list.
    if (prev && prev->orderIndex >= i.orderIndex)
      return true;
    prev = &i;
  }
  return false;
}

/// Recomputes the ordering of child operations within the block.
void Block::recomputeInstOrder() {
  parentValidInstOrderPair.setInt(true);

  // TODO(riverriddle) Have non-congruent indices to reduce the number of times
  // an insert invalidates the list.
  unsigned orderIndex = 0;
  for (auto &op : *this)
    op.orderIndex = orderIndex++;
}

//===----------------------------------------------------------------------===//
// Argument list management.
//===----------------------------------------------------------------------===//

BlockArgument *Block::addArgument(Type type) {
  auto *arg = new BlockArgument(type, this);
  arguments.push_back(arg);
  return arg;
}

/// Add one argument to the argument list for each type specified in the list.
auto Block::addArguments(ArrayRef<Type> types)
    -> llvm::iterator_range<args_iterator> {
  arguments.reserve(arguments.size() + types.size());
  auto initialSize = arguments.size();
  for (auto type : types) {
    addArgument(type);
  }
  return {arguments.data() + initialSize, arguments.data() + arguments.size()};
}

void Block::eraseArgument(unsigned index, bool updatePredTerms) {
  assert(index < arguments.size());

  // Delete the argument.
  delete arguments[index];
  arguments.erase(arguments.begin() + index);

  // If we aren't updating predecessors, there is nothing left to do.
  if (!updatePredTerms)
    return;

  // Erase this argument from each of the predecessor's terminator.
  for (auto predIt = pred_begin(), predE = pred_end(); predIt != predE;
       ++predIt) {
    auto *predTerminator = (*predIt)->getTerminator();
    predTerminator->eraseSuccessorOperand(predIt.getSuccessorIndex(), index);
  }
}

//===----------------------------------------------------------------------===//
// Terminator management
//===----------------------------------------------------------------------===//

/// Get the terminator operation of this block. This function asserts that
/// the block has a valid terminator operation.
Operation *Block::getTerminator() {
  assert(!empty() && !back().isKnownNonTerminator());
  return &back();
}

/// Return true if this block has no predecessors.
bool Block::hasNoPredecessors() { return pred_begin() == pred_end(); }

// Indexed successor access.
unsigned Block::getNumSuccessors() {
  return empty() ? 0 : back().getNumSuccessors();
}

Block *Block::getSuccessor(unsigned i) {
  assert(i < getNumSuccessors());
  return getTerminator()->getSuccessor(i);
}

/// If this block has exactly one predecessor, return it.  Otherwise, return
/// null.
///
/// Note that multiple edges from a single block (e.g. if you have a cond
/// branch with the same block as the true/false destinations) is not
/// considered to be a single predecessor.
Block *Block::getSinglePredecessor() {
  auto it = pred_begin();
  if (it == pred_end())
    return nullptr;
  auto *firstPred = *it;
  ++it;
  return it == pred_end() ? firstPred : nullptr;
}

//===----------------------------------------------------------------------===//
// Other
//===----------------------------------------------------------------------===//

/// Split the block into two blocks before the specified operation or
/// iterator.
///
/// Note that all operations BEFORE the specified iterator stay as part of
/// the original basic block, and the rest of the operations in the original
/// block are moved to the new block, including the old terminator.  The
/// original block is left without a terminator.
///
/// The newly formed Block is returned, and the specified iterator is
/// invalidated.
Block *Block::splitBlock(iterator splitBefore) {
  // Start by creating a new basic block, and insert it immediate after this
  // one in the containing region.
  auto newBB = new Block();
  getParent()->getBlocks().insert(std::next(Region::iterator(this)), newBB);

  // Move all of the operations from the split point to the end of the region
  // into the new block.
  newBB->getOperations().splice(newBB->end(), getOperations(), splitBefore,
                                end());
  return newBB;
}

//===----------------------------------------------------------------------===//
// Predecessors
//===----------------------------------------------------------------------===//

Block *PredecessorIterator::unwrap(BlockOperand &value) {
  return value.getOwner()->getBlock();
}

/// Get the successor number in the predecessor terminator.
unsigned PredecessorIterator::getSuccessorIndex() const {
  return I->getOperandNumber();
}
<commit_msg>NFC: Remove stray logging from ~Block(). PiperOrigin-RevId: 269941815<commit_after>//===- Block.cpp - MLIR Block Class ---------------------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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 "mlir/IR/Block.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Operation.h"
using namespace mlir;

//===----------------------------------------------------------------------===//
// BlockArgument
//===----------------------------------------------------------------------===//

/// Returns the number of this argument.
unsigned BlockArgument::getArgNumber() {
  // Arguments are not stored in place, so we have to find it within the list.
  auto argList = getOwner()->getArguments();
  return std::distance(argList.begin(), llvm::find(argList, this));
}

//===----------------------------------------------------------------------===//
// Block
//===----------------------------------------------------------------------===//

Block::~Block() {
  assert(!verifyInstOrder() && "Expected valid operation ordering.");
  clear();
  llvm::DeleteContainerPointers(arguments);
}

Region *Block::getParent() { return parentValidInstOrderPair.getPointer(); }

/// Returns the closest surrounding operation that contains this block or
/// nullptr if this block is unlinked.
Operation *Block::getParentOp() {
  return getParent() ? getParent()->getParentOp() : nullptr;
}

/// Return if this block is the entry block in the parent region.
bool Block::isEntryBlock() { return this == &getParent()->front(); }

/// Insert this block (which must not already be in a region) right before the
/// specified block.
void Block::insertBefore(Block *block) {
  assert(!getParent() && "already inserted into a block!");
  assert(block->getParent() && "cannot insert before a block without a parent");
  block->getParent()->getBlocks().insert(Region::iterator(block), this);
}

/// Unlink this Block from its parent Region and delete it.
void Block::erase() {
  assert(getParent() && "Block has no parent");
  getParent()->getBlocks().erase(this);
}

/// Returns 'op' if 'op' lies in this block, or otherwise finds the
/// ancestor operation of 'op' that lies in this block. Returns nullptr if
/// the latter fails.
Operation *Block::findAncestorInstInBlock(Operation &op) {
  // Traverse up the operation hierarchy starting from the owner of operand to
  // find the ancestor operation that resides in the block of 'forInst'.
  auto *currInst = &op;
  while (currInst->getBlock() != this) {
    currInst = currInst->getParentOp();
    if (!currInst)
      return nullptr;
  }
  return currInst;
}

/// This drops all operand uses from operations within this block, which is
/// an essential step in breaking cyclic dependences between references when
/// they are to be deleted.
void Block::dropAllReferences() {
  for (Operation &i : *this)
    i.dropAllReferences();
}

void Block::dropAllDefinedValueUses() {
  for (auto *arg : getArguments())
    arg->dropAllUses();
  for (auto &op : *this)
    op.dropAllDefinedValueUses();
  dropAllUses();
}

/// Returns true if the ordering of the child operations is valid, false
/// otherwise.
bool Block::isInstOrderValid() { return parentValidInstOrderPair.getInt(); }

/// Invalidates the current ordering of operations.
void Block::invalidateInstOrder() {
  // Validate the current ordering.
  assert(!verifyInstOrder());
  parentValidInstOrderPair.setInt(false);
}

/// Verifies the current ordering of child operations. Returns false if the
/// order is valid, true otherwise.
bool Block::verifyInstOrder() {
  // The order is already known to be invalid.
  if (!isInstOrderValid())
    return false;
  // The order is valid if there are less than 2 operations.
  if (operations.empty() || std::next(operations.begin()) == operations.end())
    return false;

  Operation *prev = nullptr;
  for (auto &i : *this) {
    // The previous operation must have a smaller order index than the next as
    // it appears earlier in the list.
    if (prev && prev->orderIndex >= i.orderIndex)
      return true;
    prev = &i;
  }
  return false;
}

/// Recomputes the ordering of child operations within the block.
void Block::recomputeInstOrder() {
  parentValidInstOrderPair.setInt(true);

  // TODO(riverriddle) Have non-congruent indices to reduce the number of times
  // an insert invalidates the list.
  unsigned orderIndex = 0;
  for (auto &op : *this)
    op.orderIndex = orderIndex++;
}

//===----------------------------------------------------------------------===//
// Argument list management.
//===----------------------------------------------------------------------===//

BlockArgument *Block::addArgument(Type type) {
  auto *arg = new BlockArgument(type, this);
  arguments.push_back(arg);
  return arg;
}

/// Add one argument to the argument list for each type specified in the list.
auto Block::addArguments(ArrayRef<Type> types)
    -> llvm::iterator_range<args_iterator> {
  arguments.reserve(arguments.size() + types.size());
  auto initialSize = arguments.size();
  for (auto type : types) {
    addArgument(type);
  }
  return {arguments.data() + initialSize, arguments.data() + arguments.size()};
}

void Block::eraseArgument(unsigned index, bool updatePredTerms) {
  assert(index < arguments.size());

  // Delete the argument.
  delete arguments[index];
  arguments.erase(arguments.begin() + index);

  // If we aren't updating predecessors, there is nothing left to do.
  if (!updatePredTerms)
    return;

  // Erase this argument from each of the predecessor's terminator.
  for (auto predIt = pred_begin(), predE = pred_end(); predIt != predE;
       ++predIt) {
    auto *predTerminator = (*predIt)->getTerminator();
    predTerminator->eraseSuccessorOperand(predIt.getSuccessorIndex(), index);
  }
}

//===----------------------------------------------------------------------===//
// Terminator management
//===----------------------------------------------------------------------===//

/// Get the terminator operation of this block. This function asserts that
/// the block has a valid terminator operation.
Operation *Block::getTerminator() {
  assert(!empty() && !back().isKnownNonTerminator());
  return &back();
}

/// Return true if this block has no predecessors.
bool Block::hasNoPredecessors() { return pred_begin() == pred_end(); }

// Indexed successor access.
unsigned Block::getNumSuccessors() {
  return empty() ? 0 : back().getNumSuccessors();
}

Block *Block::getSuccessor(unsigned i) {
  assert(i < getNumSuccessors());
  return getTerminator()->getSuccessor(i);
}

/// If this block has exactly one predecessor, return it.  Otherwise, return
/// null.
///
/// Note that multiple edges from a single block (e.g. if you have a cond
/// branch with the same block as the true/false destinations) is not
/// considered to be a single predecessor.
Block *Block::getSinglePredecessor() {
  auto it = pred_begin();
  if (it == pred_end())
    return nullptr;
  auto *firstPred = *it;
  ++it;
  return it == pred_end() ? firstPred : nullptr;
}

//===----------------------------------------------------------------------===//
// Other
//===----------------------------------------------------------------------===//

/// Split the block into two blocks before the specified operation or
/// iterator.
///
/// Note that all operations BEFORE the specified iterator stay as part of
/// the original basic block, and the rest of the operations in the original
/// block are moved to the new block, including the old terminator.  The
/// original block is left without a terminator.
///
/// The newly formed Block is returned, and the specified iterator is
/// invalidated.
Block *Block::splitBlock(iterator splitBefore) {
  // Start by creating a new basic block, and insert it immediate after this
  // one in the containing region.
  auto newBB = new Block();
  getParent()->getBlocks().insert(std::next(Region::iterator(this)), newBB);

  // Move all of the operations from the split point to the end of the region
  // into the new block.
  newBB->getOperations().splice(newBB->end(), getOperations(), splitBefore,
                                end());
  return newBB;
}

//===----------------------------------------------------------------------===//
// Predecessors
//===----------------------------------------------------------------------===//

Block *PredecessorIterator::unwrap(BlockOperand &value) {
  return value.getOwner()->getBlock();
}

/// Get the successor number in the predecessor terminator.
unsigned PredecessorIterator::getSuccessorIndex() const {
  return I->getOperandNumber();
}
<|endoftext|>


<commit_before>/*
    This file is part of SFUI (by Robin RUAUX).

    SFUI 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.

    SFUI 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 SFUI.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "Label.hpp"

#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Window/OpenGL.hpp>

#include "ResourceManager.hpp"

namespace sf
{
    namespace ui
    {

        Label::Label(const Unicode::Text& caption)
            :   Widget(),
                mCaption(caption, Font::GetDefaultFont(), 30.f)
        {
            LoadTemplate("BI_Label");
        }

        void    Label::SetText(const Unicode::Text& caption)
        {
            mCaption.SetText(caption);

            const FloatRect& rect = mCaption.GetRect();

            if (rect.GetWidth() > GetWidth())
                SetWidth(rect.GetWidth());
            if (rect.GetHeight() > GetHeight())
                SetHeight(rect.GetHeight());
        }

        const Unicode::Text&    Label::GetText() const
        {
            return mCaption.GetText();
        }

        void    Label::SetFont(const Font& font)
        {
            mCaption.SetFont(font);
        }

        const Font& Label::GetFont() const
        {
            return mCaption.GetFont();
        }

        void    Label::SetTextSize(float size)
        {
            mCaption.SetSize(size);
        }

        float   Label::GetTextSize() const
        {
            return mCaption.GetSize();
        }

        void    Label::SetTextColor(const Color& color)
        {
            mCaption.SetColor(color);
        }

        const Color&    Label::GetTextColor() const
        {
            return mCaption.GetColor();
        }

        const String&   Label::GetString() const
        {
            return mCaption;
        }

        void    Label::LoadTemplate(const std::string& nameTpl)
        {
            Widget::LoadTemplate(nameTpl);

            ResourceManager* rm = ResourceManager::Get();
            TemplateProperties& properties = rm->GetTemplate(nameTpl);

            SetTextSize(rm->GetValue(properties["textSize"], GetTextSize()));
            SetTextColor(rm->GetColorValue(properties["textColor"], GetTextColor()));

            if (properties["font"] != "")
            {
                SetFont(*rm->GetFont(properties["font"], GetTextSize()));
            }

            if (properties["textSize"] != "")
            {
                const FloatRect& rect = mCaption.GetRect();

                if (properties["width"] == "")
                    SetWidth(rect.GetWidth());
                if (properties["height"] == "")
                    SetHeight(rect.GetHeight());
            }
        }

        void    Label::OnPaint(RenderTarget& target) const
        {
            Widget::OnPaint(target);

            const Unicode::UTF32String& Text = mCaption.GetText();
            const Font& font = mCaption.GetFont();

            if (Text.empty())
                return;

            float CharSize =  static_cast<float>(font.GetCharacterSize());
            float Factor   = mCaption.GetSize() / CharSize;
            const Color& color = mCaption.GetColor();

            glColor4ub(color.r, color.g, color.b, color.a);
            glScalef(Factor, Factor, 1.f);

            font.GetImage().Bind();

            float X = 0.f;
            float Y = CharSize;

            glBegin(GL_QUADS);

            // Adapted from sf::String (originally coded by Laurent Gomila - SFML)
            for (std::size_t i = 0; i < Text.size(); ++i)
            {
                Uint32           CurChar  = Text[i];
                const Glyph&     CurGlyph = font.GetGlyph(CurChar);
                int              Advance  = CurGlyph.Advance;
                const IntRect&   Rect     = CurGlyph.Rectangle;
                const FloatRect& Coord    = CurGlyph.TexCoords;

                switch (CurChar)
                {
                    case L' ' :  X += Advance;                  continue;
                    case L'\n' : Y += CharSize; X = 0;          continue;
                    case L'\t' : X += font.GetGlyph(' ').Advance * 4;   continue;
                    case L'\v' : Y += CharSize * 4;             continue;
                }

                glTexCoord2f(Coord.Left,  Coord.Top);    glVertex2f(X + Rect.Left, Y + Rect.Top);
                glTexCoord2f(Coord.Left,  Coord.Bottom); glVertex2f(X + Rect.Left, Y + Rect.Bottom);
                glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + Rect.Right, Y + Rect.Bottom);
                glTexCoord2f(Coord.Right, Coord.Top);    glVertex2f(X + Rect.Right, Y + Rect.Top);

                X += Advance;
            }
            glEnd();
        }
    }
}
<commit_msg>Fixed a bug with TextInput cursor visibility.<commit_after>/*
    This file is part of SFUI (by Robin RUAUX).

    SFUI 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.

    SFUI 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 SFUI.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "Label.hpp"

#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Window/OpenGL.hpp>

#include "ResourceManager.hpp"

namespace sf
{
    namespace ui
    {

        Label::Label(const Unicode::Text& caption)
            :   Widget(),
                mCaption(caption, Font::GetDefaultFont(), 30.f)
        {
            LoadTemplate("BI_Label");
        }

        void    Label::SetText(const Unicode::Text& caption)
        {
            mCaption.SetText(caption);

            const FloatRect& rect = mCaption.GetRect();

            if (rect.GetWidth() > GetWidth())
                SetWidth(rect.GetWidth());
            if (rect.GetHeight() > GetHeight())
                SetHeight(rect.GetHeight());
        }

        const Unicode::Text&    Label::GetText() const
        {
            return mCaption.GetText();
        }

        void    Label::SetFont(const Font& font)
        {
            mCaption.SetFont(font);
        }

        const Font& Label::GetFont() const
        {
            return mCaption.GetFont();
        }

        void    Label::SetTextSize(float size)
        {
            mCaption.SetSize(size);
        }

        float   Label::GetTextSize() const
        {
            return mCaption.GetSize();
        }

        void    Label::SetTextColor(const Color& color)
        {
            mCaption.SetColor(color);
        }

        const Color&    Label::GetTextColor() const
        {
            return mCaption.GetColor();
        }

        const String&   Label::GetString() const
        {
            return mCaption;
        }

        void    Label::LoadTemplate(const std::string& nameTpl)
        {
            Widget::LoadTemplate(nameTpl);

            ResourceManager* rm = ResourceManager::Get();
            TemplateProperties& properties = rm->GetTemplate(nameTpl);

            SetTextSize(rm->GetValue(properties["textSize"], GetTextSize()));
            SetTextColor(rm->GetColorValue(properties["textColor"], GetTextColor()));

            if (properties["font"] != "")
            {
                SetFont(*rm->GetFont(properties["font"], GetTextSize()));
            }

            if (properties["textSize"] != "")
            {
                const FloatRect& rect = mCaption.GetRect();

                if (properties["width"] == "")
                    SetWidth(rect.GetWidth());
                if (properties["height"] == "")
                    SetHeight(rect.GetHeight());
            }
        }

        void    Label::OnPaint(RenderTarget& target) const
        {
            Widget::OnPaint(target);

            const Unicode::UTF32String& Text = mCaption.GetText();
            const Font& font = mCaption.GetFont();

            float CharSize =  static_cast<float>(font.GetCharacterSize());
            float Factor   = mCaption.GetSize() / CharSize;
            const Color& color = mCaption.GetColor();

            glColor4ub(color.r, color.g, color.b, color.a);
            glScalef(Factor, Factor, 1.f);

            font.GetImage().Bind();

            float X = 0.f;
            float Y = CharSize;

            glBegin(GL_QUADS);

            // Adapted from sf::String (originally coded by Laurent Gomila - SFML)
            for (std::size_t i = 0; i < Text.size(); ++i)
            {
                Uint32           CurChar  = Text[i];
                const Glyph&     CurGlyph = font.GetGlyph(CurChar);
                int              Advance  = CurGlyph.Advance;
                const IntRect&   Rect     = CurGlyph.Rectangle;
                const FloatRect& Coord    = CurGlyph.TexCoords;

                switch (CurChar)
                {
                    case L' ' :  X += Advance;                  continue;
                    case L'\n' : Y += CharSize; X = 0;          continue;
                    case L'\t' : X += font.GetGlyph(' ').Advance * 4;   continue;
                    case L'\v' : Y += CharSize * 4;             continue;
                }

                glTexCoord2f(Coord.Left,  Coord.Top);    glVertex2f(X + Rect.Left, Y + Rect.Top);
                glTexCoord2f(Coord.Left,  Coord.Bottom); glVertex2f(X + Rect.Left, Y + Rect.Bottom);
                glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + Rect.Right, Y + Rect.Bottom);
                glTexCoord2f(Coord.Right, Coord.Top);    glVertex2f(X + Rect.Right, Y + Rect.Top);

                X += Advance;
            }
            glEnd();
        }
    }
}
<|endoftext|>