<commit_before>/*
 * Copyright © 2012 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "brw_fs.h"
#include "brw_cfg.h"

/** @file brw_fs_cse.cpp
 *
 * Support for local common subexpression elimination.
 *
 * See Muchnick's Advanced Compiler Design and Implementation, section
 * 13.1 (p378).
 */

namespace {
struct aeb_entry : public exec_node {
   /** The instruction that generates the expression value. */
   fs_inst *generator;

   /** The temporary where the value is stored. */
   fs_reg tmp;
};
}

static bool
is_copy_payload(const fs_inst *inst)
{
   const int reg = inst->src[0].reg;
   if (inst->src[0].reg_offset != 0)
      return false;

   for (int i = 1; i < inst->sources; i++) {
      if (inst->src[i].reg != reg ||
          inst->src[i].reg_offset != i) {
         return false;
      }
   }
   return true;
}

static bool
is_expression(const fs_inst *const inst)
{
   switch (inst->opcode) {
   case BRW_OPCODE_MOV:
   case BRW_OPCODE_SEL:
   case BRW_OPCODE_NOT:
   case BRW_OPCODE_AND:
   case BRW_OPCODE_OR:
   case BRW_OPCODE_XOR:
   case BRW_OPCODE_SHR:
   case BRW_OPCODE_SHL:
   case BRW_OPCODE_ASR:
   case BRW_OPCODE_CMP:
   case BRW_OPCODE_CMPN:
   case BRW_OPCODE_ADD:
   case BRW_OPCODE_MUL:
   case BRW_OPCODE_FRC:
   case BRW_OPCODE_RNDU:
   case BRW_OPCODE_RNDD:
   case BRW_OPCODE_RNDE:
   case BRW_OPCODE_RNDZ:
   case BRW_OPCODE_LINE:
   case BRW_OPCODE_PLN:
   case BRW_OPCODE_MAD:
   case BRW_OPCODE_LRP:
   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD:
   case FS_OPCODE_CINTERP:
   case FS_OPCODE_LINTERP:
   case SHADER_OPCODE_FIND_LIVE_CHANNEL:
   case SHADER_OPCODE_BROADCAST:
      return true;
   case SHADER_OPCODE_RCP:
   case SHADER_OPCODE_RSQ:
   case SHADER_OPCODE_SQRT:
   case SHADER_OPCODE_EXP2:
   case SHADER_OPCODE_LOG2:
   case SHADER_OPCODE_POW:
   case SHADER_OPCODE_INT_QUOTIENT:
   case SHADER_OPCODE_INT_REMAINDER:
   case SHADER_OPCODE_SIN:
   case SHADER_OPCODE_COS:
      return inst->mlen < 2;
   case SHADER_OPCODE_LOAD_PAYLOAD:
      return !is_copy_payload(inst);
   default:
      return inst->is_send_from_grf() && !inst->has_side_effects();
   }
}

