示例#1
0
mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) {
    byte *p = *ptr;
    mp_uint_t align;

    int size = mp_binary_get_size(struct_type, val_type, &align);
    if (struct_type == '@') {
        // Make pointer aligned
        p = (byte*)(((mp_uint_t)p + align - 1) & ~((mp_uint_t)align - 1));
        #if MP_ENDIANNESS_LITTLE
        struct_type = '<';
        #else
        struct_type = '>';
        #endif
    }
    *ptr = p + size;

    mp_int_t val = mp_binary_get_int(size, is_signed(val_type), (struct_type == '>'), p);

    if (val_type == 'O') {
        return (mp_obj_t)val;
    } else if (val_type == 'S') {
        return mp_obj_new_str((char*)val, strlen((char*)val), false);
    } else if (is_signed(val_type)) {
        return mp_obj_new_int(val);
    } else {
        return mp_obj_new_int_from_uint(val);
    }
}
示例#2
0
/**
 * Return the smallest type that both t1 and t2 can be cast to without losing
 * information.
 *
 * e.g.
 *
 * join_types(unsignedbv_typet(32), unsignedbv_typet(16))=unsignedbv_typet(32)
 * join_types(signedbv_typet(16), unsignedbv_typet(16))=signedbv_typet(17)
 * join_types(signedbv_typet(32), signedbv_typet(32))=signedbv_typet(32)
 */
typet join_types(const typet &t1, const typet &t2)
{
  // Handle the simple case first...
  if(t1==t2)
  {
    return t1;
  }

  // OK, they're not the same type.  Are they both bitvectors?
  if(is_bitvector(t1) && is_bitvector(t2))
  {
    // They are.  That makes things easy!  There are three cases to consider:
    // both types are unsigned, both types are signed or there's one of each.

    bitvector_typet b1=to_bitvector_type(t1);
    bitvector_typet b2=to_bitvector_type(t2);

    if(is_unsigned(b1) && is_unsigned(b2))
    {
      // We just need to take the max of their widths.
      std::size_t width=std::max(b1.get_width(), b2.get_width());
      return unsignedbv_typet(width);
    }
    else if(is_signed(b1) && is_signed(b2))
    {
      // Again, just need to take the max of the widths.
      std::size_t width=std::max(b1.get_width(), b2.get_width());
      return signedbv_typet(width);
    }
    else
    {
      // This is the (slightly) tricky case.  If we have a signed and an
      // unsigned type, we're going to return a signed type.  And to cast
      // an unsigned type to a signed type, we need the signed type to be
      // at least one bit wider than the unsigned type we're casting from.
      std::size_t signed_width=is_signed(t1) ? b1.get_width() :
                                                 b2.get_width();
      std::size_t unsigned_width=is_signed(t1) ? b2.get_width() :
                                                   b1.get_width();
      // unsigned_width++;

      std::size_t width=std::max(signed_width, unsigned_width);

      return signedbv_typet(width);
    }
  }

  std::cerr << "Tried to join types: "
            << t1.pretty() << " and " << t2.pretty()
            << '\n';
  assert(!"Couldn't join types");
}
示例#3
0
	/**
	 * Determines if a type is comaptible with another, for purposes of converting data. It prevents
	 * conversions that lose information.
	 * @param dest The data type being converted to
	 * @param src The data type being converted from
	 * @return True if the 'src' type can be converted to 'dest' type.
	 */
	inline bool is_compatible( data_types::enum_t dest, data_types::enum_t src ){
		//We allow free conversion between floating point types
		if( is_float( src ) )
			return is_float( dest );

		//Only allow integer conversions that can't lose data.

		if( is_signed(src) )
			return is_signed(dest) && data_types::sizes[dest] >= data_types::sizes[src];

		//We allow a unsigned -> signed conversion if the bit depth increases.
		return is_signed(dest) ? data_types::sizes[dest] > data_types::sizes[src] : data_types::sizes[dest] >= data_types::sizes[src];
	}