static bool
operands_match(const fs_inst *a, const fs_inst *b, bool *negate)
{
   fs_reg *xs = a->src;
   fs_reg *ys = b->src;

   if (a->opcode == BRW_OPCODE_MAD) {
      return xs[0].equals(ys[0]) &&
             ((xs[1].equals(ys[1]) && xs[2].equals(ys[2])) ||
              (xs[2].equals(ys[1]) && xs[1].equals(ys[2])));
   } else if (a->opcode == BRW_OPCODE_MUL && a->dst.type == BRW_REGISTER_TYPE_F) {
      bool xs0_negate = xs[0].negate;
      bool xs1_negate = xs[1].file == IMM ? xs[1].fixed_hw_reg.dw1.f < 0.0f
                                          : xs[1].negate;
      bool ys0_negate = ys[0].negate;
      bool ys1_negate = ys[1].file == IMM ? ys[1].fixed_hw_reg.dw1.f < 0.0f
                                          : ys[1].negate;
      float xs1_imm = xs[1].fixed_hw_reg.dw1.f;
      float ys1_imm = ys[1].fixed_hw_reg.dw1.f;

      xs[0].negate = false;
      xs[1].negate = false;
      ys[0].negate = false;
      ys[1].negate = false;
      xs[1].fixed_hw_reg.dw1.f = fabsf(xs[1].fixed_hw_reg.dw1.f);
      ys[1].fixed_hw_reg.dw1.f = fabsf(ys[1].fixed_hw_reg.dw1.f);

      bool ret = (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
                 (xs[1].equals(ys[0]) && xs[0].equals(ys[1]));

      xs[0].negate = xs0_negate;
      xs[1].negate = xs[1].file == IMM ? false : xs1_negate;
      ys[0].negate = ys0_negate;
      ys[1].negate = ys[1].file == IMM ? false : ys1_negate;
      xs[1].fixed_hw_reg.dw1.f = xs1_imm;
      ys[1].fixed_hw_reg.dw1.f = ys1_imm;

      *negate = (xs0_negate != xs1_negate) != (ys0_negate != ys1_negate);
      return ret;
   } else if (!a->is_commutative()) {
      bool match = true;
      for (int i = 0; i < a->sources; i++) {
         if (!xs[i].equals(ys[i])) {
            match = false;
            break;
         }
      }
      return match;
   } else {
      return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
             (xs[1].equals(ys[0]) && xs[0].equals(ys[1]));
   }
}

static bool
instructions_match(fs_inst *a, fs_inst *b, bool *negate)
{
   return a->opcode == b->opcode &&
          a->saturate == b->saturate &&
          a->predicate == b->predicate &&
          a->predicate_inverse == b->predicate_inverse &&
          a->conditional_mod == b->conditional_mod &&
          a->dst.type == b->dst.type &&
          a->sources == b->sources &&
          (a->is_tex() ? (a->offset == b->offset &&
                          a->mlen == b->mlen &&
                          a->regs_written == b->regs_written &&
                          a->base_mrf == b->base_mrf &&
                          a->eot == b->eot &&
                          a->header_present == b->header_present &&
                          a->shadow_compare == b->shadow_compare)
                       : true) &&
          operands_match(a, b, negate);
}

bool
fs_visitor::opt_cse_local(bblock_t *block)
{
   bool progress = false;
   exec_list aeb;

   void *cse_ctx = ralloc_context(NULL);

   int ip = block->start_ip;
   foreach_inst_in_block(fs_inst, inst, block) {
      /* Skip some cases. */
      if (is_expression(inst) && !inst->is_partial_write() &&
          (inst->dst.file != HW_REG || inst->dst.is_null()))
      {
         bool found = false;
         bool negate = false;

         foreach_in_list_use_after(aeb_entry, entry, &aeb) {
            /* Match current instruction's expression against those in AEB. */
            if (!(entry->generator->dst.is_null() && !inst->dst.is_null()) &&
                instructions_match(inst, entry->generator, &negate)) {
               found = true;
               progress = true;
               break;
            }
         }

         if (!found) {
            if (inst->opcode != BRW_OPCODE_MOV ||
                (inst->opcode == BRW_OPCODE_MOV &&
                 inst->src[0].file == IMM &&
                 inst->src[0].type == BRW_REGISTER_TYPE_VF)) {
               /* Our first sighting of this expression.  Create an entry. */
               aeb_entry *entry = ralloc(cse_ctx, aeb_entry);
               entry->tmp = reg_undef;
               entry->generator = inst;
               aeb.push_tail(entry);
            }
         } else {
            /* This is at least our second sighting of this expression.
             * If we don't have a temporary already, make one.
             */
            bool no_existing_temp = entry->tmp.file == BAD_FILE;
            if (no_existing_temp && !entry->generator->dst.is_null()) {
               int written = entry->generator->regs_written;
               int dst_width = entry->generator->dst.width / 8;
               assert(written % dst_width == 0);

               fs_reg orig_dst = entry->generator->dst;
               fs_reg tmp = fs_reg(GRF, alloc.allocate(written),
                                   orig_dst.type, orig_dst.width);
               entry->tmp = tmp;
               entry->generator->dst = tmp;

               fs_inst *copy;
               if (written > dst_width) {
                  fs_reg *sources = ralloc_array(mem_ctx, fs_reg, written / dst_width);
                  for (int i = 0; i < written / dst_width; i++)
                     sources[i] = offset(tmp, i);
                  copy = LOAD_PAYLOAD(orig_dst, sources, written / dst_width);
               } else {
                  copy = MOV(orig_dst, tmp);
                  copy->force_writemask_all =
                     entry->generator->force_writemask_all;
               }
               entry->generator->insert_after(block, copy);
            }

            /* dest <- temp */
            if (!inst->dst.is_null()) {
               int written = inst->regs_written;
               int dst_width = inst->dst.width / 8;
               assert(written == entry->generator->regs_written);
               assert(dst_width == entry->generator->dst.width / 8);
               assert(inst->dst.type == entry->tmp.type);
               fs_reg dst = inst->dst;
               fs_reg tmp = entry->tmp;
               fs_inst *copy;
               if (written > dst_width) {
                  fs_reg *sources = ralloc_array(mem_ctx, fs_reg, written / dst_width);
                  for (int i = 0; i < written / dst_width; i++)
                     sources[i] = offset(tmp, i);
                  copy = LOAD_PAYLOAD(dst, sources, written / dst_width);
               } else {
                  copy = MOV(dst, tmp);
                  copy->force_writemask_all = inst->force_writemask_all;
                  copy->src[0].negate = negate;
               }
               inst->insert_before(block, copy);
            }

            /* Set our iterator so that next time through the loop inst->next
             * will get the instruction in the basic block after the one we've
             * removed.
             */
            fs_inst *prev = (fs_inst *)inst->prev;

            inst->remove(block);
            inst = prev;
         }
      }

      foreach_in_list_safe(aeb_entry, entry, &aeb) {
         /* Kill all AEB entries that write a different value to or read from
          * the flag register if we just wrote it.
          */
         if (inst->writes_flag()) {
            bool negate; /* dummy */
            if (entry->generator->reads_flag() ||
                (entry->generator->writes_flag() &&
                 !instructions_match(inst, entry->generator, &negate))) {
               entry->remove();
               ralloc_free(entry);
               continue;
            }
         }

         for (int i = 0; i < entry->generator->sources; i++) {
            fs_reg *src_reg = &entry->generator->src[i];

            /* Kill all AEB entries that use the destination we just
             * overwrote.
             */
            if (inst->overwrites_reg(entry->generator->src[i])) {
               entry->remove();
               ralloc_free(entry);
               break;
            }

            /* Kill any AEB entries using registers that don't get reused any
             * more -- a sure sign they'll fail operands_match().
             */
            if (src_reg->file == GRF && virtual_grf_end[src_reg->reg] < ip) {
               entry->remove();
               ralloc_free(entry);
               break;
            }
         }
      }

      ip++;
   }

   ralloc_free(cse_ctx);

   return progress;
}

bool
fs_visitor::opt_cse()
{
   bool progress = false;

   calculate_live_intervals();

   foreach_block (block, cfg) {
      progress = opt_cse_local(block) || progress;
   }

   if (progress)
      invalidate_live_intervals();

   return progress;
}
<commit_msg>i965/fs_cse: Factor out code to create copy instructions<commit_after>/*
 * Copyright © 2012 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "brw_fs.h"
#include "brw_cfg.h"

/** @file brw_fs_cse.cpp
 *
 * Support for local common subexpression elimination.
 *
 * See Muchnick's Advanced Compiler Design and Implementation, section
 * 13.1 (p378).
 */

namespace {
struct aeb_entry : public exec_node {
   /** The instruction that generates the expression value. */
   fs_inst *generator;

   /** The temporary where the value is stored. */
   fs_reg tmp;
};
}

static bool
is_copy_payload(const fs_inst *inst)
{
   const int reg = inst->src[0].reg;
   if (inst->src[0].reg_offset != 0)
      return false;

   for (int i = 1; i < inst->sources; i++) {
      if (inst->src[i].reg != reg ||
          inst->src[i].reg_offset != i) {
         return false;
      }
   }
   return true;
}

static bool
is_expression(const fs_inst *const inst)
{
   switch (inst->opcode) {
   case BRW_OPCODE_MOV:
   case BRW_OPCODE_SEL:
   case BRW_OPCODE_NOT:
   case BRW_OPCODE_AND:
   case BRW_OPCODE_OR:
   case BRW_OPCODE_XOR:
   case BRW_OPCODE_SHR:
   case BRW_OPCODE_SHL:
   case BRW_OPCODE_ASR:
   case BRW_OPCODE_CMP:
   case BRW_OPCODE_CMPN:
   case BRW_OPCODE_ADD:
   case BRW_OPCODE_MUL:
   case BRW_OPCODE_FRC:
   case BRW_OPCODE_RNDU:
   case BRW_OPCODE_RNDD:
   case BRW_OPCODE_RNDE:
   case BRW_OPCODE_RNDZ:
   case BRW_OPCODE_LINE:
   case BRW_OPCODE_PLN:
   case BRW_OPCODE_MAD:
   case BRW_OPCODE_LRP:
   case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
   case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD:
   case FS_OPCODE_CINTERP:
   case FS_OPCODE_LINTERP:
   case SHADER_OPCODE_FIND_LIVE_CHANNEL:
   case SHADER_OPCODE_BROADCAST:
      return true;
   case SHADER_OPCODE_RCP:
   case SHADER_OPCODE_RSQ:
   case SHADER_OPCODE_SQRT:
   case SHADER_OPCODE_EXP2:
   case SHADER_OPCODE_LOG2:
   case SHADER_OPCODE_POW:
   case SHADER_OPCODE_INT_QUOTIENT:
   case SHADER_OPCODE_INT_REMAINDER:
   case SHADER_OPCODE_SIN:
   case SHADER_OPCODE_COS:
      return inst->mlen < 2;
   case SHADER_OPCODE_LOAD_PAYLOAD:
      return !is_copy_payload(inst);
   default:
      return inst->is_send_from_grf() && !inst->has_side_effects();
   }
}

static bool
operands_match(const fs_inst *a, const fs_inst *b, bool *negate)
{
   fs_reg *xs = a->src;
   fs_reg *ys = b->src;

   if (a->opcode == BRW_OPCODE_MAD) {
      return xs[0].equals(ys[0]) &&
             ((xs[1].equals(ys[1]) && xs[2].equals(ys[2])) ||
              (xs[2].equals(ys[1]) && xs[1].equals(ys[2])));
   } else if (a->opcode == BRW_OPCODE_MUL && a->dst.type == BRW_REGISTER_TYPE_F) {
      bool xs0_negate = xs[0].negate;
      bool xs1_negate = xs[1].file == IMM ? xs[1].fixed_hw_reg.dw1.f < 0.0f
                                          : xs[1].negate;
      bool ys0_negate = ys[0].negate;
      bool ys1_negate = ys[1].file == IMM ? ys[1].fixed_hw_reg.dw1.f < 0.0f
                                          : ys[1].negate;
      float xs1_imm = xs[1].fixed_hw_reg.dw1.f;
      float ys1_imm = ys[1].fixed_hw_reg.dw1.f;

      xs[0].negate = false;
      xs[1].negate = false;
      ys[0].negate = false;
      ys[1].negate = false;
      xs[1].fixed_hw_reg.dw1.f = fabsf(xs[1].fixed_hw_reg.dw1.f);
      ys[1].fixed_hw_reg.dw1.f = fabsf(ys[1].fixed_hw_reg.dw1.f);

      bool ret = (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
                 (xs[1].equals(ys[0]) && xs[0].equals(ys[1]));

      xs[0].negate = xs0_negate;
      xs[1].negate = xs[1].file == IMM ? false : xs1_negate;
      ys[0].negate = ys0_negate;
      ys[1].negate = ys[1].file == IMM ? false : ys1_negate;
      xs[1].fixed_hw_reg.dw1.f = xs1_imm;
      ys[1].fixed_hw_reg.dw1.f = ys1_imm;

      *negate = (xs0_negate != xs1_negate) != (ys0_negate != ys1_negate);
      return ret;
   } else if (!a->is_commutative()) {
      bool match = true;
      for (int i = 0; i < a->sources; i++) {
         if (!xs[i].equals(ys[i])) {
            match = false;
            break;
         }
      }
      return match;
   } else {
      return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) ||
             (xs[1].equals(ys[0]) && xs[0].equals(ys[1]));
   }
}

static bool
instructions_match(fs_inst *a, fs_inst *b, bool *negate)
{
   return a->opcode == b->opcode &&
          a->saturate == b->saturate &&
          a->predicate == b->predicate &&
          a->predicate_inverse == b->predicate_inverse &&
          a->conditional_mod == b->conditional_mod &&
          a->dst.type == b->dst.type &&
          a->sources == b->sources &&
          (a->is_tex() ? (a->offset == b->offset &&
                          a->mlen == b->mlen &&
                          a->regs_written == b->regs_written &&
                          a->base_mrf == b->base_mrf &&
                          a->eot == b->eot &&
                          a->header_present == b->header_present &&
                          a->shadow_compare == b->shadow_compare)
                       : true) &&
          operands_match(a, b, negate);
}

static fs_inst *
create_copy_instr(fs_visitor *v, fs_inst *inst, fs_reg src, bool negate)
{
   int written = inst->regs_written;
   int dst_width = inst->dst.width / 8;
   fs_reg dst = inst->dst;
   fs_inst *copy;

   if (written > dst_width) {
      fs_reg *sources = ralloc_array(v->mem_ctx, fs_reg, written / dst_width);
      for (int i = 0; i < written / dst_width; i++)
         sources[i] = offset(src, i);
      copy = v->LOAD_PAYLOAD(dst, sources, written / dst_width);
   } else {
      copy = v->MOV(dst, src);
      copy->force_writemask_all = inst->force_writemask_all;
      copy->src[0].negate = negate;
   }
   assert(copy->regs_written == written);

   return copy;
}

bool
fs_visitor::opt_cse_local(bblock_t *block)
{
   bool progress = false;
   exec_list aeb;

   void *cse_ctx = ralloc_context(NULL);

   int ip = block->start_ip;
   foreach_inst_in_block(fs_inst, inst, block) {
      /* Skip some cases. */
      if (is_expression(inst) && !inst->is_partial_write() &&
          (inst->dst.file != HW_REG || inst->dst.is_null()))
      {
         bool found = false;
         bool negate = false;

         foreach_in_list_use_after(aeb_entry, entry, &aeb) {
            /* Match current instruction's expression against those in AEB. */
            if (!(entry->generator->dst.is_null() && !inst->dst.is_null()) &&
                instructions_match(inst, entry->generator, &negate)) {
               found = true;
               progress = true;
               break;
            }
         }

         if (!found) {
            if (inst->opcode != BRW_OPCODE_MOV ||
                (inst->opcode == BRW_OPCODE_MOV &&
                 inst->src[0].file == IMM &&
                 inst->src[0].type == BRW_REGISTER_TYPE_VF)) {
               /* Our first sighting of this expression.  Create an entry. */
               aeb_entry *entry = ralloc(cse_ctx, aeb_entry);
               entry->tmp = reg_undef;
               entry->generator = inst;
               aeb.push_tail(entry);
            }
         } else {
            /* This is at least our second sighting of this expression.
             * If we don't have a temporary already, make one.
             */
            bool no_existing_temp = entry->tmp.file == BAD_FILE;
            if (no_existing_temp && !entry->generator->dst.is_null()) {
               int written = entry->generator->regs_written;
               assert((written * 8) % entry->generator->dst.width == 0);

               entry->tmp = fs_reg(GRF, alloc.allocate(written),
                                   entry->generator->dst.type,
                                   entry->generator->dst.width);

               fs_inst *copy = create_copy_instr(this, entry->generator,
                                                 entry->tmp, false);
               entry->generator->insert_after(block, copy);

               entry->generator->dst = entry->tmp;
            }

            /* dest <- temp */
            if (!inst->dst.is_null()) {
               assert(inst->regs_written == entry->generator->regs_written);
               assert(inst->dst.width == entry->generator->dst.width);
               assert(inst->dst.type == entry->tmp.type);

               fs_inst *copy = create_copy_instr(this, inst,
                                                 entry->tmp, negate);
               inst->insert_before(block, copy);
            }

            /* Set our iterator so that next time through the loop inst->next
             * will get the instruction in the basic block after the one we've
             * removed.
             */
            fs_inst *prev = (fs_inst *)inst->prev;

            inst->remove(block);
            inst = prev;
         }
      }

      foreach_in_list_safe(aeb_entry, entry, &aeb) {
         /* Kill all AEB entries that write a different value to or read from
          * the flag register if we just wrote it.
          */
         if (inst->writes_flag()) {
            bool negate; /* dummy */
            if (entry->generator->reads_flag() ||
                (entry->generator->writes_flag() &&
                 !instructions_match(inst, entry->generator, &negate))) {
               entry->remove();
               ralloc_free(entry);
               continue;
            }
         }

         for (int i = 0; i < entry->generator->sources; i++) {
            fs_reg *src_reg = &entry->generator->src[i];

            /* Kill all AEB entries that use the destination we just
             * overwrote.
             */
            if (inst->overwrites_reg(entry->generator->src[i])) {
               entry->remove();
               ralloc_free(entry);
               break;
            }

            /* Kill any AEB entries using registers that don't get reused any
             * more -- a sure sign they'll fail operands_match().
             */
            if (src_reg->file == GRF && virtual_grf_end[src_reg->reg] < ip) {
               entry->remove();
               ralloc_free(entry);
               break;
            }
         }
      }

      ip++;
   }

   ralloc_free(cse_ctx);

   return progress;
}

bool
fs_visitor::opt_cse()
{
   bool progress = false;

   calculate_live_intervals();

   foreach_block (block, cfg) {
      progress = opt_cse_local(block) || progress;
   }

   if (progress)
      invalidate_live_intervals();

   return progress;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <ctime>

#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_local et.al
#include "libtorrent/socket_io.hpp" // for hash_address
#include "libtorrent/random.hpp" // for random

namespace libtorrent { namespace dht
{

// returns the distance between the two nodes
// using the kademlia XOR-metric
node_id distance(node_id const& n1, node_id const& n2)
{
	node_id ret;
	node_id::iterator k = ret.begin();
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, ++k)
	{
		*k = *i ^ *j;
	}
	return ret;
}

// returns true if: distance(n1, ref) < distance(n2, ref)
bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)
{
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)
	{
		boost::uint8_t lhs = (*i ^ *k);
		boost::uint8_t rhs = (*j ^ *k);
		if (lhs < rhs) return true;
		if (lhs > rhs) return false;
	}
	return false;
}

// returns n in: 2^n <= distance(n1, n2) < 2^(n+1)
// useful for finding out which bucket a node belongs to
int distance_exp(node_id const& n1, node_id const& n2)
{
	int byte = node_id::size - 1;
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, --byte)
	{
		TORRENT_ASSERT(byte >= 0);
		boost::uint8_t t = *i ^ *j;
		if (t == 0) continue;
		// we have found the first non-zero byte
		// return the bit-number of the first bit
		// that differs
		int bit = byte * 8;
		for (int b = 7; b >= 0; --b)
			if (t >= (1 << b)) return bit + b;
		return bit;
	}

	return 0;
}

struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__;

node_id generate_id_impl(address const& ip_, boost::uint32_t r)
{
	boost::uint8_t* ip = 0;

	const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff };
	const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
	boost::uint8_t const* mask = 0;
	int num_octets = 0;

	address_v4::bytes_type b4;
#if TORRENT_USE_IPV6
	address_v6::bytes_type b6;
	if (ip_.is_v6())
	{
		b6 = ip_.to_v6().to_bytes();
		ip = &b6[0];
		num_octets = 8;
		mask = v6mask;
	}
	else
#endif
	{
		b4 = ip_.to_v4().to_bytes();
		ip = &b4[0];
		num_octets = 4;
		mask = v4mask;
	}

	for (int i = 0; i < num_octets; ++i)
		ip[i] &= mask[i];

	hasher h;
	h.update((char*)ip, num_octets);
	boost::uint8_t rand = r & 0x7;
	h.update((char*)&r, 1);
	node_id id = h.final();
	for (int i = 4; i < 19; ++i) id[i] = random();
	id[19] = r;

	return id;
}

node_id generate_random_id()
{
	char r[20];
	for (int i = 0; i < 20; ++i) r[i] = random();
	return hasher(r, 20).final();
}

// verifies whether a node-id matches the IP it's used from
// returns true if the node-id is OK coming from this source
// and false otherwise.
bool verify_id(node_id const& nid, address const& source_ip)
{
	// no need to verify local IPs, they would be incorrect anyway
	if (is_local(source_ip)) return true;

	node_id h = generate_id_impl(source_ip, nid[19]);
	return memcmp(&nid[0], &h[0], 4) == 0;
}

node_id generate_id(address const& ip)
{
	return generate_id_impl(ip, random());
}

} }  // namespace libtorrent::dht

<commit_msg>and the typo in trunk as well<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <ctime>

#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_local et.al
#include "libtorrent/socket_io.hpp" // for hash_address
#include "libtorrent/random.hpp" // for random

namespace libtorrent { namespace dht
{

// returns the distance between the two nodes
// using the kademlia XOR-metric
node_id distance(node_id const& n1, node_id const& n2)
{
	node_id ret;
	node_id::iterator k = ret.begin();
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, ++k)
	{
		*k = *i ^ *j;
	}
	return ret;
}

// returns true if: distance(n1, ref) < distance(n2, ref)
bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)
{
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)
	{
		boost::uint8_t lhs = (*i ^ *k);
		boost::uint8_t rhs = (*j ^ *k);
		if (lhs < rhs) return true;
		if (lhs > rhs) return false;
	}
	return false;
}

// returns n in: 2^n <= distance(n1, n2) < 2^(n+1)
// useful for finding out which bucket a node belongs to
int distance_exp(node_id const& n1, node_id const& n2)
{
	int byte = node_id::size - 1;
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, --byte)
	{
		TORRENT_ASSERT(byte >= 0);
		boost::uint8_t t = *i ^ *j;
		if (t == 0) continue;
		// we have found the first non-zero byte
		// return the bit-number of the first bit
		// that differs
		int bit = byte * 8;
		for (int b = 7; b >= 0; --b)
			if (t >= (1 << b)) return bit + b;
		return bit;
	}

	return 0;
}

struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__;

node_id generate_id_impl(address const& ip_, boost::uint32_t r)
{
	boost::uint8_t* ip = 0;

	const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff };
	const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
	boost::uint8_t const* mask = 0;
	int num_octets = 0;

	address_v4::bytes_type b4;
#if TORRENT_USE_IPV6
	address_v6::bytes_type b6;
	if (ip_.is_v6())
	{
		b6 = ip_.to_v6().to_bytes();
		ip = &b6[0];
		num_octets = 8;
		mask = v6mask;
	}
	else