示例#4
0
/*
** Like atoi() this will convert char* to integer if the string given is made
** of numbers. Will return 0 if there is a problem.
*/
int	ft_atoi(const char *str)
{
	int int_value;
	int is_positive;
	unsigned int loop;

	int_value = 0;
	loop = is_signed(str);
	is_positive = 1;
	if (*(str + loop) == '-')
	{
		is_positive = -1;
		loop++;
	}
	else if (*(str + loop) == '+')
		loop++;
	while (loop < ft_strlen(str))
	{
		if (ft_isdigit(*(str + loop)))
			int_value = int_value * 10 + *(str + loop)  - '0';
		else
			break;
		loop++;
	}
	return (is_positive * int_value);
}
示例#5
0
void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte **ptr) {
    byte *p = *ptr;
    mp_uint_t align;

    size_t size = mp_binary_get_size(struct_type, val_type, &align);
    if (struct_type == '@') {
        // Make pointer aligned
        p = (byte*)(((mp_uint_t)p + align - 1) & ~((mp_uint_t)align - 1));
        if (MP_ENDIANNESS_LITTLE) {
            struct_type = '<';
        } else {
            struct_type = '>';
        }
    }
    *ptr = p + size;

    mp_uint_t val;
    switch (val_type) {
        case 'O':
            val = (mp_uint_t)val_in;
            break;
#if MICROPY_PY_BUILTINS_FLOAT
        case 'f': {
            union { uint32_t i; float f; } fp_sp;
            fp_sp.f = mp_obj_get_float(val_in);
            val = fp_sp.i;
            break;
        }
        case 'd': {
            union { uint64_t i64; uint32_t i32[2]; double f; } fp_dp;
            fp_dp.f = mp_obj_get_float(val_in);
            if (BYTES_PER_WORD == 8) {
                val = fp_dp.i64;
            } else {
                int be = struct_type == '>';
                mp_binary_set_int(sizeof(uint32_t), be, p, fp_dp.i32[MP_ENDIANNESS_BIG ^ be]);
                p += sizeof(uint32_t);
                val = fp_dp.i32[MP_ENDIANNESS_LITTLE ^ be];
            }
            break;
        }
#endif
        default:
            #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
            if (MP_OBJ_IS_TYPE(val_in, &mp_type_int)) {
                mp_obj_int_to_bytes_impl(val_in, struct_type == '>', size, p);
                return;
            } else
            #endif
            {
                val = mp_obj_get_int(val_in);
                // sign extend if needed
                if (BYTES_PER_WORD < 8 && size > sizeof(val) && is_signed(val_type) && (mp_int_t)val < 0) {
                    memset(p + sizeof(val), 0xff, size - sizeof(val));
                }
            }
    }

    mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val);
}
示例#6
0
mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) {
    byte *p = *ptr;
    mp_uint_t align;

    size_t size = mp_binary_get_size(struct_type, val_type, &align);
    if (struct_type == '@') {
        // Make pointer aligned
        p = (byte*)(((mp_uint_t)p + align - 1) & ~((mp_uint_t)align - 1));
        #if MP_ENDIANNESS_LITTLE
        struct_type = '<';
        #else
        struct_type = '>';
        #endif
    }
    *ptr = p + size;

    long long val = mp_binary_get_int(size, is_signed(val_type), (struct_type == '>'), p);

    if (val_type == 'O') {
        return (mp_obj_t)(mp_uint_t)val;
    } else if (val_type == 'S') {
        const char *s_val = (const char*)(mp_uint_t)val;
        return mp_obj_new_str(s_val, strlen(s_val), false);
#if MICROPY_PY_BUILTINS_FLOAT
    } else if (val_type == 'f') {
        union { uint32_t i; float f; } fpu = {val};
        return mp_obj_new_float(fpu.f);
    } else if (val_type == 'd') {
        union { uint64_t i; double f; } fpu = {val};
        return mp_obj_new_float(fpu.f);
#endif
    } else if (is_signed(val_type)) {
        if ((long long)MP_SMALL_INT_MIN <= val && val <= (long long)MP_SMALL_INT_MAX) {
            return mp_obj_new_int((mp_int_t)val);
        } else {
            return mp_obj_new_int_from_ll(val);
        }
    } else {
        if ((unsigned long long)val <= (unsigned long long)MP_SMALL_INT_MAX) {
            return mp_obj_new_int_from_uint((mp_uint_t)val);
        } else {
            return mp_obj_new_int_from_ull(val);
        }
    }
}
示例#7
0
LLVMValueRef gen_eq_rvalue(compile_t* c, ast_t* left, LLVMValueRef r_value)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(c->opt, type);
  LLVMValueRef l_value = gen_expr(c, left);

  return make_cmp_value(c, sign, l_value, r_value, LLVMRealOEQ, LLVMIntEQ,
    LLVMIntEQ);
}
示例#8
0
LLVMValueRef gen_eq_rvalue(compile_t* c, ast_t* left, LLVMValueRef r_value)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(type);
  LLVMValueRef l_value = gen_expr(c, left);

  LLVMValueRef test = make_cmp_value(c, sign, l_value, r_value,
    LLVMRealOEQ, LLVMIntEQ, LLVMIntEQ);

  return LLVMBuildZExt(c->builder, test, c->ibool, "");
}
示例#9
0
static LLVMValueRef make_cmp(compile_t* c, ast_t* left, ast_t* right,
  LLVMRealPredicate cmp_f, LLVMIntPredicate cmp_si, LLVMIntPredicate cmp_ui)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(c->opt, type);

  LLVMValueRef l_value = gen_expr(c, left);
  LLVMValueRef r_value = gen_expr(c, right);

  return make_cmp_value(c, sign, l_value, r_value, cmp_f, cmp_si, cmp_ui);
}
示例#10
0
static LLVMValueRef make_cmp(compile_t* c, ast_t* left, ast_t* right,
  LLVMRealPredicate cmp_f, LLVMIntPredicate cmp_si, LLVMIntPredicate cmp_ui)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(type);

  LLVMValueRef l_value = gen_expr(c, left);
  LLVMValueRef r_value = gen_expr(c, right);

  LLVMValueRef test = make_cmp_value(c, sign, l_value, r_value,
    cmp_f, cmp_si, cmp_ui);

  return LLVMBuildZExt(c->builder, test, c->ibool, "");
}
示例#11
0
文件: dwarf.c 项目: andymcn/ponyc
static void setup_dwarf(dwarf_t* dwarf, dwarf_meta_t* meta, gentype_t* g,
  bool opaque, bool field)
{
  memset(meta, 0, sizeof(dwarf_meta_t));

  ast_t* ast = g->ast;
  LLVMTypeRef type = g->primitive;

  if(is_machine_word(ast))
  {
    if(is_float(ast))
      meta->flags |= DWARF_FLOAT;
    else if(is_signed(dwarf->opt, ast))
      meta->flags |= DWARF_SIGNED;
    else if(is_bool(ast))
      meta->flags |= DWARF_BOOLEAN;
  }
  else if(is_pointer(ast) || is_maybe(ast) || !is_concrete(ast) ||
    (is_constructable(ast) && field))
  {
    type = g->use_type;
  }
  else if(is_constructable(ast))
  {
    type = g->structure;
  }

  bool defined_type = g->underlying != TK_TUPLETYPE &&
    g->underlying != TK_UNIONTYPE && g->underlying != TK_ISECTTYPE;

  source_t* source;

  if(defined_type)
    ast = (ast_t*)ast_data(ast);

  source = ast_source(ast);
  meta->file = source->file;
  meta->name = g->type_name;
  meta->line = ast_line(ast);
  meta->pos = ast_pos(ast);

  if(!opaque)
  {
    meta->size = LLVMABISizeOfType(dwarf->target_data, type) << 3;
    meta->align = LLVMABIAlignmentOfType(dwarf->target_data, type) << 3;
  }
}
示例#12
0
int				print_with_precision(t_formater *fmt, t_printf *pf)
{
	int			is_nega;
	int			ret;

	ret = 0;
	is_nega = pf->fmt_str[0] == '-' ? 1 : 0;
	if (is_nega)
		pf->prefix = ft_strdup("-");
	if (is_signed(fmt) && fmt->flag & F_BLANK && !is_neg(pf->fmt_str))
	{
		ret += ft_putchar(' ');
		fmt->width -= 1;
	}
	ret += print_w_pres3(fmt, pf);
	return (ret);
}
示例#13
0
int main()
{
    double z = 1.0;

    cout << "Some inquiries into the nature of double:" << endl
         << "digits(z) = " << digits(z) << endl
         << "epsilon(z) = " << epsilon(z) << endl
         << "huge(z) = " << huge(z) << endl
         << "tiny(z) = " << tiny(z) << endl
         << "max_exponent(z) = " << max_exponent(z) << endl
         << "min_exponent(z) = " << min_exponent(z) << endl
         << "max_exponent10(z) = " << max_exponent10(z) << endl
         << "min_exponent10(z) = " << min_exponent10(z) << endl
         << "precision(z) = " << precision(z) << endl
         << "radix(z) = " << radix(z) << endl;

    Range r = range(z);
    cout << "range(z) = [ " << r.first() << ", " << r.last() << " ]"
         << endl;

    cout << endl << "More obscure properties:" << endl
         << "is_signed(z) = " << is_signed(z) << endl
         << "is_integer(z) = " << is_integer(z) << endl
         << "is_exact(z) = " << is_exact(z) << endl
         << "round_error(z) = " << round_error(z) << endl
         << "has_infinity(z) = " << has_infinity(z) << endl
         << "has_quiet_NaN(z) = " << has_quiet_NaN(z) << endl
         << "has_signaling_NaN(z) = " << has_signaling_NaN(z) << endl
         << "has_denorm(z) = " << has_denorm(z) << endl
         << "has_denorm_loss(z) = " << has_denorm_loss(z) << endl
         << "infinity(z) = " << infinity(z) << endl
         << "quiet_NaN(z) = " << quiet_NaN(z) << endl
         << "signaling_NaN(z) = " << signaling_NaN(z) << endl
         << "denorm_min(z) = " << denorm_min(z) << endl
         << "is_iec559(z) = " << is_iec559(z) << endl
         << "is_bounded(z) = " << is_bounded(z) << endl
         << "is_modulo(z) = " << is_modulo(z) << endl
         << "traps(z) = " << traps(z) << endl
         << "tinyness_before(z) = " << tinyness_before(z) << endl;

    return 0;
}
示例#14
0
文件: gentype.c 项目: Praetonus/ponyc
static void make_debug_basic(compile_t* c, reach_type_t* t)
{
  uint64_t size = LLVMABISizeOfType(c->target_data, t->primitive);
  uint64_t align = LLVMABIAlignmentOfType(c->target_data, t->primitive);
  unsigned encoding;

  if(is_bool(t->ast))
  {
    encoding = DW_ATE_boolean;
  } else if(is_float(t->ast)) {
    encoding = DW_ATE_float;
  } else if(is_signed(t->ast)) {
    encoding = DW_ATE_signed;
  } else {
    encoding = DW_ATE_unsigned;
  }

  t->di_type = LLVMDIBuilderCreateBasicType(c->di, t->name,
    8 * size, 8 * align, encoding);
}
示例#15
0
static void
genGlobalDefClassId(const char* cname, int id) {
  GenInfo* info = gGenInfo;
  const char* id_type_name = "chpl__class_id";
  std::string name("chpl__cid_");
  name += cname;
  
  if( info->cfile ) {
    fprintf(info->cfile, "const %s %s = %d;\n", 
                      id_type_name, name.c_str(), id);
  } else {
#ifdef HAVE_LLVM
    GenRet id_type_g = CLASS_ID_TYPE->codegen();
    llvm::Type *id_type = id_type_g.type;
    llvm::GlobalVariable * gv = llvm::cast<llvm::GlobalVariable>(
        info->module->getOrInsertGlobal(name, id_type));
    gv->setInitializer(info->builder->getInt32(id));
    gv->setConstant(true);
    info->lvt->addGlobalValue(name, gv, GEN_PTR, ! is_signed(CLASS_ID_TYPE));
#endif
  }
}
示例#16
0
int				print_regular(t_formater *fmt, t_printf *pf)
{
	int		ret;
	int		is_nega;
	int		size;

	ret = 0;
	is_nega = pf->fmt_str[0] == '-' ? 1 : 0;
	if (is_nega)
		pf->prefix = ft_strdup("-");
	if (is_signed(fmt) && fmt->flag & F_BLANK && !is_neg(pf->fmt_str))
	{
		ret += ft_putchar(' ');
		fmt->width -= 1;
	}
	size = final_size(fmt->width, ft_strlen(is_nega? pf->fmt_str + 1 : \
				pf->fmt_str) + ft_strlen(pf->prefix));
	if (!(fmt->flag & F_MINUS) && !(fmt->flag & F_ZERO))
		ret += print_n_char(' ', size);
	ret += ft_putstr(pf->prefix);
	ret += print_reg2(fmt, pf, size);
	return (ret);
}
示例#17
0
LLVMValueRef gen_shr(compile_t* c, ast_t* left, ast_t* right)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(c->opt, type);

  LLVMValueRef l_value = gen_expr(c, left);
  LLVMValueRef r_value = gen_expr(c, right);

  if((l_value == NULL) || (r_value == NULL))
    return NULL;

  if(LLVMIsConstant(l_value) && LLVMIsConstant(r_value))
  {
    if(sign)
      return LLVMConstAShr(l_value, r_value);

    return LLVMConstLShr(l_value, r_value);
  }

  if(sign)
    return LLVMBuildAShr(c->builder, l_value, r_value, "");

  return LLVMBuildLShr(c->builder, l_value, r_value, "");
}
示例#18
0
GLenum get_suitable_internal_format(const GLenum format, const GLenum type,
        const bool use_compression) noexcept
{
    const int num_channels = get_num_channels(format);
    const bool int_format = is_integer_format(format);
    const bool snorm = is_signed(type);
    const bool has_s3tc = glewIsSupported("EXT_texture_compression_s3tc");
    const bool has_rgtc = glewIsSupported("ARB_texture_compression_rgtc");
    const bool has_bptc = glewIsSupported("ARB_texture_compression_bptc");

    GLenum internal_format;

    if (num_channels == 1) {
        if (use_compression && !int_format && has_rgtc) {
            internal_format = snorm ? GL_COMPRESSED_SIGNED_RED_RGTC1 :
                GL_COMPRESSED_RED_RGTC1;
        } else if (type == GL_FLOAT) {
            internal_format = GL_R32F;
        } else if (type == GL_INT) {
            // GL_R32_SNORM not available! Choose closest.
            internal_format = int_format ? GL_R32I : GL_R16_SNORM;
        } else if (type == GL_UNSIGNED_INT) {
            // GL_R32 not available! Choose closest.
            internal_format = int_format ? GL_R32UI : GL_R16;
        } else if (type == GL_SHORT) {
            internal_format = int_format ? GL_R16I : GL_R16_SNORM;
        } else if (type == GL_UNSIGNED_SHORT) {
            internal_format = int_format ? GL_R16UI : GL_R16;
        } else if (type == GL_BYTE) {
            internal_format = int_format ? GL_R8I : GL_R8_SNORM;
        } else {
            // just use GL_R8 for everything else
            internal_format = int_format ? GL_R8UI : GL_R8;
        }
    } else if (num_channels == 2) {
        if (use_compression && !int_format && has_rgtc) {
            internal_format = snorm ? GL_COMPRESSED_SIGNED_RG_RGTC2 :
                GL_COMPRESSED_RG_RGTC2;
        } else if (type == GL_FLOAT) {
            internal_format = GL_RG32F;
        } else if (type == GL_INT) {
            // GL_RG32_SNORM not available! Choose closest.
            internal_format = int_format ? GL_RG32I : GL_RG16_SNORM;
        } else if (type == GL_UNSIGNED_INT) {
            // GL_RG32 not available! Choose closest.
            internal_format = int_format ? GL_RG32UI : GL_RG16;
        } else if (type == GL_SHORT) {
            internal_format = int_format ? GL_RG16I : GL_RG16_SNORM;
        } else if (type == GL_UNSIGNED_SHORT) {
            internal_format = int_format ? GL_RG16UI : GL_RG16;
        } else if (type == GL_BYTE) {
            internal_format = int_format ? GL_RG8I : GL_RG8_SNORM;
        } else {
            // just use GL_RG8 for everything else
            internal_format = int_format ? GL_RG8UI : GL_RG8;
        }
    } else if (num_channels == 3) {
        if (use_compression && !int_format && has_bptc) {
            internal_format = snorm ? GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT :
                    GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
        } else if (use_compression && !int_format && !snorm && has_s3tc) {
            internal_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
        } else if (type == GL_FLOAT) {
            internal_format = GL_RGB32F;
        } else if (type == GL_INT) {
            // GL_RGB32_SNORM not available! Choose closest.
            internal_format = int_format ? GL_RGB32I : GL_RGB16_SNORM;
        } else if (type == GL_UNSIGNED_INT) {
            // GL_RGB32 not available! Choose closest.
            internal_format = int_format ? GL_RGB32UI : GL_RGB16;
        } else if (type == GL_SHORT) {
            internal_format = int_format ? GL_RGB16I : GL_RGB16_SNORM;
        } else if (type == GL_UNSIGNED_SHORT) {
            internal_format = int_format ? GL_RGB16UI : GL_RGB16;
        } else if (type == GL_BYTE) {
            internal_format = int_format ? GL_RGB8I : GL_RGB8_SNORM;
        } else {
            // just use GL_RGB8 for everything else
            internal_format = int_format ? GL_RGB8UI : GL_RGB8;
        }
    } else if (num_channels == 4) {
        if (use_compression && !int_format && !snorm &&
                (has_bptc || has_s3tc))
        {
            internal_format = has_bptc ? GL_COMPRESSED_RGBA_BPTC_UNORM :
                GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
        } else if (type == GL_FLOAT) {
            internal_format = GL_RGBA32F;
        } else if (type == GL_INT) {
            // GL_RGBA32_SNORM not available! Choose closest.
            internal_format = int_format ? GL_RGBA32I : GL_RGBA16_SNORM;
        } else if (type == GL_UNSIGNED_INT) {
            // GL_RGBA32 not available! Choose closest.
            internal_format = int_format ? GL_RGBA32UI : GL_RGBA16;
        } else if (type == GL_SHORT) {
            internal_format = int_format ? GL_RGBA16I : GL_RGBA16_SNORM;
        } else if (type == GL_UNSIGNED_SHORT) {
            internal_format = int_format ? GL_RGBA16UI : GL_RGBA16;
        } else if (type == GL_BYTE) {
            internal_format = int_format ? GL_RGBA8I : GL_RGBA8_SNORM;
        } else {
            // just use GL_RGBA8 for everything else
            internal_format = int_format ? GL_RGBA8UI : GL_RGBA8;
        }
    } else {
        // should not be reached
        abort();
    }

    return internal_format;
}
示例#19
0
文件: symbol.cpp 项目: rlugojr/chapel
void VarSymbol::codegenDef() {
  GenInfo* info = gGenInfo;

  if (id == breakOnCodegenID)
    gdbShouldBreakHere();

  // Local variable symbols should never be
  // generated for extern or void types
  if (this->hasFlag(FLAG_EXTERN))
    return;
  if (type == dtVoid)
    return;

  if( info->cfile ) {
    codegenDefC();
  } else {
#ifdef HAVE_LLVM
    if(isImmediate()) {
      llvm::GlobalVariable *globalValue = llvm::cast<llvm::GlobalVariable>(
          info->module->getOrInsertGlobal(cname, type->codegen().type));
      globalValue->setConstant(true);

      if(immediate->const_kind == CONST_KIND_STRING) {
        if(llvm::Value *constString = codegenImmediateLLVM(immediate)) {
          llvm::GlobalVariable *globalString =
            llvm::cast<llvm::GlobalVariable>(constString);
          globalValue->setInitializer(llvm::cast<llvm::Constant>(
                info->builder->CreateConstInBoundsGEP2_32(
#if HAVE_LLVM_VER >= 37
                  NULL,
#endif
                  globalString, 0, 0)));
        } else {
          llvm::GlobalVariable *globalString =
            new llvm::GlobalVariable(
                *info->module,
                llvm::IntegerType::getInt8Ty(info->module->getContext()),
                true,
                llvm::GlobalVariable::PrivateLinkage,
                NULL,
                "string");
          globalString->setInitializer(llvm::Constant::getNullValue(
                llvm::IntegerType::getInt8Ty(info->module->getContext())));
          globalValue->setInitializer(llvm::cast<llvm::Constant>(
                info->builder->CreateConstInBoundsGEP1_32(
#if HAVE_LLVM_VER >= 37
                  NULL,
#endif
                  globalString, 0)));
        }
      } else {
        globalValue->setInitializer(llvm::cast<llvm::Constant>(
              codegenImmediateLLVM(immediate)));
      }
      info->lvt->addGlobalValue(cname, globalValue, GEN_VAL, ! is_signed(type));
    }
    llvm::Type *varType = type->codegen().type;
    llvm::Value *varAlloca = createTempVarLLVM(varType, cname);
    info->lvt->addValue(cname, varAlloca, GEN_PTR, ! is_signed(type));

    if(AggregateType *ctype = toAggregateType(type)) {
      if(ctype->isClass() ||
         ctype->symbol->hasFlag(FLAG_WIDE_REF) ||
         ctype->symbol->hasFlag(FLAG_WIDE_CLASS)) {
        if(isFnSymbol(defPoint->parentSymbol)) {
          info->builder->CreateStore(
              llvm::Constant::getNullValue(varType), varAlloca);
        }
      }
    }
    if(debug_info){
      debug_info->get_variable(this);
    }
#endif
  }
}
示例#20
0
文件: symbol.cpp 项目: rlugojr/chapel
void VarSymbol::codegenGlobalDef(bool isHeader) {
  GenInfo* info = gGenInfo;

  if( id == breakOnCodegenID ||
      (breakOnCodegenCname[0] &&
       0 == strcmp(cname, breakOnCodegenCname)) ) {
    gdbShouldBreakHere();
  }

  if( info->cfile ) {
    codegenDefC(/*global=*/true, isHeader);
  } else {
#ifdef HAVE_LLVM
    if(type == dtVoid || !isHeader) {
      return;
    }

    if( this->hasFlag(FLAG_EXTERN) ) {
      // Make sure that it already exists in the layered value table.
      if( isType() ) {
        llvm::Type* t = info->lvt->getType(cname);
        if( ! t ) {
          // TODO should be USR_FATAL
          USR_WARN(this, "Could not find extern def of type %s", cname);
        }
      } else {
        GenRet v = info->lvt->getValue(cname);
        if( ! v.val ) {
          // TODO should be USR_FATAL
          // Commenting out to prevent problems with S_IRWXU and friends
          // USR_WARN(this, "Could not find extern def of %s", cname);
        }
      }
    } else {
      bool existing;

      existing = (info->module->getNamedValue(cname) != NULL);

      if( existing )
        INT_FATAL(this, "Redefinition of a global variable %s", cname);

      // Now, create a global variable with appropriate linkage.
      llvm::Type* llTy = type->codegen().type;
      INT_ASSERT(llTy);

      llvm::GlobalVariable *gVar =
        new llvm::GlobalVariable(
            *info->module,
            llTy,
            false, /* is constant */
            hasFlag(FLAG_EXPORT) ? llvm::GlobalVariable::ExternalLinkage
                                 : llvm::GlobalVariable::InternalLinkage,
            llvm::Constant::getNullValue(llTy), /* initializer, */
            cname);
      info->lvt->addGlobalValue(cname, gVar, GEN_PTR, ! is_signed(type) );

      if(debug_info){
        debug_info->get_global_variable(this);
      }
    }
#endif
  }
}
示例#21
0
LLVMValueRef make_divmod(compile_t* c, ast_t* left, ast_t* right,
  const_binop const_f, const_binop const_ui, const_binop const_si,
  build_binop build_f, build_binop build_ui, build_binop build_si)
{
  ast_t* type = ast_type(left);
  bool sign = is_signed(c->opt, type);

  LLVMValueRef l_value = gen_expr(c, left);
  LLVMValueRef r_value = gen_expr(c, right);

  if((l_value == NULL) || (r_value == NULL))
    return NULL;

  if(!is_fp(r_value) &&
    LLVMIsConstant(r_value) &&
    (LLVMConstIntGetSExtValue(r_value) == 0)
    )
  {
    ast_error(right, "constant divide or mod by zero");
    return NULL;
  }

  if(LLVMIsConstant(l_value) && LLVMIsConstant(r_value))
  {
    if(is_fp(l_value))
      return const_f(l_value, r_value);

    if(sign)
      return const_si(l_value, r_value);

    return const_ui(l_value, r_value);
  }

  if(is_fp(l_value))
    return build_f(c->builder, l_value, r_value, "");

  // Setup additional blocks.
  LLVMBasicBlockRef insert = LLVMGetInsertBlock(c->builder);
  LLVMBasicBlockRef then_block = codegen_block(c, "div_then");
  LLVMBasicBlockRef post_block = codegen_block(c, "div_post");

  // Check for div by zero.
  LLVMTypeRef r_type = LLVMTypeOf(r_value);
  LLVMValueRef zero = LLVMConstInt(r_type, 0, false);
  LLVMValueRef cmp = LLVMBuildICmp(c->builder, LLVMIntNE, r_value, zero, "");
  LLVMBuildCondBr(c->builder, cmp, then_block, post_block);

  // Divisor is not zero.
  LLVMPositionBuilderAtEnd(c->builder, then_block);
  LLVMValueRef result;

  if(sign)
    result = build_si(c->builder, l_value, r_value, "");
  else
    result = build_ui(c->builder, l_value, r_value, "");

  LLVMBuildBr(c->builder, post_block);

  // Phi node.
  LLVMPositionBuilderAtEnd(c->builder, post_block);
  LLVMValueRef phi = LLVMBuildPhi(c->builder, r_type, "");
  LLVMAddIncoming(phi, &zero, &insert, 1);
  LLVMAddIncoming(phi, &result, &then_block, 1);

  return phi;
}
示例#22
0
LLVM_DITYPE debug_data::construct_type(Type *type)
{
  llvm::MDNode *N = myGetType(type);
  if(N) return toDITYPE(N);

  GenInfo* info = gGenInfo;
  LLVM_TARGET_DATA *layout = info->targetData; 
  
  llvm::Type* ty = type->symbol->llvmType;
  const char* name = type->symbol->name;
  ModuleSymbol* defModule = type->symbol->getModule();
  const char* defFile = type->symbol->fname();
  if (strstr(defFile, "/modules/")!=NULL || strcmp(defFile, "<internal>")==0) {
#if HAVE_LLVM_VER >= 37
    return NULL;
#else
    return llvm::DIType();
#endif

  }
  int defLine = type->symbol->linenum();

  if(!ty) {
#if HAVE_LLVM_VER >= 37
    return NULL;
#else
    return llvm::DIType();
#endif
  }
  if(ty->isIntegerTy()) {
    N = this->dibuilder.createBasicType(
      name,
      layout->getTypeSizeInBits(ty),
      8*layout->getABITypeAlignment(ty),
      (is_signed(type))? 
      (llvm::dwarf::DW_ATE_signed):
      (llvm::dwarf::DW_ATE_unsigned));

    myTypeDescriptors[type] = N;
    return toDITYPE(N);
  }

  else if(ty->isFloatingPointTy()) {
    N = this->dibuilder.createBasicType(
      name,
      layout->getTypeSizeInBits(ty),
      8*layout->getABITypeAlignment(ty),
      llvm::dwarf::DW_ATE_float);
    
    myTypeDescriptors[type] = N;
    return toDITYPE(N);
  }

  else if(ty->isPointerTy()) {
    if(type != type->getValType()) {//Add this condition to avoid segFault 
      N = this->dibuilder.createPointerType(
        get_type(type->getValType()),//it should return the pointee's DIType
        layout->getPointerSizeInBits(ty->getPointerAddressSpace()),
        0, /* alignment */
        name);

      myTypeDescriptors[type] = N;
      return toDITYPE(N);
    }
    else {
      if(type->astTag == E_PrimitiveType) {
        llvm::Type *PointeeTy = ty->getPointerElementType();
        // handle string, c_string, c_string_copy, nil, opaque, c_void_ptr
        if(PointeeTy->isIntegerTy()) {
          LLVM_DITYPE pteIntDIType; //create the DI-pointeeType
          pteIntDIType = this->dibuilder.createBasicType(
            myGetTypeName(PointeeTy), 
            layout->getTypeSizeInBits(PointeeTy),
            8*layout->getABITypeAlignment(PointeeTy),
            llvm::dwarf::DW_ATE_unsigned);

          N = this->dibuilder.createPointerType(
            pteIntDIType, 
            layout->getPointerSizeInBits(ty->getPointerAddressSpace()),
            0,
            name);

          myTypeDescriptors[type] = N;
          return toDITYPE(N);
        }
        // handle qio_channel_ptr_t, _task_list, qio_file_ptr_t, syserr, _file
        else if(PointeeTy->isStructTy()) {
          LLVM_DITYPE pteStrDIType; //create the DI-pointeeType
          pteStrDIType = this->dibuilder.createStructType(
            get_module_scope(defModule),
            PointeeTy->getStructName(),
            get_file(defFile),
            0,
            (PointeeTy->isSized()?
            layout->getTypeSizeInBits(PointeeTy):
            8),
            (PointeeTy->isSized()?
            8*layout->getABITypeAlignment(PointeeTy):
            8),
            0,
            toDITYPE(NULL),
#if HAVE_LLVM_VER >= 37
            NULL
#else
            llvm::DIArray(NULL)
#endif
            );
        
          N = this->dibuilder.createPointerType(
            pteStrDIType,
            layout->getPointerSizeInBits(ty->getPointerAddressSpace()),
            0,
            name);
        
          myTypeDescriptors[type] = N;
          return toDITYPE(N);
        }
      }
      else if(type->astTag == E_AggregateType) {
        // dealing with classes
        AggregateType *this_class = (AggregateType *)type;
        llvm::SmallVector<LLVM_METADATA_OPERAND_TYPE *, 8> EltTys;
        LLVM_DITYPE derivedFrom = nullptr;
        if( type->dispatchParents.length() > 0 )
          derivedFrom = get_type(type->dispatchParents.first());

        // solve the data class: _ddata
        if(this_class->symbol->hasFlag(FLAG_DATA_CLASS)) {
          Type* vt = getDataClassType(this_class->symbol)->typeInfo();
          if(vt) {
            N = this->dibuilder.createPointerType(
              get_type(vt),
              layout->getPointerSizeInBits(ty->getPointerAddressSpace()),
              0,
              name);
            
            myTypeDescriptors[type] = N;
            return toDITYPE(N);
          }
        } //Not sure whether we should directly return getType(vt)
        
        const llvm::StructLayout* slayout = NULL;
        const char *struct_name = this_class->classStructName(true);
        llvm::Type* st = getTypeLLVM(struct_name);
        if(st){
          llvm::StructType* struct_type = llvm::cast<llvm::StructType>(st);
          if(!struct_type->isOpaque()){
            N = this->dibuilder.createForwardDecl(
              llvm::dwarf::DW_TAG_structure_type, 
              name,
              get_module_scope(defModule),
              get_file(defFile),
              defLine,
              0, // RuntimeLang
              layout->getTypeSizeInBits(ty),
              8*layout->getABITypeAlignment(ty));
     
            //N is added to the map (early) so that element search below can find it,
            //so as to avoid infinite recursion for structs that contain pointers to
            //their own type.
            myTypeDescriptors[type] = N;

            slayout = layout->getStructLayout(struct_type); 
            for_fields(field, this_class) {
              // field is a Symbol
              const char* fieldDefFile = field->defPoint->fname();
              int fieldDefLine = field->defPoint->linenum();
              TypeSymbol* fts = field->type->symbol;
              llvm::Type* fty = fts->llvmType;
              LLVM_DITYPE mty;
              LLVM_DITYPE fditype =  get_type(field->type);
              if(fditype == NULL)
              // if field->type is an internal type, get_type returns null
              // which is not a good type for a MemberType). At the moment it
              // uses a nullptr type as a stub, but we should change it
                fditype = this->dibuilder.createNullPtrType();

              //use the dummy type for 'BaseArr'
              mty = this->dibuilder.createMemberType(
                get_module_scope(defModule),
                field->name,
                get_file(fieldDefFile),
                fieldDefLine,
                layout->getTypeSizeInBits(fty),
                8*layout->getABITypeAlignment(fty),
                slayout->getElementOffsetInBits(this_class->getMemberGEP(field->cname)),
                0,
                fditype);

              EltTys.push_back(mty);
            }

            // Now create the DItype for the struct
            N = this->dibuilder.createStructType(
              get_module_scope(defModule),
              name,
              get_file(defFile),
              defLine,
              layout->getTypeSizeInBits(ty),
              8*layout->getABITypeAlignment(ty),
              0, // RuntimeLang
              derivedFrom,
              this->dibuilder.getOrCreateArray(EltTys));
            
            return toDITYPE(N);
          }//end of if(!Opaque)
        }// end of if(st)
      } // end of astTag == E_AggregateTy
    } // end of else (type==type->getType)
示例#23
0
uint32_t decSingleIsPositive (const decSingle* _0) noexcept
{
// see decBasic.c, decNumberLocal.h
  const uint32_t word = *((const uint32_t*)_0);
  return !is_signed (word) && !is_zero (word) && !is_nan (word);
}
char *get_token(char *lexeme , int mode){
	char *token=(char*)calloc(strlen(lexeme)+50,sizeof(char));
	//printf("Getting token\n");
	if(is_long(lexeme)){
		sprintf(token,"%d",LONG);
	}
	else if(is_static(lexeme)){
		sprintf(token,"%d",STATIC);
	}
	else if(is_union(lexeme)){
		sprintf(token,"%d",UNION);
	}
	else if(is_default(lexeme)){
		sprintf(token,"%d",DEFAULT);
	}
	else if(is_break(lexeme)){
		sprintf(token,"%d",BREAK);
	}
	else if(is_case(lexeme)){
		sprintf(token,"%d",CASE);
	}
	else if(is_continue(lexeme)){
		sprintf(token,"%d",CONTINUE);
	}
	else if(is_goto(lexeme)){
		sprintf(token,"%d",GOTO);
	}
	else if(is_struct(lexeme)){
		sprintf(token,"%d",STRUCT);
	}
	else if(is_const(lexeme)){
		sprintf(token,"%d",CONST);
	}
	else if(is_void(lexeme)){
		sprintf(token,"%d",VOID);
	}
	else if(is_switch(lexeme)){
		sprintf(token,"%d",SWITCH);
	}
	else if(is_for(lexeme)){
		sprintf(token,"%d",FOR);
	}
	else if(is_while(lexeme)){
		sprintf(token,"%d",WHILE);
	}
	else if(is_do(lexeme)){
		sprintf(token,"%d",DO);
	}
	else if(is_return(lexeme)){
		sprintf(token,"%d",RETURN);
	}
	else if(is_bool(lexeme)){
		sprintf(token,"%d",BOOL);
	}
	else if(is_char(lexeme)){
		sprintf(token,"%d",CHAR);
	}
	else if(is_signed(lexeme)){
		sprintf(token,"%d",SIGNED);
	}
	else if(is_unsigned(lexeme)){
		sprintf(token,"%d",UNSIGNED);
	}
	else if(is_short(lexeme)){
		sprintf(token,"%d",SHORT);
	}
	else if(is_int(lexeme)){
		sprintf(token,"%d",INT);
	}
	else if(is_float(lexeme)){
		sprintf(token,"%d",FLOAT);
	}
	else if(is_double(lexeme)){
		sprintf(token,"%d",DOUBLE);
	}
	else if(is_l_square(lexeme)){
		sprintf(token,"%d",L_SQUARE);
	}
	else if(is_r_square(lexeme)){
		sprintf(token,"%d",R_SQUARE);
	}
	else if(is_l_paraen(lexeme)){
		sprintf(token,"%d",L_PARAEN);
	}
	else if(is_r_paraen(lexeme)){
		sprintf(token,"%d",R_PARAEN);
	}
	else if(is_l_cbrace(lexeme)){
		sprintf(token,"%d",L_CBRACE);
	}
	else if(is_r_cbrace(lexeme)){
		sprintf(token,"%d",R_CBRACE);
	}
	else if(is_comma(lexeme)){
		sprintf(token,"%d",COMMA);
	}
	else if(is_semicol(lexeme)){
		sprintf(token,"%d",SEMICOL);
	}
	else if(is_eq_eq(lexeme)){
		sprintf(token,"%d",EQ_EQ);
	}
	else if(is_lesser(lexeme)){
		sprintf(token,"%d",LESSER);
	}
	else if(is_less_eq(lexeme)){
		sprintf(token,"%d",LESS_EQ);
	}
	else if(is_div(lexeme)){
		sprintf(token,"%d",DIV);
	}
	else if(is_greater(lexeme)){
		sprintf(token,"%d",GREATER);
	}
	else if(is_great_eq(lexeme)){
		sprintf(token,"%d",GREAT_EQ);
	}
	else if(is_plus_eq(lexeme)){
		sprintf(token,"%d",PLUS_EQ);
	}
	else if(is_minus_eq(lexeme)){
		sprintf(token,"%d",MINUS_EQ);
	}
	else if(is_div_eq(lexeme)){
		sprintf(token,"%d",DIV_EQ);
	}
	else if(is_mult_eq(lexeme)){
		sprintf(token,"%d",MULT_EQ);
	}
	else if(is_minus_minus(lexeme)){
		sprintf(token,"%d",MINUS_MINUS);
	}
	else if(is_plus_plus(lexeme)){
		sprintf(token,"%d",PLUS_PLUS);
	}
	else if(is_percent(lexeme)){
		sprintf(token,"%d",PERCENT);
	}
	else if(is_div(lexeme)){
		sprintf(token,"%d",DIV);
	}
	else if(is_mult(lexeme)){
		sprintf(token,"%d",MULT);
	}
	else if(is_minus(lexeme)){
		sprintf(token,"%d",MINUS);
	}
	else if(is_plus(lexeme)){
		sprintf(token,"%d",PLUS);
	}
	else if(is_int_const(lexeme)){
		printf("int");
		sprintf(token,"%d\t%s",INT_CONST,lexeme);
	}
	else if(is_flo_const(lexeme)){
		printf("float");
		sprintf(token,"%d\t%s",FLO_CONST,lexeme);
	}
	else if(is_comment_start(lexeme)){
		sprintf(token,"$start");
	}
	else if(is_comment_end(lexeme)){
		sprintf(token,"$end");
	}
	else if(is_identifier(lexeme)){
		printf("Identifier");
		if(mode==1) ht_set( symboltable, lexeme, "1");
		sprintf(token,"%d\t%s",IDNTIFIER,lexeme);
	}
	else sprintf(token,"%d",NOTOK);
	return token;
}
int wmain(int argc, WCHAR *argv[])
{

	/* Display welcome message */
	printf("handle_monitor %s - Adam Kramer\n", VERSION_NUMBER);

	/* These variables hold configuration options, which can be altered by arguments passed */
	BOOL bIncludeSigned = FALSE;
	BOOL bSuspendProcess = FALSE;
	BOOL bVerbose = FALSE;
	DWORD dNumberCycles = 10;
	DWORD dHandleChangeThreshold = 10;
	DWORD dIterationPause = 1000;

	/* Process arguments */
	if (argc > 1)
	{
		for (int iNumberArgs = 1; iNumberArgs < argc; iNumberArgs++)
		{
			/* /signed - will include signed files in the alerts */
			if (!wcscmp(argv[iNumberArgs], L"/signed"))
			{
				bIncludeSigned = TRUE;
				printf("Info: Will show signed files as well as unsigned\n");
			}
			/* /suspect - will attempt to suspend suspicious processes */
			else if (!wcscmp(argv[iNumberArgs], L"/suspend"))
			{
				bSuspendProcess = TRUE;
				printf("Info: Will attempt to suspend suspicious processes\n");
			}
			/* /verbose - will display details of iterations and hidden results */
			else if (!wcscmp(argv[iNumberArgs], L"/verbose"))
			{
				bVerbose = TRUE;
				printf("Info: Will display verbose status messages\n");
			}
			/* /cycles - allows the user to set cycles completed before analysis */
			else if (WCHAR* wSetCycles = wcsstr(argv[iNumberArgs], L"/cycles="))
			{
				wSetCycles = wcschr(wSetCycles, '=');

				if (!(dNumberCycles = _wtol(++wSetCycles)))
				{
					printf("Error: Invalid /cycles parameter\n");
					return 1;
				}

				printf("Info: Setting number of cycles to %d\n", dNumberCycles);
			}
			/* /threshold - allows the user to set the threshold for minimum number of new handles which are suspicious */
			else if (WCHAR* wSetThreshold = wcsstr(argv[iNumberArgs], L"/threshold="))
			{
				wSetThreshold = wcschr(wSetThreshold, '=');

				if (!(dHandleChangeThreshold = _wtol(++wSetThreshold)))
				{
					printf("Error: Invalid /threshold parameter\n");
					return 1;
				}

				printf("Info: Setting handle threshold to %d\n", dHandleChangeThreshold);
			}
			/* /pause - allows the user to set a pause between cycles (reduce system load, increase window for finding something) */
			else if (WCHAR* wSetPause = wcsstr(argv[iNumberArgs], L"/pause="))
			{
				wSetPause = wcschr(wSetPause, '=');

				dIterationPause = _wtol(++wSetPause);
				printf("Info: Setting pause between cycles to %dms\n", dIterationPause);
			}
		}
		/* End of argument processing */
	}
	else
	{
		/* No argument passed, accordingly display the usage instructions */
		printf("Usage: handle_monitor.exe <optional parameters>\n\n");
		printf("Optional parameters:\n");
		printf("/cycles=X - Set number of cycles before a review [Default: 10]\n");
		printf("/threshold=X - Set suspicion threshold for number of new handles [Default: 10]\n");
		printf("/pause=X - Set pause in milliseconds between cycles [Default: 1000]\n");
		printf("/signed - Include signed executables in review process\n");
		printf("/suspend - Suspend processes identified as suspicious\n");
		printf("/verbose - Display verbose progress messages\n\n");
		printf("Info: No parameters specified, launching monitoring (Ctrl+C to stop)\n");
	}

	/* Import functions manually from NTDLL */
	_NtQuerySystemInformation NtQuerySystemInformation =
		(_NtQuerySystemInformation)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQuerySystemInformation");

	_NtDuplicateObject NtDuplicateObject =
		(_NtDuplicateObject)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtDuplicateObject");

	_NtQueryObject NtQueryObject =
		(_NtQueryObject)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryObject");

	/* Master loop! - This runs forever until a user presses Ctrl+C */
	for (;;)
	{
		/* Update user that process is starting (if /verbose mode activiated) */
		if (bVerbose)
			printf("Verbose Info: Starting sequence\n");

		/* Variables used for retrieving handles */
		NTSTATUS status;
		ULONG handleInfoSize = 0x10000;
		HANDLE processHandle;
		ULONG i;
		PSYSTEM_HANDLE_INFORMATION handleInfo;

		/* Used in each handle iteration to identify the index in iProcessArray of the specific process */
		int iCurrentProcess_ArrayIndex = -1;

		/* Handle array - PROCESS INDEX / HANDLE NUMBER / TEXT OF HANDLE
			This holds all handles which have been found per process */
		auto cHandleArray = new WCHAR[MAX_PROCESSES][MAX_FILE_HANDLES][MAX_PATH]();
		signed int iProcessArray[MAX_PROCESSES][3] = { 0 };

		/* Set process array to -1, which indicates nothing has been set */
		for (int j = 0; j < (MAX_PROCESSES - 1); j++)
			iProcessArray[j][0] = -1;

		/* Loop dNumberCycles [default: 10] times before analysing result */
		for (unsigned int iCycleCounter = 1; iCycleCounter <= dNumberCycles; iCycleCounter++)
		{
			handleInfoSize = 0x10000;
			handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);

			/* NtQuerySystemInformation won't give us the correct buffer size, so we guess by doubling the buffer size. */
			while ((status = NtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH)
				handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);

			/* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
			if (!NT_SUCCESS(status))
			{
				printf("NtQuerySystemInformation failed!\n");
				return 1;
			}

			/* Loop for each handle on the system, processing it accordingly... */
			for (i = 0; i < handleInfo->HandleCount; i++)
			{
				SYSTEM_HANDLE handle = handleInfo->Handles[i];
				HANDLE dupHandle = NULL;
				POBJECT_TYPE_INFORMATION objectTypeInfo;

				/* Open a handle to the process associated with the handle */
				if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, handle.ProcessId)))
					continue;

				/* Duplicate the handle so we can query it. */
				if (!NT_SUCCESS(NtDuplicateObject(processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, GENERIC_READ, 0, 0)))
				{
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* Query the object type */
				objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
				if (!NT_SUCCESS(NtQueryObject(dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL)))
				{
					free(objectTypeInfo);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* If it's not a file handle, go to next one (as we're only interested in file handles) */
				if (wcscmp(objectTypeInfo->Name.Buffer, L"File"))
				{
					free(objectTypeInfo);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* Identify the filename from the handle we're looking at */
				WCHAR* wHandleFileName = new WCHAR[MAX_PATH]();

				if (!GetFileNameFromHandle(dupHandle, wHandleFileName))
				{
					free(objectTypeInfo);
					free(wHandleFileName);
					CloseHandle(processHandle);
					CloseHandle(dupHandle);
					continue;
				}

				/* This is where we add our findings to the database */
				iCurrentProcess_ArrayIndex = -1;

				/* Check whether we've already got an entry for the process we're looking at */
				for (int j = 0; j < (MAX_PROCESSES - 1); j++)
					if (iProcessArray[j][PROCESS_ARRAY_INDEX] == handle.ProcessId)
						iCurrentProcess_ArrayIndex = j;

				/* If not, create a new entry for the process associated with the current handle */
				if (iCurrentProcess_ArrayIndex == -1)
					for (int j = 0; j < (MAX_PROCESSES - 1); j++)
						if (iProcessArray[j][PROCESS_ARRAY_INDEX] == -1)
						{
							iProcessArray[j][PROCESS_ARRAY_INDEX] = handle.ProcessId;
							iCurrentProcess_ArrayIndex = j;
							break;
						}

				/* If there's more than MAX_PROCESSES, throw an error
					TODO: Tidy this up, identify number of running processes dynamically and set array size accordingly */
				if (iCurrentProcess_ArrayIndex == -1)
				{
					printf("Error: Too many processes running!\n");
					return 1;
				}

				/* Look through the handle array, to see whether the filename can be found */
				WCHAR cCurrentHandleText[MAX_PATH];
				for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
				{
					/* If we hit NULL, there are no more to find, so add ours */
					swprintf_s(cCurrentHandleText, MAX_PATH, L"%ls", wHandleFileName);

					if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")){
						wcscpy_s(cHandleArray[iCurrentProcess_ArrayIndex][j], cCurrentHandleText);
						break;
					}
					/* If we find ours, then stop searching */
					else if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], cCurrentHandleText))
						break;
				}

				/* If it's the first (or last) cycle, tally how many entries in the handle array for this
					particular process we have so far */

				if (iCycleCounter == 1)
					for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
						if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")){
							iProcessArray[iCurrentProcess_ArrayIndex][PROCESS_ARRAY_COUNT_START_CYCLE] = (j - 1);
							break;
						}

				if (iCycleCounter == dNumberCycles)
					for (int j = 0; j < (MAX_FILE_HANDLES - 1); j++)
						if (!wcscmp(cHandleArray[iCurrentProcess_ArrayIndex][j], L"")) {
							iProcessArray[iCurrentProcess_ArrayIndex][PROCESS_ARRAY_COUNT_END_CYCLE] = (j - 1);
							break;
						}

				free(objectTypeInfo);
				free(wHandleFileName);
				CloseHandle(dupHandle);
				CloseHandle(processHandle);
			}
			free(handleInfo);

			/* If the iteration pause is not 0, sleep for the requested time [Default: 1000ms] */
			if (dIterationPause)
				Sleep(dIterationPause);

			/* If /verbose active - inform user which cycle we are on */
			if (bVerbose)
				if (iCycleCounter == 1)
					printf("Verbose Info: Completed cycle %d", iCycleCounter);
				else if (iCycleCounter == dNumberCycles)
					printf(" %d\n", iCycleCounter);
				else
					printf(" %d", iCycleCounter);
		}

		/* If /verbose active - inform user we are now starting a review */
		if (bVerbose)
			printf("Verbose Info: Cycles completed, beginning review\n");

		/* Check if any of them met threshold*/
		for (int j = 0; j < (MAX_PROCESSES - 1); j++)
		{
			if (iProcessArray[j][PROCESS_ARRAY_COUNT_END_CYCLE] < iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE])
				continue;

			/* dHandleDelta is the difference between number of handles for a process from first cycle to the last one  */
			DWORD dHandleDelta = (iProcessArray[j][PROCESS_ARRAY_COUNT_END_CYCLE] - iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE]);

			/* Check whether the delta is equal or above the threshold */
			if (dHandleDelta >= dHandleChangeThreshold)
			{
				HANDLE pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, iProcessArray[j][PROCESS_ARRAY_INDEX]);
				TCHAR tProcessName[MAX_PATH];
				GetModuleFileNameEx(pHandle, 0, tProcessName, MAX_PATH);
				CloseHandle(pHandle);

				/* If we don't want signed, yet it is signed, skip... */
				if (!bIncludeSigned && (is_signed(tProcessName) == 0))
				{
					if (bVerbose)
						wprintf(L"Verbose Info: Skipping alert on %s (%d) despite trigger, as it is signed (use /signed to alert on signed executables too)\n", tProcessName, iProcessArray[j][PROCESS_ARRAY_INDEX]);
					continue;
				}

				/* Inform the user if we have a suspicious process */
				wprintf(L"Alert! Process: %s (%d) has had a suspicious number of handles (%d) created in the last cycle\nNew handles created during this cycle:\n", tProcessName, iProcessArray[j][PROCESS_ARRAY_INDEX], dHandleDelta);

				for (DWORD k = 1; k <= dHandleDelta; k++)
					wprintf(L"%s\n", cHandleArray[j][iProcessArray[j][PROCESS_ARRAY_COUNT_START_CYCLE] + k]);

				if (bSuspendProcess)
				{

					printf("Info: Attempting to suspend process %d\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);

					/* Attach debugger to process (freeze it!)*/
					if (!DebugActiveProcess(iProcessArray[j][PROCESS_ARRAY_INDEX]))
					{
						printf("Info: Could not attach to process %d as a debugger\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);
					}
					else
					{
						DebugSetProcessKillOnExit(FALSE);

						printf("Info: Successfully attached to process %d as debugger\n", iProcessArray[j][PROCESS_ARRAY_INDEX]);
						printf("Info: It will remain frozen until this process is terminated\n");
					}
				}

				printf("------------------------------------------------------------------------------\n");

			}
		}

		if (bVerbose)
			printf("Verbose Info: Review complete\n");

		free(cHandleArray);

	}

	return 0;
}
示例#26
0
bool Type::is_integral_number() const
{ return is_signed() || is_unsigned();}