#endif
	{
		b4 = ip_.to_v4().to_bytes();
		ip = &b4[0];
		num_octets = 4;
		mask = v4mask;
	}

	for (int i = 0; i < num_octets; ++i)
		ip[i] &= mask[i];

	hasher h;
	h.update((char*)ip, num_octets);
	boost::uint8_t rand = r & 0x7;
	h.update((char*)&rand, 1);
	node_id id = h.final();
	for (int i = 4; i < 19; ++i) id[i] = random();
	id[19] = r;

	return id;
}

node_id generate_random_id()
{
	char r[20];
	for (int i = 0; i < 20; ++i) r[i] = random();
	return hasher(r, 20).final();
}

// verifies whether a node-id matches the IP it's used from
// returns true if the node-id is OK coming from this source
// and false otherwise.
bool verify_id(node_id const& nid, address const& source_ip)
{
	// no need to verify local IPs, they would be incorrect anyway
	if (is_local(source_ip)) return true;

	node_id h = generate_id_impl(source_ip, nid[19]);
	return memcmp(&nid[0], &h[0], 4) == 0;
}

node_id generate_id(address const& ip)
{
	return generate_id_impl(ip, random());
}

} }  // namespace libtorrent::dht

<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <ctime>

#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_local et.al
#include "libtorrent/socket_io.hpp" // for hash_address
#include "libtorrent/random.hpp"

namespace libtorrent { namespace dht
{

// returns the distance between the two nodes
// using the kademlia XOR-metric
node_id distance(node_id const& n1, node_id const& n2)
{
	node_id ret;
	node_id::iterator k = ret.begin();
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, ++k)
	{
		*k = *i ^ *j;
	}
	return ret;
}

// returns true if: distance(n1, ref) < distance(n2, ref)
bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)
{
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)
	{
		boost::uint8_t lhs = (*i ^ *k);
		boost::uint8_t rhs = (*j ^ *k);
		if (lhs < rhs) return true;
		if (lhs > rhs) return false;
	}
	return false;
}

// returns n in: 2^n <= distance(n1, n2) < 2^(n+1)
// useful for finding out which bucket a node belongs to
int distance_exp(node_id const& n1, node_id const& n2)
{
	int byte = node_id::size - 1;
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, --byte)
	{
		TORRENT_ASSERT(byte >= 0);
		boost::uint8_t t = *i ^ *j;
		if (t == 0) continue;
		// we have found the first non-zero byte
		// return the bit-number of the first bit
		// that differs
		int bit = byte * 8;
		for (int b = 7; b >= 0; --b)
			if (t >= (1 << b)) return bit + b;
		return bit;
	}

	return 0;
}

struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__;

node_id generate_id_impl(address const& ip_, boost::uint32_t r)
{
	boost::uint8_t* ip = 0;

	const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff };
	const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
	boost::uint8_t const* mask = 0;
	int num_octets = 0;

	address_v4::bytes_type b4;
#if TORRENT_USE_IPV6
	address_v6::bytes_type b6;
	if (ip_.is_v6())
	{
		b6 = ip_.to_v6().to_bytes();
		ip = &b6[0];
		num_octets = 8;
		mask = v6mask;
	}
	else
#endif
	{
		b4 = ip_.to_v4().to_bytes();
		ip = &b4[0];
		num_octets = 4;
		mask = v4mask;
	}

	for (int i = 0; i < num_octets; ++i)
		ip[i] &= mask[i];

	hasher h;
	h.update((char*)ip, num_octets);
	boost::uint8_t rand = r & 0x7;
	h.update((char*)&r, 1);
	node_id id = h.final();
	for (int i = 4; i < 19; ++i) id[i] = rand;
	id[19] = r;

	return id;
}

node_id generate_random_id()
{
	char r[20];
	for (int i = 0; i < 20; ++i) r[i] = random();
	return hasher(r, 20).final();
}

// verifies whether a node-id matches the IP it's used from
// returns true if the node-id is OK coming from this source
// and false otherwise.
bool verify_id(node_id const& nid, address const& source_ip)
{
	// no need to verify local IPs, they would be incorrect anyway
	if (is_local(source_ip)) return true;

	node_id h = generate_id_impl(source_ip, nid[19]);
	return memcmp(&nid[0], &h[0], 4) == 0;
}

node_id generate_id(address const& ip)
{
	return generate_id_impl(ip, rand());
}

} }  // namespace libtorrent::dht

<commit_msg>fixed typo<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <ctime>

#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_local et.al
#include "libtorrent/socket_io.hpp" // for hash_address
#include "libtorrent/random.hpp"

namespace libtorrent { namespace dht
{

// returns the distance between the two nodes
// using the kademlia XOR-metric
node_id distance(node_id const& n1, node_id const& n2)
{
	node_id ret;
	node_id::iterator k = ret.begin();
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, ++k)
	{
		*k = *i ^ *j;
	}
	return ret;
}

// returns true if: distance(n1, ref) < distance(n2, ref)
bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)
{
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)
	{
		boost::uint8_t lhs = (*i ^ *k);
		boost::uint8_t rhs = (*j ^ *k);
		if (lhs < rhs) return true;
		if (lhs > rhs) return false;
	}
	return false;
}

// returns n in: 2^n <= distance(n1, n2) < 2^(n+1)
// useful for finding out which bucket a node belongs to
int distance_exp(node_id const& n1, node_id const& n2)
{
	int byte = node_id::size - 1;
	for (node_id::const_iterator i = n1.begin(), j = n2.begin()
		, end(n1.end()); i != end; ++i, ++j, --byte)
	{
		TORRENT_ASSERT(byte >= 0);
		boost::uint8_t t = *i ^ *j;
		if (t == 0) continue;
		// we have found the first non-zero byte
		// return the bit-number of the first bit
		// that differs
		int bit = byte * 8;
		for (int b = 7; b >= 0; --b)
			if (t >= (1 << b)) return bit + b;
		return bit;
	}

	return 0;
}

struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__;

node_id generate_id_impl(address const& ip_, boost::uint32_t r)
{
	boost::uint8_t* ip = 0;

	const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff };
	const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
	boost::uint8_t const* mask = 0;
	int num_octets = 0;

	address_v4::bytes_type b4;
#if TORRENT_USE_IPV6
	address_v6::bytes_type b6;
	if (ip_.is_v6())
	{
		b6 = ip_.to_v6().to_bytes();
		ip = &b6[0];
		num_octets = 8;
		mask = v6mask;
	}
	else
#endif
	{
		b4 = ip_.to_v4().to_bytes();
		ip = &b4[0];
		num_octets = 4;
		mask = v4mask;
	}

	for (int i = 0; i < num_octets; ++i)
		ip[i] &= mask[i];

	hasher h;
	h.update((char*)ip, num_octets);
	boost::uint8_t rand = r & 0x7;
	h.update((char*)&r, 1);
	node_id id = h.final();
	for (int i = 4; i < 19; ++i) id[i] = random();
	id[19] = r;

	return id;
}

node_id generate_random_id()
{
	char r[20];
	for (int i = 0; i < 20; ++i) r[i] = random();
	return hasher(r, 20).final();
}

// verifies whether a node-id matches the IP it's used from
// returns true if the node-id is OK coming from this source
// and false otherwise.
bool verify_id(node_id const& nid, address const& source_ip)
{
	// no need to verify local IPs, they would be incorrect anyway
	if (is_local(source_ip)) return true;

	node_id h = generate_id_impl(source_ip, nid[19]);
	return memcmp(&nid[0], &h[0], 4) == 0;
}

node_id generate_id(address const& ip)
{
	return generate_id_impl(ip, rand());
}

} }  // namespace libtorrent::dht

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <initializer_list>
#include <vector>
#include <string>

// supervisor [-f|--fork] [-p|--pidfile=PATH] -- cmd ...
//
// -f,--fork            whether to fork the supervisor process into background
// -p,--pidfile=PATH    location to store the current supervisor PID
// -r,--restart
// -c,--cgroups         Use cgroups to track PIDs
//
// Examples:
//     supervisor /usr/sbin/x0d --no-fork
//     supervisor -p /var/run/xzero/supervisor.pid -- /usr/sbin/x0d --no-fork

static int childPid = 0;
static int lastSignum = 0;
static std::string programPath;
static std::vector<std::string> programArgs;
static int retryCount = 5;

bool isTerminateSignal(int sig) {
  return sig == SIGTERM || sig == SIGQUIT || sig == SIGINT || sig == SIGHUP;
}

void runProgram() {
  printf("Running program...\n");

  pid_t pid = fork();

  if (pid < 0) {
    fprintf(stderr, "fork failed. %s\n", strerror(errno));
    abort();
  } else if (pid > 0) {
    // parent
    childPid = pid;
    printf("supervisor: child pid is %d\n", pid);
  } else {
    // child

    std::vector<char*> argv;
    argv.push_back(const_cast<char*>(programPath.c_str()));
    for (const std::string& arg : programArgs) {
      argv.push_back(const_cast<char*>(arg.c_str()));
    }
    argv.push_back(nullptr);

    execvp(programPath.c_str(), argv.data());
    fprintf(stderr, "execvp failed. %s\n", strerror(errno));
    abort();
  }
}

bool restartProgram() {
  if (retryCount == 0) {
    return false;
  }

  --retryCount;

  printf("Restarting program (retry count: %d)\n", retryCount);
  runProgram();
  return true;
}

void sighandler(int signum) {
  lastSignum = signum;

  if (childPid) {
    printf("Signal %s (%d) received. Forwarding to child PID %d.\n",
           strsignal(signum), signum, childPid);

    // forward to child process
    kill(childPid, signum);
  }
}

bool parseArgs(int argc, const char* argv[]) {
  if (argc <= 1) {
    fprintf(stderr, "usage error\n");
    return false;
  }

  int i = 1;

  programPath = argv[i];
  i++;

  while (argv[i] != nullptr) {
    programArgs.push_back(argv[i]);
    i++;
  }

  return true;
}

int main(int argc, const char* argv[]) {
  if (!parseArgs(argc, argv)) return 1;

  printf("Installing signal handler...\n");
  for (int sig : {SIGINT, SIGTERM, SIGQUIT, SIGHUP}) {
    signal(sig, &sighandler);
  }

  runProgram();

  while (childPid != 0) {
    int status = 0;
    if (waitpid(childPid, &status, 0) < 0) {
      perror("waitpid");
      break;
    }

    if (WIFEXITED(status)) {
      printf("Child %d terminated with exit code %d\n", childPid,
             WEXITSTATUS(status));
      restartProgram();
      // exit(WEXITSTATUS(status));
    }

    if (WIFSIGNALED(status)) {
      printf("Child %d terminated with signal %s (%d)\n", childPid,
             strsignal(WTERMSIG(status)), WTERMSIG(status));
      restartProgram();
      // exit(EXIT_FAILURE);
    }

    fprintf(stderr, "Child %d terminated. Status code %d\n", childPid, status);
    restartProgram();
    // break;
  }

  return 0;
}

// vim:ts=2:sw=2
<commit_msg>supervisor: snapshot<commit_after>// This file is part of the "x0" project, http://xzero.io/
//   (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <initializer_list>
#include <vector>
#include <fstream>
#include <iostream>
#include <string>

// supervisor [-f|--fork] [-p|--pidfile=PATH] -- cmd ...
//
// -f,--fork            whether to fork the supervisor process into background
// -p,--pidfile=PATH    location to store the current supervisor PID
// -r,--restart         Automatically restart program, if crashed.
// -c,--cgroups         Use cgroups to track PIDs
//
// Examples:
//     supervisor /usr/sbin/x0d --no-fork
//     supervisor -p /var/run/xzero/supervisor.pid -- /usr/sbin/x0d --no-fork

class PidTracker {
 public:
  PidTracker();
  ~PidTracker();

  void add(int pid);
  std::vector<int> get();
  void dump();
};

PidTracker::PidTracker() {
  char path[80];
  snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid());
  int rv = mkdir(path, 0777);

  if (rv < 0) {
    perror("PidTracker: mkdir");
  }
}

PidTracker::~PidTracker() {
  char path[80];
  snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid());
  rmdir(path);
}

void PidTracker::add(int pid) {
  char path[80];
  snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid());

  char buf[64];
  ssize_t n = snprintf(buf, sizeof(buf), "%d", pid);

  int fd = open(path, O_WRONLY);
  write(fd, buf, n);
  close(fd);
}

std::vector<int> PidTracker::get() {
  std::vector<int> result;

  char path[80];
  snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid());

  std::ifstream tasksFile(path);
  std::string line;

  while (std::getline(tasksFile, line)) {
    result.push_back(stoi(line));
  }

  return result;
}

void PidTracker::dump() {
  printf("PID tracking: ");
  const auto pids = get();
  for (int pid: pids) {
    printf(" %d", pid);
  }
  printf("\n");
}

static PidTracker pidTracker;
static int childPid = 0;
static int lastSignum = 0;
static std::string programPath;
static std::vector<std::string> programArgs;
static int retryCount = 5;

void runProgram() {
  printf("Running program...\n");

  pid_t pid = fork();

  if (pid < 0) {
    fprintf(stderr, "fork failed. %s\n", strerror(errno));
    abort();
  } else if (pid > 0) { // parent
    childPid = pid;
    pidTracker.add(pid);
    printf("supervisor: child pid is %d\n", pid);
    pidTracker.dump();
  } else { // child
    std::vector<char*> argv;
    argv.push_back(const_cast<char*>(programPath.c_str()));
    for (const std::string& arg : programArgs) {
      argv.push_back(const_cast<char*>(arg.c_str()));
    }
    argv.push_back(nullptr);

    execvp(programPath.c_str(), argv.data());
    fprintf(stderr, "execvp failed. %s\n", strerror(errno));
    abort();
  }
}

void restartProgram() {
  pidTracker.dump();
  const auto pids = pidTracker.get();
  if (pids.size() == 1) {
    childPid = pids[0];
    printf("supervisor: reattaching to child PID %d\n", childPid);
    return;
  }

  printf("Restarting program (retry count: %d)\n", retryCount);

  if (retryCount == 0) {
    throw EXIT_FAILURE;
  }

  retryCount--;
  runProgram();
}

void sighandler(int signum) {
  lastSignum = signum;

  if (childPid) {
    printf("Signal %s (%d) received. Forwarding to child PID %d.\n",
           strsignal(signum), signum, childPid);

    // forward to child process
    kill(childPid, signum);
  }
}

bool parseArgs(int argc, const char* argv[]) {
  if (argc <= 1) {
    fprintf(stderr, "usage error\n");
    return false;
  }

  int i = 1;

  programPath = argv[i];
  i++;

  while (argv[i] != nullptr) {
    programArgs.push_back(argv[i]);
    i++;
  }

  return true;
}

int main(int argc, const char* argv[]) {
  try {
    if (!parseArgs(argc, argv)) return 1;

    printf("Installing signal handler...\n");
    for (int sig : {SIGINT, SIGTERM, SIGQUIT, SIGHUP}) {
      signal(sig, &sighandler);
    }

    // if (setsid() < 0) {
    //   fprintf(stderr, "Error creating session. %s\n", strerror(errno));
    //   return EXIT_FAILURE;
    // }

    if (setpgrp() < 0) {
      fprintf(stderr, "Error creating process group. %s\n", strerror(errno));
      return EXIT_FAILURE;
    }

    runProgram();

    for (;;) {
      int status = 0;
      if (waitpid(childPid, &status, 0) < 0) {
        perror("waitpid");
        throw EXIT_FAILURE;
      }

      if (WIFEXITED(status)) {
        printf("Child %d terminated with exit code %d\n", childPid,
               WEXITSTATUS(status));
        restartProgram();
      }

      if (WIFSIGNALED(status)) {
        printf("Child %d terminated with signal %s (%d)\n", childPid,
               strsignal(WTERMSIG(status)), WTERMSIG(status));
        restartProgram();
      }

      fprintf(stderr, "Child %d terminated. Status code %d\n", childPid, status);
      restartProgram();
    }
  } catch (int exitCode) {
    return exitCode;
  }
}

// vim:ts=2:sw=2
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "views/controls/textfield/native_textfield_gtk.h"

#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "skia/ext/skia_utils_gtk.h"
#include "views/controls/textfield/textfield.h"

namespace views {
// A character used to hide a text in password mode.
const char kPasswordChar = '*';

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, public:

NativeTextfieldGtk::NativeTextfieldGtk(Textfield* textfield)
    : textfield_(textfield) {
  if (textfield_->style() & Textfield::STYLE_MULTILINE)
    NOTIMPLEMENTED();  // We don't support multiline yet.
  // Make |textfield| the focused view, so that when we get focused the focus
  // manager sees |textfield| as the focused view (since we are just a wrapper
  // view).
  set_focus_view(textfield);
}

NativeTextfieldGtk::~NativeTextfieldGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, NativeTextfieldWrapper implementation:

string16 NativeTextfieldGtk::GetText() const {
  return UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(native_view())));
}

void NativeTextfieldGtk::UpdateText() {
  if (!native_view())
    return;
  gtk_entry_set_text(GTK_ENTRY(native_view()),
                     UTF16ToUTF8(textfield_->text()).c_str());
}

void NativeTextfieldGtk::AppendText(const string16& text) {
  gint position = -1;
  gtk_editable_insert_text(GTK_EDITABLE(native_view()),
                           UTF16ToUTF8(text).c_str(),
                           text.size(), &position);
  if (!native_view())
    return;
  gtk_entry_append_text(GTK_ENTRY(native_view()), UTF16ToUTF8(text).c_str());
}

string16 NativeTextfieldGtk::GetSelectedText() const {
  if (!native_view())
    return string16();

  string16 result;
  gint start_pos;
  gint end_pos;
  if (!gtk_editable_get_selection_bounds(GTK_EDITABLE(native_view()),
                                         &start_pos, &end_pos))
    return result;  // No selection.

  UTF8ToUTF16(gtk_editable_get_chars(GTK_EDITABLE(native_view()),
                                     start_pos, end_pos),
              end_pos - start_pos, &result);
  return result;
}

void NativeTextfieldGtk::SelectAll() {
  if (!native_view())
    return;
  // -1 as the end position selects to the end of the text.
  gtk_editable_select_region(GTK_EDITABLE(native_view()), 0, -1);
}

void NativeTextfieldGtk::ClearSelection() {
  if (!native_view())
    return;
  gtk_editable_select_region(GTK_EDITABLE(native_view()), 0, 0);
}

void NativeTextfieldGtk::UpdateBorder() {
  if (!native_view())
    return;

  if (!textfield_->draw_border())
    gtk_entry_set_has_frame(GTK_ENTRY(native_view()), false);
}

void NativeTextfieldGtk::UpdateTextColor() {
  if (textfield_->use_default_text_color()) {
    // Passing NULL as the color undoes the effect of previous calls to
    // gtk_widget_modify_text.
    gtk_widget_modify_text(native_view(), GTK_STATE_NORMAL, NULL);
    return;
  }
  GdkColor gdk_color = skia::SkColorToGdkColor(textfield_->text_color());
  gtk_widget_modify_text(native_view(), GTK_STATE_NORMAL, &gdk_color);
}

void NativeTextfieldGtk::UpdateBackgroundColor() {
  if (textfield_->use_default_background_color()) {
    // Passing NULL as the color undoes the effect of previous calls to
    // gtk_widget_modify_base.
    gtk_widget_modify_base(native_view(), GTK_STATE_NORMAL, NULL);
    return;
  }
  GdkColor gdk_color = skia::SkColorToGdkColor(textfield_->background_color());
  gtk_widget_modify_base(native_view(), GTK_STATE_NORMAL, &gdk_color);
}

void NativeTextfieldGtk::UpdateReadOnly() {
  if (!native_view())
    return;
  gtk_editable_set_editable(GTK_EDITABLE(native_view()),
                            !textfield_->read_only());
}

void NativeTextfieldGtk::UpdateFont() {
  if (!native_view())
    return;
  gtk_widget_modify_font(native_view(),
                         gfx::Font::PangoFontFromGfxFont(textfield_->font()));
}

void NativeTextfieldGtk::UpdateEnabled() {
  if (!native_view())
    return;
  SetEnabled(textfield_->IsEnabled());
}

gfx::Insets NativeTextfieldGtk::CalculateInsets() {
  if (!native_view())
    return gfx::Insets();

  GtkWidget* widget = native_view();
  GtkEntry* entry = GTK_ENTRY(widget);
  const GtkBorder* inner_border = gtk_entry_get_inner_border(entry);
  int left = 0, right = 0, top = 0, bottom = 0;
  if (!inner_border)
    gtk_widget_style_get(widget, "inner-border", &inner_border, NULL);

  if (inner_border) {
    left += inner_border->left;
    right += inner_border->right;
    top += inner_border->top;
    bottom += inner_border->bottom;
  }

  if (entry->has_frame) {
    left += widget->style->xthickness;
    right += widget->style->xthickness;
    top += widget->style->ythickness;
    bottom += widget->style->ythickness;
  }

  gboolean interior_focus;
  gint focus_width;
  gtk_widget_style_get(widget,
                       "focus-line-width", &focus_width,
                       "interior-focus", &interior_focus,
                       NULL);
  if (!interior_focus) {
    left += focus_width;
    right += focus_width;
    top += focus_width;
    bottom += focus_width;
  }

  return gfx::Insets(top, left, bottom, right);
}

void NativeTextfieldGtk::SetHorizontalMargins(int left, int right) {
  if (!native_view())
    return;
  GtkBorder border = { left, right, 0, 0 };
  gtk_entry_set_inner_border(GTK_ENTRY(native_view()), &border);
}

void NativeTextfieldGtk::SetFocus() {
  Focus();
}

View* NativeTextfieldGtk::GetView() {
  return this;
}

gfx::NativeView NativeTextfieldGtk::GetTestingHandle() const {
  return native_view();
}

// static
gboolean NativeTextfieldGtk::OnKeyPressEventHandler(
    GtkWidget* entry,
    GdkEventKey* event,
    NativeTextfieldGtk* textfield) {
  return textfield->OnKeyPressEvent(event);
}

gboolean NativeTextfieldGtk::OnKeyPressEvent(GdkEventKey* event) {
  Textfield::Controller* controller = textfield_->GetController();
  if (controller) {
    Textfield::Keystroke ks(event);
    return controller->HandleKeystroke(textfield_, ks);
  }
  return false;
}

// static
gboolean NativeTextfieldGtk::OnChangedHandler(
    GtkWidget* entry,
    NativeTextfieldGtk* textfield) {
  return textfield->OnChanged();
}

gboolean NativeTextfieldGtk::OnChanged() {
  textfield_->SyncText();
  Textfield::Controller* controller = textfield_->GetController();
  if (controller)
    controller->ContentsChanged(textfield_, GetText());
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, NativeControlGtk overrides:

void NativeTextfieldGtk::CreateNativeControl() {
  NativeControlCreated(gtk_entry_new());
  if (textfield_->IsPassword()) {
    gtk_entry_set_invisible_char(GTK_ENTRY(native_view()),
                                 static_cast<gunichar>(kPasswordChar));
    gtk_entry_set_visibility(GTK_ENTRY(native_view()), false);
  }
}

void NativeTextfieldGtk::NativeControlCreated(GtkWidget* widget) {
  NativeControlGtk::NativeControlCreated(widget);
  g_signal_connect(widget, "changed",
                   G_CALLBACK(OnChangedHandler), this);
  g_signal_connect(widget, "key-press-event",
                   G_CALLBACK(OnKeyPressEventHandler), this);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldWrapper, public:

// static
NativeTextfieldWrapper* NativeTextfieldWrapper::CreateWrapper(
    Textfield* field) {
  return new NativeTextfieldGtk(field);
}

}  // namespace views
<commit_msg>Partially revert r28629.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "views/controls/textfield/native_textfield_gtk.h"

#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "skia/ext/skia_utils_gtk.h"
#include "views/controls/textfield/textfield.h"

namespace views {
// A character used to hide a text in password mode.
const char kPasswordChar = '*';

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, public:

NativeTextfieldGtk::NativeTextfieldGtk(Textfield* textfield)
    : textfield_(textfield) {
  if (textfield_->style() & Textfield::STYLE_MULTILINE)
    NOTIMPLEMENTED();  // We don't support multiline yet.
  // Make |textfield| the focused view, so that when we get focused the focus
  // manager sees |textfield| as the focused view (since we are just a wrapper
  // view).
  set_focus_view(textfield);
}

NativeTextfieldGtk::~NativeTextfieldGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, NativeTextfieldWrapper implementation:

string16 NativeTextfieldGtk::GetText() const {
  return UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(native_view())));
}

void NativeTextfieldGtk::UpdateText() {
  if (!native_view())
    return;
  gtk_entry_set_text(GTK_ENTRY(native_view()),
                     UTF16ToUTF8(textfield_->text()).c_str());
}

void NativeTextfieldGtk::AppendText(const string16& text) {
  gint position = -1;
  gtk_editable_insert_text(GTK_EDITABLE(native_view()),
                           UTF16ToUTF8(text).c_str(),
                           text.size(), &position);
  if (!native_view())
    return;
  gtk_entry_append_text(GTK_ENTRY(native_view()), UTF16ToUTF8(text).c_str());
}

string16 NativeTextfieldGtk::GetSelectedText() const {
  if (!native_view())
    return string16();

  string16 result;
  gint start_pos;
  gint end_pos;
  if (!gtk_editable_get_selection_bounds(GTK_EDITABLE(native_view()),
                                         &start_pos, &end_pos))
    return result;  // No selection.

  UTF8ToUTF16(gtk_editable_get_chars(GTK_EDITABLE(native_view()),
                                     start_pos, end_pos),
              end_pos - start_pos, &result);
  return result;
}

void NativeTextfieldGtk::SelectAll() {
  if (!native_view())
    return;
  // -1 as the end position selects to the end of the text.
  gtk_editable_select_region(GTK_EDITABLE(native_view()), 0, -1);
}

void NativeTextfieldGtk::ClearSelection() {
  if (!native_view())
    return;
  gtk_editable_select_region(GTK_EDITABLE(native_view()), 0, 0);
}

void NativeTextfieldGtk::UpdateBorder() {
  if (!native_view())
    return;

  if (!textfield_->draw_border())
    gtk_entry_set_has_frame(GTK_ENTRY(native_view()), false);
}

void NativeTextfieldGtk::UpdateTextColor() {
  if (textfield_->use_default_text_color()) {
    // Passing NULL as the color undoes the effect of previous calls to
    // gtk_widget_modify_text.
    gtk_widget_modify_text(native_view(), GTK_STATE_NORMAL, NULL);
    return;
  }
  GdkColor gdk_color = skia::SkColorToGdkColor(textfield_->text_color());
  gtk_widget_modify_text(native_view(), GTK_STATE_NORMAL, &gdk_color);
}

void NativeTextfieldGtk::UpdateBackgroundColor() {
  if (textfield_->use_default_background_color()) {
    // Passing NULL as the color undoes the effect of previous calls to
    // gtk_widget_modify_base.
    gtk_widget_modify_base(native_view(), GTK_STATE_NORMAL, NULL);
    return;
  }
  GdkColor gdk_color = skia::SkColorToGdkColor(textfield_->background_color());
  gtk_widget_modify_base(native_view(), GTK_STATE_NORMAL, &gdk_color);
}

void NativeTextfieldGtk::UpdateReadOnly() {
  if (!native_view())
    return;
  gtk_editable_set_editable(GTK_EDITABLE(native_view()),
                            !textfield_->read_only());
}

void NativeTextfieldGtk::UpdateFont() {
  if (!native_view())
    return;
  gtk_widget_modify_font(native_view(),
                         gfx::Font::PangoFontFromGfxFont(textfield_->font()));
}

void NativeTextfieldGtk::UpdateEnabled() {
  if (!native_view())
    return;
  SetEnabled(textfield_->IsEnabled());
}

gfx::Insets NativeTextfieldGtk::CalculateInsets() {
  if (!native_view())
    return gfx::Insets();

  GtkWidget* widget = native_view();
  GtkEntry* entry = GTK_ENTRY(widget);
  const GtkBorder* inner_border = gtk_entry_get_inner_border(entry);
  int left = 0, right = 0, top = 0, bottom = 0;
  if (!inner_border)
    gtk_widget_style_get(widget, "inner-border", &inner_border, NULL);

  if (inner_border) {
    left += inner_border->left;
    right += inner_border->right;
    top += inner_border->top;
    bottom += inner_border->bottom;
  }

  if (entry->has_frame) {
    left += widget->style->xthickness;
    right += widget->style->xthickness;
    top += widget->style->ythickness;
    bottom += widget->style->ythickness;
  }

  gboolean interior_focus;
  gint focus_width;
  gtk_widget_style_get(widget,
                       "focus-line-width", &focus_width,
                       "interior-focus", &interior_focus,
                       NULL);
  if (!interior_focus) {
    left += focus_width;
    right += focus_width;
    top += focus_width;
    bottom += focus_width;
  }

  return gfx::Insets(top, left, bottom, right);
}

void NativeTextfieldGtk::SetHorizontalMargins(int left, int right) {
  if (!native_view())
    return;
  GtkBorder border = { left, right, 0, 0 };
  gtk_entry_set_inner_border(GTK_ENTRY(native_view()), &border);
}

void NativeTextfieldGtk::SetFocus() {
  Focus();
}

View* NativeTextfieldGtk::GetView() {
  return this;
}

gfx::NativeView NativeTextfieldGtk::GetTestingHandle() const {
  return native_view();
}

// static
gboolean NativeTextfieldGtk::OnKeyPressEventHandler(
    GtkWidget* entry,
    GdkEventKey* event,
    NativeTextfieldGtk* textfield) {
  return textfield->OnKeyPressEvent(event);
}

gboolean NativeTextfieldGtk::OnKeyPressEvent(GdkEventKey* event) {
  Textfield::Controller* controller = textfield_->GetController();
  if (controller) {
    Textfield::Keystroke ks(event);
    return controller->HandleKeystroke(textfield_, ks);
  }
  return false;
}

// static
gboolean NativeTextfieldGtk::OnChangedHandler(
    GtkWidget* entry,
    NativeTextfieldGtk* textfield) {
  return textfield->OnChanged();
}

gboolean NativeTextfieldGtk::OnChanged() {
  Textfield::Controller* controller = textfield_->GetController();
  if (controller)
    controller->ContentsChanged(textfield_, GetText());
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldGtk, NativeControlGtk overrides:

void NativeTextfieldGtk::CreateNativeControl() {
  NativeControlCreated(gtk_entry_new());
  if (textfield_->IsPassword()) {
    gtk_entry_set_invisible_char(GTK_ENTRY(native_view()),
                                 static_cast<gunichar>(kPasswordChar));
    gtk_entry_set_visibility(GTK_ENTRY(native_view()), false);
  }
}

void NativeTextfieldGtk::NativeControlCreated(GtkWidget* widget) {
  NativeControlGtk::NativeControlCreated(widget);
  g_signal_connect(widget, "changed",
                   G_CALLBACK(OnChangedHandler), this);
  g_signal_connect(widget, "key-press-event",
                   G_CALLBACK(OnKeyPressEventHandler), this);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTextfieldWrapper, public:

// static
NativeTextfieldWrapper* NativeTextfieldWrapper::CreateWrapper(
    Textfield* field) {
  return new NativeTextfieldGtk(field);
}

}  // namespace views
<|endoftext|>


<commit_before>// Copyright 2014, Yahoo! Inc.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <jni.h>

#include "yahoo/cnet/android/cnet_jni.h"

#include "base/android/base_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/android/scoped_java_ref.h"
#include "base/logging.h"
#include "net/android/net_jni_registrar.h"
#include "url/android/url_jni_registrar.h"
#include "yahoo/cnet/cnet.h"
#include "yahoo/cnet/android/cnet_jni.h"
#include "yahoo/cnet/android/cnet_jni_registrar.h"
#include "yahoo/cnet/android/cnet_ymagine.h"

namespace {

const base::android::RegistrationMethod kCnetRegisteredMethods[] = {
  {"BaseAndroid", base::android::RegisterJni},
  {"NetAndroid", net::android::RegisterJni},
  {"UrlAndroid", url::android::RegisterJni},
  {"CnetAndroid", cnet::android::RegisterJni},
};

}

extern "C" {

jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
  if (base::android::IsVMInitialized()) {
    LOG(ERROR) << "Double load of the cnet library.";
  } else {
    LOG(INFO) << "Loading Cnet.";

    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
      return -1;
    }

    base::android::InitVM(vm);

    if (!base::android::RegisterNativeMethods(
          env, kCnetRegisteredMethods, arraysize(kCnetRegisteredMethods))) {
      LOG(ERROR) << "Failed to register Cnet native methods.";
      return -1;
    }

    // Dynamic link to Ymagine if it is available.
    cnet::ymagine::android::SymsInit();

    CnetInitialize(0);
  }

  return JNI_VERSION_1_6;
}

void JNIEXPORT JNICALL JNI_OnUnload(JavaVM* jvm, void* reserved) {
  LOG(INFO) << "Unloading Cnet";
  CnetCleanup();
}

void CnetJniInitializeAppContext(JNIEnv* env, jobject context) {
  base::android::ScopedJavaLocalRef<jobject> scoped_context(env, context);
  base::android::InitApplicationContext(env, scoped_context);
}

};
<commit_msg>Android: improve init ordering.<commit_after>// Copyright 2014, Yahoo! Inc.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <jni.h>

#include "yahoo/cnet/android/cnet_jni.h"

#include "base/android/base_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/android/scoped_java_ref.h"
#include "base/logging.h"
#include "net/android/net_jni_registrar.h"
#include "url/android/url_jni_registrar.h"
#include "yahoo/cnet/cnet.h"
#include "yahoo/cnet/android/cnet_jni.h"
#include "yahoo/cnet/android/cnet_jni_registrar.h"
#include "yahoo/cnet/android/cnet_ymagine.h"

namespace {

const base::android::RegistrationMethod kCnetRegisteredMethods[] = {
  {"BaseAndroid", base::android::RegisterJni},
  {"NetAndroid", net::android::RegisterJni},
  {"UrlAndroid", url::android::RegisterJni},
  {"CnetAndroid", cnet::android::RegisterJni},
};

}

extern "C" {

jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
  if (base::android::IsVMInitialized()) {
    LOG(ERROR) << "Double load of the cnet library.";
  } else {
    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
      return -1;
    }

    base::android::InitVM(vm);

    if (!base::android::RegisterNativeMethods(
          env, kCnetRegisteredMethods, arraysize(kCnetRegisteredMethods))) {
      return -1;
    }

    CnetInitialize(0);

    // Dynamic link to Ymagine if it is available.
    cnet::ymagine::android::SymsInit();
  }

  return JNI_VERSION_1_6;
}

void JNIEXPORT JNICALL JNI_OnUnload(JavaVM* jvm, void* reserved) {
  LOG(INFO) << "Unloading Cnet";
  CnetCleanup();
}

void CnetJniInitializeAppContext(JNIEnv* env, jobject context) {
  base::android::ScopedJavaLocalRef<jobject> scoped_context(env, context);
  base::android::InitApplicationContext(env, scoped_context);
}

};
<|endoftext|>


<commit_before>/*
 * mpu6050_node.cpp
 * Copyright (c) 2017, Robot Mitya.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Robot Mitya nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *  Created on: Dec 3, 2017
 *      Author: Dmitry Dzakhov
 */

#include <ros/ros.h>
#include <sensor_msgs/Imu.h>
#include "std_msgs/String.h"
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include "consts.h"

#define VALUES_TO_CALIBRATE 1000

class Mpu6050Node
{
public:
  Mpu6050Node();
  void fillImuMessage(const sensor_msgs::ImuPtr& msg);
  void publishImuMessage(const sensor_msgs::ImuPtr& msg);
private:
  int i2cAddress_;
  int fileDescriptor_;
  float readWord2c(int addr);

  // Topic RM_IMU_TOPIC_NAME ('imu') publisher:
  ros::Publisher imuPublisher_;

  ros::Subscriber imuInputSubscriber_;
  void imuInputCallback(const std_msgs::StringConstPtr& msg);

//  float angularVelocitiesX[VALUES_TO_CALIBRATE];
//  float angularVelocitiesY[VALUES_TO_CALIBRATE];
//  float angularVelocitiesZ[VALUES_TO_CALIBRATE];
//  float accelerationsX[VALUES_TO_CALIBRATE];
//  float accelerationsY[VALUES_TO_CALIBRATE];
//  float accelerationsZ[VALUES_TO_CALIBRATE];
//  int arrayIndex;
};

const int PWR_MGMT_1 = 0x6B;

Mpu6050Node::Mpu6050Node()
{
  ros::NodeHandle privateNodeHandle("~");
  privateNodeHandle.param("i2c_address", i2cAddress_, 0x68);

  // Connect to device.
  fileDescriptor_ = wiringPiI2CSetup(i2cAddress_);
  if (fileDescriptor_ == -1)
  {
    ROS_ERROR("No i2c device found?");
    return;
  }
  // Device starts in sleep mode so wake it up.
  wiringPiI2CWriteReg16(fileDescriptor_, PWR_MGMT_1, 0);

  ros::NodeHandle nodeHandle(RM_NAMESPACE);
  imuPublisher_ = nodeHandle.advertise<sensor_msgs::Imu>(RM_HEAD_IMU_OUTPUT_TOPIC_NAME, 100);

  imuInputSubscriber_ = nodeHandle.subscribe(RM_HEAD_IMU_INPUT_TOPIC_NAME, 10, &Mpu6050Node::imuInputCallback, this);
}

float Mpu6050Node::readWord2c(int addr)
{
  int high = wiringPiI2CReadReg8(fileDescriptor_, addr);
  int low = wiringPiI2CReadReg8(fileDescriptor_, addr + 1);
  int val = (high << 8) + low;
  return float((val >= 0x8000) ? -((65535 - val) + 1) : val);
}

void Mpu6050Node::fillImuMessage(const sensor_msgs::ImuPtr& msg)
{
  msg->header.stamp = ros::Time::now();
  msg->header.frame_id = '0';  // no frame

  // Read gyroscope values.
  // At default sensitivity of 250deg/s we need to scale by 131.
  msg->angular_velocity.x = readWord2c(0x43) / 131;
  msg->angular_velocity.y = readWord2c(0x45) / 131;
  msg->angular_velocity.z = readWord2c(0x47) / 131;

  // Read accelerometer values.
  // At default sensitivity of 2g we need to scale by 16384.
  // Note: at "level" x = y = 0 but z = 1 (i.e. gravity)
  // But! Imu message documentations say acceleration should be in m/2 so need to *9.807
  const float la_rescale = 16384.0 / 9.807;
  msg->linear_acceleration.x = readWord2c(0x3b) / la_rescale;
  msg->linear_acceleration.y = readWord2c(0x3d) / la_rescale;
  msg->linear_acceleration.z = readWord2c(0x3f) / la_rescale;
}

void Mpu6050Node::publishImuMessage(const sensor_msgs::ImuPtr& msg)
{
  imuPublisher_.publish(msg);
}

void Mpu6050Node::imuInputCallback(const std_msgs::StringConstPtr& msg)
{
  if (msg->data.compare("calibrate") == 0)
  {
    ROS_INFO("Starting to calibrate head IMU...");
  }
  else
  {
    ROS_INFO("%s.%s: Unknown command \"%s\"", RM_MPU6050_NODE_NAME, RM_HEAD_IMU_INPUT_TOPIC_NAME, msg->data.c_str());
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, RM_MPU6050_NODE_NAME);

  Mpu6050Node mpu6050Node;
  sensor_msgs::ImuPtr imuPrt(new sensor_msgs::Imu());

  ros::Rate rate(50);  // hz
  while(ros::ok())
  {
    mpu6050Node.fillImuMessage(imuPrt);
    mpu6050Node.publishImuMessage(imuPrt);

    ros::spinOnce();
    rate.sleep();
  }
  return 0;
}
<commit_msg>#12 Preparing to MPU calibrate procedure<commit_after>/*
 * mpu6050_node.cpp
 * Copyright (c) 2017, Robot Mitya.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Robot Mitya nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *  Created on: Dec 3, 2017
 *      Author: Dmitry Dzakhov
 */

#include <ros/ros.h>
#include <sensor_msgs/Imu.h>
#include "std_msgs/String.h"
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include "consts.h"

#define VALUES_TO_CALIBRATE 1000

class Mpu6050Node
{
public:
  Mpu6050Node();
  void fillImuMessage(const sensor_msgs::ImuPtr& msg);
  void publishImuMessage(const sensor_msgs::ImuPtr& msg);
private:
  int i2cAddress_;
  int fileDescriptor_;
  float readWord2c(int addr);

  // Topic RM_IMU_TOPIC_NAME ('imu') publisher:
  ros::Publisher imuPublisher_;

  ros::Subscriber imuInputSubscriber_;
  void imuInputCallback(const std_msgs::StringConstPtr& msg);

//  float angularVelocitiesX[VALUES_TO_CALIBRATE];
//  float angularVelocitiesY[VALUES_TO_CALIBRATE];
//  float angularVelocitiesZ[VALUES_TO_CALIBRATE];
//  float accelerationsX[VALUES_TO_CALIBRATE];
//  float accelerationsY[VALUES_TO_CALIBRATE];
//  float accelerationsZ[VALUES_TO_CALIBRATE];
//  int arrayIndex;
};

const int PWR_MGMT_1 = 0x6B;

Mpu6050Node::Mpu6050Node()
{
  ros::NodeHandle privateNodeHandle("~");
  privateNodeHandle.param("i2c_address", i2cAddress_, 0x68);

  // Connect to device.
  fileDescriptor_ = wiringPiI2CSetup(i2cAddress_);
  if (fileDescriptor_ == -1)
  {
    ROS_ERROR("No i2c device found?");
    return;
  }
  // Device starts in sleep mode so wake it up.
  wiringPiI2CWriteReg16(fileDescriptor_, PWR_MGMT_1, 0);

  ros::NodeHandle nodeHandle(RM_NAMESPACE);
  imuPublisher_ = nodeHandle.advertise<sensor_msgs::Imu>(RM_HEAD_IMU_OUTPUT_TOPIC_NAME, 100);

  imuInputSubscriber_ = nodeHandle.subscribe(RM_HEAD_IMU_INPUT_TOPIC_NAME, 10, &Mpu6050Node::imuInputCallback, this);
}

float Mpu6050Node::readWord2c(int addr)
{
  int high = wiringPiI2CReadReg8(fileDescriptor_, addr);
  int low = wiringPiI2CReadReg8(fileDescriptor_, addr + 1);
  int val = (high << 8) + low;
  return float((val >= 0x8000) ? -((65535 - val) + 1) : val);
}

void Mpu6050Node::fillImuMessage(const sensor_msgs::ImuPtr& msg)
{
  msg->header.stamp = ros::Time::now();
  msg->header.frame_id = '0';  // no frame

  // Read gyroscope values.
  // At default sensitivity of 250deg/s we need to scale by 131.
  msg->angular_velocity.x = readWord2c(0x43) / 131;
  msg->angular_velocity.y = readWord2c(0x45) / 131;
  msg->angular_velocity.z = readWord2c(0x47) / 131;

  // Read accelerometer values.
  // At default sensitivity of 2g we need to scale by 16384.
  // Note: at "level" x = y = 0 but z = 1 (i.e. gravity)
  // But! Imu message documentations say acceleration should be in m/2 so need to *9.807
  const float la_rescale = 16384.0 / 9.807;
  msg->linear_acceleration.x = readWord2c(0x3b) / la_rescale;
  msg->linear_acceleration.y = readWord2c(0x3d) / la_rescale;
  msg->linear_acceleration.z = readWord2c(0x3f) / la_rescale;
}

void Mpu6050Node::publishImuMessage(const sensor_msgs::ImuPtr& msg)
{
  imuPublisher_.publish(msg);
}

void Mpu6050Node::imuInputCallback(const std_msgs::StringConstPtr& msg)
{
  ROS_INFO("In imuInputCallback()"); //TODO Remove this line!
  if (msg->data.compare("calibrate") == 0)
  {
    ROS_INFO("Starting to calibrate head IMU...");
  }
  else
  {
    ROS_INFO("%s.%s: Unknown command \"%s\"", RM_MPU6050_NODE_NAME, RM_HEAD_IMU_INPUT_TOPIC_NAME, msg->data.c_str());
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, RM_MPU6050_NODE_NAME);

  Mpu6050Node mpu6050Node;
  sensor_msgs::ImuPtr imuPrt(new sensor_msgs::Imu());

  ros::Rate rate(50);  // hz
  while(ros::ok())
  {
    mpu6050Node.fillImuMessage(imuPrt);
    mpu6050Node.publishImuMessage(imuPrt);

    ros::spinOnce();
    rate.sleep();
  }
  return 0;
}
<|endoftext|>