Пример #1
0
/* Get first and second integer numbers, store in foreground and background fields of @a style. */
static void get_keyfile_int(GKeyFile *config, GKeyFile *configh, const gchar *section,
							const gchar *key, gint fdefault_val, gint sdefault_val,
							GeanyLexerStyle *style)
{
	gchar **list;
	gsize len;
	GeanyLexerStyle def = {fdefault_val, sdefault_val, FALSE, FALSE};

	g_return_if_fail(config);
	g_return_if_fail(configh);
	g_return_if_fail(section);
	g_return_if_fail(key);

	list = g_key_file_get_string_list(configh, section, key, &len, NULL);
	if (list == NULL)
		list = g_key_file_get_string_list(config, section, key, &len, NULL);

	*style = def;
	if (!list)
		return;

	if (list[0])
	{
		convert_int(list[0], &style->foreground);
		if (list[1])
		{
			convert_int(list[1], &style->background);
		}
	}
	g_strfreev(list);
}
Пример #2
0
int convert_ijk(char const *const s, int* i, int* j, double* k, int* n) {
  int ret;
  const char* sp = s;

  if( (ret = convert_int(&sp, i)) != 0 )
    return ret;

  if( (ret = convert_int(&sp, j)) != 0 )
    return ret;

  return convert_k(sp, k, n);
}
Пример #3
0
int PMI2_Init(int *spawned, int *size, int *rank, int *appnum)
{
    pmix_value_t *kv;
    pmix_status_t rc;

    if (PMIX_SUCCESS != PMIx_Init(&myproc)) {
        return PMI2_ERR_INIT;
    }

    if (NULL != size) {
        /* get the universe size - this will likely pull
         * down all attributes assigned to the job, thus
         * making all subsequent "get" operations purely
         * local */
        if (PMIX_SUCCESS == PMIx_Get(&myproc, PMIX_UNIV_SIZE, NULL, 0, &kv)) {
            rc = convert_int(size, kv);
            PMIX_VALUE_RELEASE(kv);
            return convert_err(rc);
        } else {
            /* cannot continue without this info */
            return PMI2_ERR_INIT;
        }
    }

    if (NULL != spawned) {
        /* get the spawned flag */
        if (PMIX_SUCCESS == PMIx_Get(&myproc, PMIX_SPAWNED, NULL, 0, &kv)) {
            rc = convert_int(spawned, kv);
            PMIX_VALUE_RELEASE(kv);
            return convert_err(rc);
        } else {
            /* if not found, default to not spawned */
            *spawned = 0;
        }
    }

    if (NULL != appnum) {
        /* get our appnum */
        if (PMIX_SUCCESS == PMIx_Get(&myproc, PMIX_APPNUM, NULL, 0, &kv)) {
            rc = convert_int(appnum, kv);
            PMIX_VALUE_RELEASE(kv);
            return convert_err(rc);
        } else {
            /* if not found, default to 0 */
            *appnum = 0;
        }
    }

    return PMI2_SUCCESS;
}
Пример #4
0
void		fork_(t_charu *a, t_chp *chp)
{
	int		i;
	int		j;

	i = -1;
	if (chp->f > 0)
		return ;
	j = convert_int(chp->cmd->args, 2) % IDX_MOD;
	add(chp);
	chp->prev->PC = new_add(chp->PC + j, a);
	chp->prev->reg[0] = g_pid;
	chp->prev->pid = g_pid++;
	while (++i < REG_NUMBER)
		chp->prev->reg[i] = chp->reg[i];
	chp->prev->cycle = 0;
	chp->prev->carry = chp->carry;
	chp->prev->f = chp->pid;
	chp->prev->cycle_to_die = chp->cycle_to_die;
	chp->prev->cmd = malloc(sizeof(*(chp->prev->cmd)));
	if (chp->prev->cmd == NULL)
		ft_er("Malloc() Fail");
	chp->prev->cmd->type_args[0] = 0;
	chp->prev->cmd->type_args[1] = 0;
	chp->prev->cmd->type_args[2] = 0;
}
Пример #5
0
void		lfork(t_charu *a, t_chp *chp)
{
	int		i;
	int		j;

	i = 1;
	j = convert_int(chp->cmd->args, 2);
	chp->carry = j ? 0 : 1;
	add(chp);
	chp->prev->PC = new_add(chp->PC + j, a);
	chp->prev->reg[0] = g_pid;
	chp->prev->pid = g_pid++;
	while (i < REG_NUMBER)
	{
		chp->prev->reg[i] = chp->reg[i];
		i++;
	}
	chp->prev->cycle = 0;
	chp->prev->carry = chp->carry;
	chp->prev->f = chp->pid;
	chp->prev->cycle_to_die = chp->cycle_to_die;
	chp->prev->cmd = malloc(sizeof(*(chp->prev->cmd)));
	if (chp->prev->cmd == NULL)
		ft_er("Malloc() fail");
	chp->prev->cmd->type_args[0] = 0;
	chp->prev->cmd->type_args[1] = 0;
	chp->prev->cmd->type_args[2] = 0;
}
Пример #6
0
Файл: pmi2.c Проект: AT95/ompi
int PMI2_Info_GetSize(int *size)
{
    pmix_status_t rc = PMIX_ERROR;
    pmix_value_t *val;
    pmix_info_t info[1];
    bool  val_optinal = 1;

    PMI2_CHECK();

    if (NULL == size) {
        return PMI2_ERR_INVALID_ARGS;
    }

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    if (PMIX_SUCCESS == PMIx_Get(&myproc, PMIX_LOCAL_SIZE, info, 1, &val)) {
        rc = convert_int(size, val);
        PMIX_VALUE_RELEASE(val);
    }

    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #7
0
void RateMeyerHaeseler::readRateFile(char *rate_file) {
	cout << "Reading site-specific rate file " << rate_file << " ..." << endl;
	try {
		ifstream in;
		in.exceptions(ios::failbit | ios::badbit);
		in.open(rate_file);
		char line[256];
		int site, i;
		double rate;
		int nsites = phylo_tree->aln->getNSite();
		resize(phylo_tree->aln->getNPattern(), -1.0);
		int saturated_sites = 0, saturated_ptn = 0;

		in.getline(line, sizeof(line));
		//if (strncmp(line, "Site", 4) != 0) throw "Wrong header line";

		for (i = 0; i < nsites; i++) {
			in.getline(line, sizeof(line));
			stringstream ss(line);
			string tmp;
			ss >> tmp;
			site = convert_int(tmp.c_str());
			if (site <= 0 || site > nsites) throw "Wrong site number (must be between 1 and #sites)";
			site--;
			ss >> tmp;
			rate = convert_double(tmp.c_str());
			if (rate < 0.0) throw "Negative rate not allowed";
			if (rate <= 0.0) rate = MIN_SITE_RATE;
			int ptn = phylo_tree->aln->getPatternID(site);
			if (rate >= MAX_SITE_RATE) {
				rate = MAX_SITE_RATE; 
				saturated_sites += phylo_tree->aln->at(ptn).frequency; 
				saturated_ptn ++;
			}
			at(ptn) = rate;
		}
		in.clear();
		// set the failbit again
		in.exceptions(ios::failbit | ios::badbit);
		in.close();

		for (i = 0; i < size(); i++)
			if (at(i) < 0.0) throw "Some site has no rate information";

		if (saturated_sites) {
			stringstream str;
			str << saturated_sites << " sites (" << saturated_ptn << " patterns) show too high rates (>=" << MAX_SITE_RATE << ")";
			outWarning(str.str());
		}
	} catch (const char *str) {
		outError(str);
	} catch (string str) {
		outError(str);
	} catch(ios::failure) {
		outError(ERR_READ_INPUT);
	}
}
Пример #8
0
PMIX_EXPORT int PMI_Init(int *spawned)
{
    pmix_status_t rc = PMIX_SUCCESS;
    pmix_value_t *val;
    pmix_proc_t proc;
    pmix_info_t info[1];
    bool  val_optinal = 1;

    if (PMIX_SUCCESS != (rc = PMIx_Init(&myproc, NULL, 0))) {
        /* if we didn't see a PMIx server (e.g., missing envar),
         * then allow us to run as a singleton */
        if (PMIX_ERR_INVALID_NAMESPACE == rc) {
            if (NULL != spawned) {
                *spawned = 0;
            }
            pmi_singleton = true;
            (void)strncpy(myproc.nspace, "1234", PMIX_MAX_NSLEN);
            myproc.rank = 0;
            pmi_init = 1;
            return PMI_SUCCESS;
        }
        return PMI_ERR_INIT;
    }

    /* getting internal key requires special rank value */
    memcpy(&proc, &myproc, sizeof(myproc));
    proc.rank = PMIX_RANK_UNDEF;

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    if (NULL != spawned) {
        /* get the spawned flag */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_SPAWNED, info, 1, &val)) {
            rc = convert_int(spawned, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* if not found, default to not spawned */
            *spawned = 0;
        }
    }
    pmi_init = 1;

    rc = PMIX_SUCCESS;

error:
    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #9
0
void convert_int(int x)
{
	if(x<0)
	{
		x = x*(-1);
		USART_puts(USART2,'-');
	}
	
    if(x>=10)
        convert_int(x/10);

    x = x%10;
    USART_puts(USART2,x+'0');
}
Пример #10
0
// function used to go from int distances to float and then back
// when finding distance to an individual polygon
Distance3i distance_trianglei(const int3 p, const int3* poly) {
  float3 poly_float3[3];
  for (int i = 0; i < 3; ++i) {
    /* poly_float3[i] = (float3)(poly[i].x, poly[i].y, poly[i].z); */
    poly_float3[i] = convert_float3(poly[i]);
  }
  Distance3f d =
      /* distance_trianglef((float3)(p.x, p.y, p.z), poly_float3); */
      distance_trianglef(convert_float3(p), poly_float3);
  return make_dist3(
      // convert_int_rte(d.d),
      // convert_int3_rte(d.p));
      convert_int(d.d),
      convert_int3(d.p));
}
Пример #11
0
void NGSAlignment::readFritzFile(const char *filename) {
    cout << "Reading Fritz file " << filename << " ..." << endl;
    try {
        ifstream in;
        in.exceptions(ios::failbit | ios::badbit);
        in.open(filename);
        in.clear();
        int i, total_size;
        string tmp;
        in >> tmp;
        ncategory = convert_int(tmp.c_str());
        if (ncategory < 1) throw "Wrong number of positions";
        in >> tmp;
        num_states = convert_int(tmp.c_str());
        total_size = ncategory*num_states*num_states;
        if (num_states < 1) throw "Wrong number of states";
        pair_freq = new double[total_size];
        for (i=0; i < total_size; i++) {
            in >> tmp;
            double count = convert_double(tmp.c_str());
            if (count < 0) throw "Wrong count";
            pair_freq[i] = count;
        }
        // set the failbit again
        in.exceptions(ios::failbit | ios::badbit);
        in.close();
    } catch (const char *str) {
        outError(str);
    } catch (string str) {
        outError(str);
    } catch (ios::failure) {
        outError(ERR_READ_INPUT);
    }

    cout << ncategory << " matrices of size " << num_states << endl;
}
Пример #12
0
void		st(t_charu *a, t_chp *chp)
{
	int		i;
	int		j;

	i = giv_para_val(chp, chp->cmd, 0, a);
	j = giv_para_val(chp, chp->cmd, 1, a);
	if (chp->cmd->type_args[0] == 1)
		i = chp->reg[giv_reg_nbr(i)];
	if (chp->cmd->type_args[1] == 1)
		chp->reg[giv_reg_nbr(j)] = i;
	else if (chp->cmd->type_args[1] == 2)
	{
		j = convert_int(chp->cmd->args + chp->cmd->type_args[0], 2);
		stock_conv_nbr(chp->PC+ j, a, i);
	}
}
Пример #13
0
Distance3i distance_geom3(
    const int3 p, global const int* geometry, global const int3* verts) {
  // Distance3i best = { INT_MAX, (int3)(0, 0, 0) };
  Distance3i best = { INT_MAX, make_int3(0, 0, 0) };
  const int num_tris = geometry[1];
  const Triangle* tris = (Triangle*)(geometry+2);
  for (int j = 0; j < num_tris; ++j) {
    Triangle t = tris[j];
    const int3 tri_verts[3] =
        { (verts[t.s[0]]),
          (verts[t.s[1]]),
          (verts[t.s[2]]) };
    int3 set_verts[3];
    const int num_unique = find_unique(tri_verts, set_verts);

    if (num_unique == 3) {
      best = min_pair3i(best, distance_trianglei(p, tri_verts));
    } else {
      // Degenerate triangle
      if (num_unique == 1) {
        // Degenerate to a point
        int3 closest = tri_verts[0];
        float3 closest_d = convert_float3(closest);
        float3 p_d = convert_float3(p);
        int dist = (int)(fast_length(p_d-closest_d)+0.5f);
        best = min_pair3i(best, make_dist3(dist, closest));
      } else {
        // Degenerate to a line
        int3 a = set_verts[0];
        int3 b = set_verts[1];
        Distance3f dist = distance_line3(convert_float3(p),
                                        convert_float3(a),
                                        convert_float3(b));
        Distance3i disti = make_dist3(
            // convert_int_rte(dist.d),
            // convert_int3_rte(dist.p));
            convert_int(dist.d),
            convert_int3(dist.p));
        best = min_pair3i(best, disti);
      }
    }
  }
  return best;
}
Пример #14
0
PMIX_EXPORT int PMI_Get_appnum(int *appnum)
{
    pmix_status_t rc = PMIX_SUCCESS;
    pmix_value_t *val;
    pmix_info_t info[1];
    bool  val_optinal = 1;
    pmix_proc_t proc = myproc;
    proc.rank = PMIX_RANK_WILDCARD;

    PMI_CHECK();

    if (NULL == appnum) {
        return PMI_ERR_INVALID_ARG;
    }

    if (pmi_singleton) {
        *appnum = 0;
        return PMI_SUCCESS;
    }

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    rc = PMIx_Get(&proc, PMIX_APPNUM, info, 1, &val);
    if (PMIX_SUCCESS == rc) {
        rc = convert_int(appnum, val);
        PMIX_VALUE_RELEASE(val);
    } else if( PMIX_ERR_NOT_FOUND == rc ){
        /* this is optional value, set to 0 */
        *appnum = 0;
        rc = PMIX_SUCCESS;
    }

    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #15
0
PMIX_EXPORT int PMI_Get_clique_size(int *size)
{
    pmix_status_t rc = PMIX_SUCCESS;
    pmix_value_t *val;
    pmix_info_t info[1];
    bool  val_optinal = 1;
    pmix_proc_t proc = myproc;
    proc.rank = PMIX_RANK_WILDCARD;

    PMI_CHECK();

    if (NULL == size) {
        return PMI_ERR_INVALID_ARG;
    }

    if (pmi_singleton) {
        *size = 1;
        return PMI_SUCCESS;
    }

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    rc = PMIx_Get(&proc, PMIX_LOCAL_SIZE, info, 1, &val);
    if (PMIX_SUCCESS == rc) {
        rc = convert_int(size, val);
        PMIX_VALUE_RELEASE(val);
    }

    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #16
0
PMIX_EXPORT int PMI2_Init(int *spawned, int *size, int *rank, int *appnum)
{
    pmix_status_t rc = PMIX_SUCCESS;
    pmix_value_t *val;
    pmix_info_t info[1];
    bool  val_optinal = 1;
    pmix_proc_t proc = myproc;
    proc.rank = PMIX_RANK_WILDCARD;

    if (PMIX_SUCCESS != (rc = PMIx_Init(&myproc, NULL, 0))) {
        /* if we didn't see a PMIx server (e.g., missing envar),
         * then allow us to run as a singleton */
        if (PMIX_ERR_INVALID_NAMESPACE == rc) {
            if (NULL != spawned) {
                *spawned = 0;
            }
            if (NULL != size) {
                *size = 1;
            }
            if (NULL != rank) {
                *rank = 0;
            }
            if (NULL != appnum) {
                *appnum = 0;
            }
            pmi2_singleton = true;
            (void)strncpy(myproc.nspace, "1234", PMIX_MAX_NSLEN);
            myproc.rank = 0;
            pmi2_init = 1;
            return PMI2_SUCCESS;
        }
        return PMI2_ERR_INIT;
    }

    /* get the rank */
    *rank = myproc.rank;

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    if (NULL != size) {
        /* get the universe size - this will likely pull
         * down all attributes assigned to the job, thus
         * making all subsequent "get" operations purely
         * local */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_UNIV_SIZE, info, 1, &val)) {
            rc = convert_int(size, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* cannot continue without this info */
            rc = PMIX_ERR_INIT;
            goto error;
        }
    }

    if (NULL != spawned) {
        /* get the spawned flag */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_SPAWNED, info, 1, &val)) {
            rc = convert_int(spawned, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* if not found, default to not spawned */
            *spawned = 0;
        }
    }

    if (NULL != appnum) {
        /* get our appnum */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_APPNUM, info, 1, &val)) {
            rc = convert_int(appnum, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* if not found, default to 0 */
            *appnum = 0;
        }
    }
    pmi2_init = 1;

    rc = PMIX_SUCCESS;

error:
    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #17
0
/* A half-arsed and buggy, but good-enough, implementation of
   printf. */
static
UInt vprintf_wrk ( void(*sink)(char),
                   const char* format,
                   va_list ap )
{
#  define PUT(_ch)  \
      do { sink(_ch); nout++; } \
      while (0)

#  define PAD(_n) \
      do { Int _qq = (_n); for (; _qq > 0; _qq--) PUT(padchar); } \
      while (0)

#  define PUTSTR(_str) \
      do { const char* _qq = _str; for (; *_qq; _qq++) PUT(*_qq); } \
      while (0)

   const char* saved_format;
   Bool   longlong, ljustify;
   char  padchar;
   Int    fwidth, nout, len1, len2, len3;
   char  intbuf[100];  /* big enough for a 64-bit # in base 2 */

   nout = 0;
   while (1) {

      if (!format)
         break;
      if (*format == 0) 
         break;

      if (*format != '%') {
         PUT(*format); 
         format++;
         continue;
      }

      saved_format = format;
      longlong = False;
      ljustify = False;
      padchar = ' ';
      fwidth = 0;
      format++;

      if (*format == '-') {
         format++;
         ljustify = True;
      }
      if (*format == '0') {
         format++;
         padchar = '0';
      }
      while (*format >= '0' && *format <= '9') {
         fwidth = fwidth * 10 + (*format - '0');
         format++;
      }
      if (*format == 'l') {
         format++;
         if (*format == 'l') {
            format++;
           longlong = True;
         }
      }

      switch (*format) {
         case 's': {
            const char* str = va_arg(ap, const char*);
            if (str == NULL)
               str = "(null)";
            len1 = len3 = 0;
            len2 = vex_strlen(str);
            if (fwidth > len2) { len1 = ljustify ? 0 : fwidth-len2;
                                 len3 = ljustify ? fwidth-len2 : 0; }
            PAD(len1); PUTSTR(str); PAD(len3);
            break;
         }
         case 'c': {
            char c = (char)va_arg(ap, int);
            char str[2];
            str[0] = c;
            str[1] = 0;
            len1 = len3 = 0;
            len2 = vex_strlen(str);
            if (fwidth > len2) { len1 = ljustify ? 0 : fwidth-len2;
                                 len3 = ljustify ? fwidth-len2 : 0; }
            PAD(len1); PUTSTR(str); PAD(len3);
            break;
         }
         case 'd': {
            Long l;
            if (longlong) {
               l = va_arg(ap, Long);
            } else {
               l = (Long)va_arg(ap, Int);
            }
            convert_int(intbuf, l, 10/*base*/, True/*signed*/,
                                False/*irrelevant*/);
            len1 = len3 = 0;
            len2 = vex_strlen(intbuf);
            if (fwidth > len2) { len1 = ljustify ? 0 : fwidth-len2;
                                 len3 = ljustify ? fwidth-len2 : 0; }
            PAD(len1); PUTSTR(intbuf); PAD(len3);
            break;
         }
         case 'u': 
         case 'x': 
         case 'X': {
            Int   base = *format == 'u' ? 10 : 16;
            Bool  hexcaps = True; /* *format == 'X'; */
            ULong l;
            if (longlong) {
               l = va_arg(ap, ULong);
            } else {
               l = (ULong)va_arg(ap, UInt);
            }
            convert_int(intbuf, l, base, False/*unsigned*/, hexcaps);
            len1 = len3 = 0;
            len2 = vex_strlen(intbuf);
            if (fwidth > len2) { len1 = ljustify ? 0 : fwidth-len2;
                                 len3 = ljustify ? fwidth-len2 : 0; }
            PAD(len1); PUTSTR(intbuf); PAD(len3);
            break;
         }
         case 'p': 
         case 'P': {
            Bool hexcaps = toBool(*format == 'P');
            ULong l = Ptr_to_ULong( va_arg(ap, void*) );
            convert_int(intbuf, l, 16/*base*/, False/*unsigned*/, hexcaps);
            len1 = len3 = 0;
            len2 = vex_strlen(intbuf)+2;
            if (fwidth > len2) { len1 = ljustify ? 0 : fwidth-len2;
                                 len3 = ljustify ? fwidth-len2 : 0; }
            PAD(len1); PUT('0'); PUT('x'); PUTSTR(intbuf); PAD(len3);
            break;
         }
         case '%': {
            PUT('%');
            break;
         }
         default:
            /* no idea what it is.  Print the format literally and
               move on. */
            while (saved_format <= format) {
               PUT(*saved_format);
               saved_format++;
            }
            break;
      }

      format++;

   }

   return nout;

#  undef PUT
#  undef PAD
#  undef PUTSTR
}
Пример #18
0
static inline int readmm_header(FILE* f,
  int* object, int* format, int* datatype, int* symmetry,
  int* rows, int* cols, int* nz,
  char** comments) {

  assert(f != NULL);

  // valid field types
  const char* header[]      = { "%%matrixmarket", NULL };
  const char* objects[]     = { "matrix", NULL };
  const char* formats[]     = { "array", "coordinate", NULL };
  const char* datatypes[]   = { "real", "integer", "complex", "pattern", NULL };
  const char* symmetries[]  = { "general", "symmetric", "skew-symmetric", "hermitian", NULL };

  const int FIELDS = 5;
  int dummy;
  char const **const fields[] = { header, objects, formats, datatypes, symmetries, NULL};
  int *             outputs[] = { &dummy, object,  format,  datatype,  symmetry,   NULL };

  const int CHARS = 1025;
  char line[CHARS];

  // read the first line of the file (stops at EOF or newline, null terminated)
  const char* lp = fgets(line, CHARS, f);
  if(lp == NULL)
    return -1; // error or EOF w/ no characters

  // initialize results
  int i;
  for(i=0; i<FIELDS; i++) {
    *(outputs[i]) = -1;
  }
  *rows = *cols = *nz = 0;
  if(comments != NULL) {
    free(*comments);
    *comments = NULL;
  }

  // loop through the strings to decode the header
  int ret = 0;
  char const **fp = fields[0];
  int fi = 0;
  lp = line; // reset string ptr to start-of-line
  while((fp != NULL) && (ret == 0)) {
    int sp = 0;
    while((fp[sp] != NULL) && (sp >= 0)) {
      // compare the string
      const size_t chars_in_string = strlen(fp[sp]);
      if(strncasecmp(lp, fp[sp], chars_in_string) != 0) {
	sp++;
	continue;
      }

      // if it matches, check that the next character is ' ', '\n'
      char const *const lpt = lp + chars_in_string; // temporary pointer for looking ahead
      if(!isspace(*lpt)) {
	sp++;
	continue;
      }

      // on match save result and set sp = -1 to break out of the loop
      lp += chars_in_string;
      *(outputs[fi]) = sp;
      sp = -1;
    }
    // see if we recognized this field, no need to go further if we're lost
    if(*outputs[fi] == -1)
      ret = -2; // unrecognized format
    fi++;
    fp = fields[fi];

    // and consume any leading spaces before looking at the next string
    while(isblank(*lp)) lp++;
  }
  // no need to go further if we're already confused
  if(ret != 0)
    return ret;

  // store comments if requested
  if(comments != NULL) {
    assert(0); // TODO unfinished code
  }
  else { // just get past the comments
    do {
      // check for long lines which would screw up this parsing
      // the first line ending aught to be in here somewhere...
      while(isprint(*lp)) lp++;
      if(!is_eol(*lp))
        return -3; // line too long

      // read in the next line
      lp = fgets(line, CHARS, f);
    } while((*lp == '%') || is_eol(*lp));
  }
  // lp now points to the first non-blank line after the comments

  // find matrix dimensions
  if(*format == 0) { // dense array, expecting "  <rows> <columns>"
    int err1 = convert_int(&lp, rows);
    int err2 = convert_int(&lp, cols);
    *nz = (*rows) * (*cols);

    if(err1 | err2)
      return -2;
  }
  else { // must be COO format, expecting "  <rows> <columns> <non-zeros>"
    int err1 = convert_int(&lp, rows);
    int err2 = convert_int(&lp, cols);
    int err3 = convert_int(&lp, nz);

    if(err1 | err2 | err3)
      return -2;
  }

  // final check for end of line
  while(isblank(*lp)) lp++;
  if(!is_eol(*lp))
    return -3; // line too long

  return ret;
}
Пример #19
0
int main ( int argc, char* argv[] )
{
  // We have to be told where MPD is running.
  char* host = "guanaco"; // Well, that's mine. Maybe this should be localhost.
  int   port = 6600;      // The standard MPD port.
  // Default database.
  char* database = "album_art.sqlite3";

  bool bad_argument = false;
  int c;

  // Start the logger.
  main_data.logger = log_init();

  while ( 1 ) {
    int option_index = 0;
    static struct option long_options[] = {
      { "host", required_argument, 0, 'h' },
      { "port", required_argument, 0, 'p' },
      { "database", required_argument, 0, 'd' },
      { 0,      0,                 0, 0 }
    };

    c = getopt_long( argc, argv, "h:p:d:", long_options, &option_index );

    if ( c == -1 ) {
      break;
    }

    switch ( c ) {
    case 'h':
      if ( *optarg == '\0' ) {
	bad_argument = true;
	printf( "--host argument must be non-empty\n" );
      }
      host = optarg;
      break;
    case 'p':
#if 0
      port = optarg;
      {
	int port_n = convert_int( optarg );
	if ( errno != 0 ) {
	  bad_argument = true;
	  printf( "--port argument was not a valid integer: '%s' (%s)\n",
		  optarg, strerror( errno ) );
	}
	if ( port_n <= 0 ) {
	  bad_argument = true;
	  printf( "--port argument must be positive (%s)\n", port );
	}
      }
#else
      {
	port = convert_int( optarg );
	if ( errno != 0 ) {
	  bad_argument = true;
	  printf( "--port argument was not a valid integer: '%s' (%s)\n",
		  optarg, strerror( errno ) );
	}
	if ( port <= 0 ) {
	  bad_argument = true;
	  printf( "--port argument must be positive (%d)\n", port );
	}
      }
#endif
      break;
    case 'd':
      if ( *optarg == '\0' ) {
	bad_argument = true;
	printf( "--database argument must be non-empty\n" );
      }
      database = optarg;
      break;
    default:
      bad_argument = true;
      printf( "?? getopt returned character code 0%o ??\n", c );
    }
  }
  if ( bad_argument ) {
    printf( USAGE, argv[0] );
    return 1;
  }

  log_message_info( main_data.logger, "MPD host: '%s'", host );
  log_message_info( main_data.logger, "MPD port: '%d'", port );
  log_message_info( main_data.logger, "Database: '%s'", database );

  main_data.mpd = mpd_create( host, port, main_data.logger );

  if ( mpd_status( main_data.mpd ) < 0 ) {
    printf( USAGE, argv[0] );
    return 1;
  }

  // Try to open the image database connection.

  main_data.image_db = image_db_create( database, main_data.logger );

  // If we get this far, we can try to initialize the graphics.

  main_data.display = display_init( main_data.image_db, main_data.mpd );

  if ( display_status( main_data.display ) < 0 ) {
    return 1;
  }

  // Well, after all that, we can now start polling MPD to see what's up.

  main_data.loop = g_main_loop_new( NULL, FALSE );

  // Poll MPD periodically.
  (void)g_timeout_add_seconds( 1, poll_mpd, &main_data );

  // Also try to poll the buttons on the Pibrella (if it is configured
  // properly).
  add_pibrella_button10( &main_data );
  add_pibrella_button11( &main_data );

  // Mouse or touch screen events.
  add_event( &main_data );

  g_main_loop_run( main_data.loop );

  log_message_info( main_data.logger, "Done with main loop. Cleaning up." );

  g_main_loop_unref( main_data.loop );

  display_close( main_data.display );

  mpd_free( main_data.mpd );

  log_close( main_data.logger );

  return 0;
}
Пример #20
0
Файл: pmi2.c Проект: AT95/ompi
int PMI2_Init(int *spawned, int *size, int *rank, int *appnum)
{
    pmix_status_t rc = PMIX_SUCCESS;
    pmix_value_t *val;
    pmix_proc_t proc;
    pmix_info_t info[1];
    bool  val_optinal = 1;

    if (PMIX_SUCCESS != PMIx_Init(&myproc)) {
        return PMI2_ERR_INIT;
    }

    /* get the rank */
    *rank = myproc.rank;

    /* getting internal key requires special rank value */
    memcpy(&proc, &myproc, sizeof(myproc));
    proc.rank = PMIX_RANK_UNDEF;

    /* set controlling parameters
     * PMIX_OPTIONAL - expect that these keys should be available on startup
     */
    PMIX_INFO_CONSTRUCT(&info[0]);
    PMIX_INFO_LOAD(&info[0], PMIX_OPTIONAL, &val_optinal, PMIX_BOOL);

    if (NULL != size) {
        /* get the universe size - this will likely pull
         * down all attributes assigned to the job, thus
         * making all subsequent "get" operations purely
         * local */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_UNIV_SIZE, info, 1, &val)) {
            rc = convert_int(size, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* cannot continue without this info */
            rc = PMIX_ERR_INIT;
            goto error;
        }
    }

    if (NULL != spawned) {
        /* get the spawned flag */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_SPAWNED, info, 1, &val)) {
            rc = convert_int(spawned, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* if not found, default to not spawned */
            *spawned = 0;
        }
    }

    if (NULL != appnum) {
        /* get our appnum */
        if (PMIX_SUCCESS == PMIx_Get(&proc, PMIX_APPNUM, info, 1, &val)) {
            rc = convert_int(appnum, val);
            PMIX_VALUE_RELEASE(val);
            if (PMIX_SUCCESS != rc) {
                goto error;
            }
        } else {
            /* if not found, default to 0 */
            *appnum = 0;
        }
    }
    pmi2_init = 1;

    rc = PMIX_SUCCESS;

error:
    PMIX_INFO_DESTRUCT(&info[0]);

    return convert_err(rc);
}
Пример #21
0
/* convert - The main conversion function. *format points at a '%'.
   - str contains the output string. The original buffer was 'size' large
     (but *str is the current insert position inside the buffer).
   - *n is the offset inside the output buffer of the current insert position,
     or: (str - start_str).
   - args is an array of arguments passed to snprintf.
   - *thisarg is the next argument to process. */
static const char *convert(char *str, unsigned size, const char *format, int *n, arg_t *args, int *thisarg) {
  pf_state_t s;
  memset((uint8_t*)&s, 0, sizeof(pf_state_t));
  s.precision = 1;
  
  char buf[BUFSZ];

  while (*++format) {
    switch (*format) {

    case '%': /* %% = simple escaped % */
      return cat_char(str, size, n, '%');
    
    case '#': /* Alternate form flag */
      s.alternate_form = 1;
      break;

    case '0': /* Zero pad */
      s.zero_pad = 1;
      break;

    case '-': /* Left justify */
      s.left_justify = 1;
      break;

    case ' ': /* Prefix any positive signed conversion with a space */
      s.pos_sign_prefix_space = 1;
      break;

    case '+': /* Prefix any positive signed conversion with a + */
      s.pos_sign_prefix_plus = 1;
      break;

    case '1': case '2': case '3': case '4': case '5':
    case '6': case '7': case '8': case '9': case '*': {
      /* Number starting with nonzero or '*' is the minimum field width. */
      s.min_field_width = parse_direct_or_indirect_int(&format, args, thisarg);
      break;
    }
    
    case '.': /* Precision */
      ++format;
      s.precision = parse_direct_or_indirect_int(&format, args, thisarg);
      break;
    
    case 'd': case 'i':
      /* If precision is given, zero_pad must be disabled. */
      if (s.precision != 1) s.zero_pad = 0;
      convert_int(buf, BUFSZ, args[(*thisarg)++].i, 10, s, 1);
      pad_str(str, size, n, buf, 1, s, NULL);
      return format+1;
    case 'o':
      /* If precision is given, zero_pad must be disabled. */
      if (s.precision != 1) s.zero_pad = 0;
      convert_int(buf, BUFSZ, args[(*thisarg)++].u, 8, s, 0);
      pad_str(str, size, n, buf, 0, s, s.alternate_form ? "0" : NULL);
      return format+1;
    case 'u':
      /* If precision is given, zero_pad must be disabled. */
      if (s.precision != 1) s.zero_pad = 0;
      convert_int(buf, BUFSZ, (unsigned int)args[(*thisarg)++].i, 10, s, 0);
      pad_str(str, size, n, buf, 0, s, NULL);
      return format+1;
    case 'x':
      /* If precision is given, zero_pad must be disabled. */
      if (s.precision != 1) s.zero_pad = 0;
      convert_int(buf, BUFSZ, args[(*thisarg)++].u, 16, s, 0);
      pad_str(str, size, n, buf, 0, s, s.alternate_form ? "0x" : NULL);
      return format+1;
    case 'X':
      /* If precision is given, zero_pad must be disabled. */
      if (s.precision != 1) s.zero_pad = 0;
      s.transliterate_hex = 1;
      convert_int(buf, BUFSZ, args[(*thisarg)++].u, 16, s, 0);
      pad_str(str, size, n, buf, 0, s, s.alternate_form ? "0X" : NULL);
      return format+1;
    case 'c':
      s.zero_pad = 0;
      buf[0] = (char)args[(*thisarg)++].i;
      buf[1] = '\0';
      pad_str(str, size, n, buf, 0, s, NULL);
      return format+1;
    case 's': {
      s.zero_pad = 0;
      char *in = (char*)args[(*thisarg)++].p;
      if (!in) in = "<null>";
      pad_str(str, size, n, in, 0, s, NULL);
      return format+1;
    }
    case 'p': /* Equivalent to %#x */
      s.zero_pad = 0;
      convert_int(buf, BUFSZ, (uintptr_t)args[(*thisarg)++].p, 16, s, 0);
      pad_str(str, size, n, buf, 0, s, "0x");
      return format+1;
    case 'n': /* Write out the number of arguments converted. */
      s.zero_pad = 0;
      convert_int(buf, BUFSZ, (uintptr_t)*thisarg, 10, s, 0);
      pad_str(str, size, n, buf, 0, s, NULL);
      return format+1;

    case 'e': case 'E':
    case 'f': case 'F':
    case 'g': case 'G':
    case 'a': case 'A':
      pad_str(str, size, n, "???", 0, s, NULL);
      (*thisarg)++;
      return format+1;

    default: /* Shouldn't get here, but we don't have panic available so just try not to infinite loop. */
      return format;
    }
  }
  return format;
}
Пример #22
0
IMPLEMENT_HCONVERT_QVARIANT(int)
{
    return convert_int(val,hr);
}
Пример #23
0
static void put_data(int fd, char *null_buf, const CELL * cell,
		     int row, int n, int zeros_r_nulls)
{
    struct fileinfo *fcb = &R__.fileinfo[fd];
    int compressed = fcb->cellhd.compressed;
    int len = compressed ? sizeof(CELL) : fcb->nbytes;
    unsigned char *work_buf, *wk;
    ssize_t nwrite;

    if (row < 0 || row >= fcb->cellhd.rows)
	return;

    if (n <= 0)
	return;

    work_buf = G__alloca(fcb->cellhd.cols * sizeof(CELL) + 1);
    wk = work_buf;

    if (compressed)
	set_file_pointer(fd, row);

    if (compressed)
	wk++;

    convert_int(wk, null_buf, cell, n, len, zeros_r_nulls);

    if (compressed) {
	unsigned char *wk = work_buf + 1;
	int nbytes = count_bytes(wk, n, len);
	unsigned char *compressed_buf;
	int total;

	if (fcb->nbytes < nbytes)
	    fcb->nbytes = nbytes;

	/* first trim away zero high bytes */
	if (nbytes < len)
	    trim_bytes(wk, n, len, len - nbytes);

	total = nbytes * n;
	compressed_buf = G__alloca(total + 1);

	compressed_buf[0] = work_buf[0] = nbytes;

	/* then compress the data */
	nwrite = compressed == 1
	    ? rle_compress(compressed_buf + 1, work_buf + 1, n, nbytes)
	    : zlib_compress(compressed_buf + 1, work_buf + 1, n, nbytes);

	if (nwrite > 0) {
	    nwrite++;

	    if (write(fd, compressed_buf, nwrite) != nwrite)
		G_fatal_error(_("Error writing compressed data for row %d of <%s>"),
			      row, fcb->name);
	}
	else {
	    nwrite = nbytes * n + 1;
	    if (write(fd, work_buf, nwrite) != nwrite)
		G_fatal_error(_("Error writing compressed data for row %d of <%s>"),
			      row, fcb->name);
	}

	G__freea(compressed_buf);
    }
    else {
	nwrite = fcb->nbytes * n;

	if (write(fd, work_buf, nwrite) != nwrite)
	    G_fatal_error(_("Error writing uncompressed data for row %d of <%s>"),
			  row, fcb->name);
    }

    G__freea(work_buf);
}
Пример #24
0
int main(int argc, char *argv[])
{
	int i, err, partnum = 0, scb;
	Bytef *tmp = NULL, *otmp = NULL, *dtmp = NULL;
	char *input_file = NULL, *output_file = NULL;
	char *plist = NULL;
	char *blkx = NULL;
	unsigned int blkx_size;
	struct _mishblk *parts = NULL;
	char *data_begin = NULL, *data_end = NULL;
	char *partname_begin = NULL, *partname_end = NULL;
	char *mish_begin = NULL;
	char partname[255] = "";
	unsigned int *partlen = NULL;
	unsigned int data_size;
	uint64_t out_offs, out_size, in_offs, in_size, in_offs_add, add_offs, to_read,
	      to_write, chunk;
	char reserved[5] = "    ";
	char sztype[64] = "";
	unsigned int block_type, dw_reserved;

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-s"))
			verbose = 0;
		else if (!strcmp(argv[i], "-v"))
			verbose = 2;
		else if (!strcmp(argv[i], "-V"))
			verbose = 3;
		else if (!strcmp(argv[i], "-d"))
			debug = 1;
		else if (!strcmp(argv[i], "-l"))
			listparts = 1;
		else if (!strcmp(argv[i], "-p"))
			sscanf(argv[++i], "%d", &extractpart);
		else if (!strcmp(argv[i], "-i") && i < argc - 1)
			input_file = argv[++i];
		else if (!strcmp(argv[i], "-o") && i < argc - 1)
			output_file = argv[++i];
		else if (!input_file)
			input_file = argv[i];
		else if (!output_file)
			output_file = argv[i];
	}

	if (!input_file) {
		printf("\n%s\n\n%s\n\n", VERSION, USAGE);
		return 0;
	}
	if (!output_file) {
		i = strlen(input_file);
		output_file = (char *)malloc(i + 6);
		if (output_file) {
			strcpy(output_file, input_file);
			if (strcasecmp(&output_file[i - 4], ".dmg"))
				strcat(output_file, ".img");
			else
				strcpy(&output_file[i - 4], ".img");
		}
	}
	if (verbose)
		printf("\n%s\n\n", VERSION);
	if (debug) {
		FDBG = fopen("dmg2img.log", "wb");
		if (FDBG == NULL) {
			debug = 0;
			printf("ERROR: Can't create dmg2img.log. No debug info will be written.\n");
		}
	}
	FIN = fopen(input_file, "rb");
	if (FIN == NULL) {
		printf("ERROR: Can't open input file %s\n", input_file);
		return 0;
	}
	if (output_file)
		FOUT = fopen(output_file, "wb");
	else
		FOUT = NULL;
	if (FOUT == NULL) {
		printf("ERROR: Can't create output file %s\n", output_file);
		fclose(FIN);
		return 0;
	}
	//parsing koly block
	fseeko(FIN, -0x200, SEEK_END);
	read_kolyblk(FIN, &kolyblk);
	if (kolyblk.Signature != 0x6b6f6c79) {
		fseeko(FIN, 0, SEEK_SET);
		read_kolyblk(FIN, &kolyblk);
	}
	char szSignature[5];
	szSignature[4] = '\0';
	int rSignature = convert_int(kolyblk.Signature);
	memcpy(szSignature, &rSignature, 4);

	if (debug) {
		fprintf(FDBG, "Signature:\t\t0x%08" PRIX32 " (%s)\n", kolyblk.Signature, szSignature);
		fprintf(FDBG, "Version:\t\t0x%08" PRIX32 "\n", kolyblk.Version);
		fprintf(FDBG, "HeaderSize:\t\t0x%08" PRIX32 "\n", kolyblk.HeaderSize);
		fprintf(FDBG, "Flags:\t\t\t0x%08" PRIX32 "\n", kolyblk.Flags);
		fprintf(FDBG, "RunningDataForkOffset:\t0x%016" PRIX64 "\n", kolyblk.RunningDataForkOffset);
		fprintf(FDBG, "DataForkOffset:\t\t0x%016" PRIX64 "\n", kolyblk.DataForkOffset);
		fprintf(FDBG, "DataForkLength:\t\t0x%016" PRIX64 "\n", kolyblk.DataForkLength);
		fprintf(FDBG, "RsrcForkOffset:\t\t0x%016" PRIX64 "\n", kolyblk.RsrcForkOffset);
		fprintf(FDBG, "RsrcForkLength:\t\t0x%016" PRIX64 "\n", kolyblk.RsrcForkLength);
		fprintf(FDBG, "SegmentNumber:\t\t0x%08" PRIX32 "\n", kolyblk.SegmentNumber);
		fprintf(FDBG, "SegmentCount:\t\t0x%08" PRIX32 "\n", kolyblk.SegmentCount);
		fprintf(FDBG, "SegmentID:\t\t0x%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "\n", kolyblk.SegmentID1, kolyblk.SegmentID2, kolyblk.SegmentID3, kolyblk.SegmentID4);
		fprintf(FDBG, "DataForkChecksumType:\t0x%08" PRIX32 " %s\n", kolyblk.DataForkChecksumType, kolyblk.DataForkChecksumType == 0x02 ? "CRC-32" : "");
		fprintf(FDBG, "DataForkChecksum:\t0x%08" PRIX32 "\n", kolyblk.DataForkChecksum);
		fprintf(FDBG, "XMLOffset:\t\t0x%016" PRIX64 "\n", kolyblk.XMLOffset);
		fprintf(FDBG, "XMLLength:\t\t0x%016" PRIX64 "\n", kolyblk.XMLLength);
		fprintf(FDBG, "MasterChecksumType:\t0x%08" PRIX32 " %s\n", kolyblk.MasterChecksumType, kolyblk.MasterChecksumType == 0x02 ? "CRC-32" : "");
		fprintf(FDBG, "MasterChecksum:\t\t0x%08" PRIX32 "\n", kolyblk.MasterChecksum);
		fprintf(FDBG, "ImageVariant:\t\t0x%08" PRIX32 "\n", kolyblk.ImageVariant);
		fprintf(FDBG, "SectorCount:\t\t0x%016" PRIX64 "\n", kolyblk.SectorCount);

		fprintf(FDBG, "\n");
	}
	if (kolyblk.Signature != 0x6b6f6c79) {
		error_dmg_corrupted();
	}
	if (verbose) {
		if (input_file && output_file)
			printf("%s --> %s\n\n", input_file, listparts ? "(partition list)" : output_file);
	}
	if (debug)
		printf("Debug info will be written to dmg2img.log\n\n");

	if (kolyblk.XMLOffset != 0 && kolyblk.XMLLength != 0) {
		//We have a plist to parse
			if (verbose > 1)
			printf("reading property list, %llu bytes from address %llu ...\n", (unsigned long long)kolyblk.XMLLength, (unsigned long long)kolyblk.XMLOffset);

		plist = (char *)malloc(kolyblk.XMLLength + 1);

		if (!plist)
			mem_overflow();

		fseeko(FIN, kolyblk.XMLOffset, SEEK_SET);
		fread(plist, kolyblk.XMLLength, 1, FIN);
		plist[kolyblk.XMLLength] = '\0';

		if (debug && verbose >= 3) {
			fprintf(FDBG, "%s\n", plist);
		}
		char *_blkx_begin = strstr(plist, blkx_begin);
		blkx_size = strstr(_blkx_begin, list_end) - _blkx_begin;
		blkx = (char *)malloc(blkx_size + 1);
		memcpy(blkx, _blkx_begin, blkx_size);
		blkx[blkx_size] = '\0';

		if (!strstr(plist, plist_begin) ||
		    !strstr(&plist[kolyblk.XMLLength - 20], plist_end)) {
			printf("ERROR: Property list is corrupted.\n");
			exit(-1);
		}
		data_begin = blkx;
		partnum = 0;
		scb = strlen(chunk_begin);
		while (1) {
			unsigned int tmplen;
			data_begin = strstr(data_begin, chunk_begin);
			if (!data_begin)
				break;
			data_begin += scb;
			data_end = strstr(data_begin, chunk_end);
			if (!data_end)
				break;
			data_size = data_end - data_begin;
			i = partnum;
			++partnum;
			parts = (struct _mishblk *)realloc(parts, partnum * sizeof(struct _mishblk));
			if (!parts)
				mem_overflow();

			char *base64data = (char *)malloc(data_size + 1);
			if (!base64data)
				mem_overflow();
			base64data[data_size] = '\0';
			memcpy(base64data, data_begin, data_size);
			if (verbose >= 3)
				printf("%s\n", base64data);
			cleanup_base64(base64data, data_size);
			decode_base64(base64data, strlen(base64data), base64data, &tmplen);
			fill_mishblk(base64data, &parts[i]);
			if (parts[i].BlocksSignature != 0x6D697368)
				break;

			parts[i].Data = (char *)malloc(parts[i].BlocksRunCount * 0x28);
			if (!parts[i].Data)
				mem_overflow();
			memcpy(parts[i].Data, base64data + 0xCC, parts[i].BlocksRunCount * 0x28);

			free(base64data);
	
			partname_begin = strstr(data_begin, name_key);
			partname_begin = strstr(partname_begin, name_begin) + strlen(name_begin);
			partname_end = strstr(partname_begin, name_end);
			memset(partname, 0, 255);
			memcpy(partname, partname_begin, partname_end - partname_begin);
			if (verbose >= 2) {
				printf("partition %d: begin=%d, size=%d, decoded=%d\n", i, (int)(data_begin - blkx), data_size, tmplen);
				if (listparts)
					printf("             %s\n", partname);
			} else if (listparts)
				printf("partition %d: %s\n", i, partname);
		}
	} else if (kolyblk.RsrcForkOffset != 0 && kolyblk.RsrcForkLength != 0) {
		//We have a binary resource fork to parse
			plist = (char *)malloc(kolyblk.RsrcForkLength);
		if (!plist)
			mem_overflow();
		fseeko(FIN, kolyblk.RsrcForkOffset, SEEK_SET);
		fread(plist, kolyblk.RsrcForkLength, 1, FIN);
		partnum = 0;
		struct _mishblk mishblk;
		int next_mishblk = 0;
		mish_begin = plist + 0x104;
		while (1) {
			mish_begin += next_mishblk;
			if (mish_begin - plist + 0xCC > kolyblk.RsrcForkLength)
				break;

			fill_mishblk(mish_begin, &mishblk);
			if (mishblk.BlocksSignature != 0x6D697368)
				break;

			next_mishblk = 0xCC + 0x28 * mishblk.BlocksRunCount + 0x04;
			i = partnum;
			++partnum;
			parts = (struct _mishblk *)realloc(parts, partnum * sizeof(struct _mishblk));
			if (!parts)
				mem_overflow();
			memcpy(&parts[i], &mishblk, sizeof(struct _mishblk));
			parts[i].Data = (char *)malloc(0x28 * mishblk.BlocksRunCount);
			if (!parts[i].Data)
				mem_overflow();
			memcpy(parts[i].Data, mish_begin + 0xCC, 0x28 * mishblk.BlocksRunCount);
			if (verbose >= 2)
				printf("partition %d: begin=%d, size=%" PRIu32 "\n", i, (int)(mish_begin - plist), 0xCC + mishblk.BlocksRunCount * 0x28);
		}
	} else {
		error_dmg_corrupted();
	}
	
	if (listparts || extractpart > partnum-1) {
		if (extractpart > partnum-1)
			printf("partition %d not found\n", extractpart);
		
		for (i = 0; i < partnum; i++)
			if (parts[i].Data != NULL)
				free(parts[i].Data);
		if (parts != NULL)
			free(parts);
		if (plist != NULL)
			free(plist);
		if (blkx != NULL)
			free(blkx);
		
		return 0;
	}
		
	if (verbose)
		printf("\ndecompressing:\n");

	tmp = (Bytef *) malloc(CHUNKSIZE);
	otmp = (Bytef *) malloc(CHUNKSIZE);
	dtmp = (Bytef *) malloc(DECODEDSIZE);
	if (!tmp || !otmp || !dtmp)
		mem_overflow();
	z.zalloc = (alloc_func) 0;
	z.zfree = (free_func) 0;
	z.opaque = (voidpf) 0;
	bz.bzalloc = NULL;
	bz.bzfree = NULL;
	bz.opaque = NULL;

	in_offs = add_offs = in_offs_add = kolyblk.DataForkOffset;

	for (i = extractpart==-1?0:extractpart; i < (extractpart==-1?partnum:extractpart+1) && in_offs < kolyblk.DataForkLength - kolyblk.DataForkOffset; i++) {
		if (verbose)
			printf("opening partition %d ...           ", i);
		if (verbose >= 3)
			printf("\n");
		else if (verbose)
			printf("         ");
		fflush(stdout);
		offset = 0;
		add_offs = in_offs_add;
		block_type = 0;
		if (debug) {
			fprintf(FDBG, "\n   run..... ..type.... ..reserved ..sectorStart..... ..sectorCount..... ..compOffset...... ..compLength......\n");
		}
		unsigned long bi = 0;
		while (block_type != BT_TERM && offset < parts[i].BlocksRunCount * 0x28) {
			block_type = convert_char4((unsigned char *)parts[i].Data + offset);
			dw_reserved = convert_char4((unsigned char *)parts[i].Data + offset + 4);
			memcpy(&reserved, parts[i].Data + offset + 4, 4);
			out_offs = convert_char8((unsigned char *)parts[i].Data + offset + 8) * 0x200;
			out_size = convert_char8((unsigned char *)parts[i].Data + offset + 16) * 0x200;
			in_offs = convert_char8((unsigned char *)parts[i].Data + offset + 24);
			in_size = convert_char8((unsigned char *)parts[i].Data + offset + 32);
			if (block_type != BT_TERM)
				in_offs_add = add_offs + in_offs + in_size;
			if (debug) {
				switch (block_type) {
				case BT_ADC:
					strcpy(sztype, "adc");
					break;
				case BT_ZLIB:
					strcpy(sztype, "zlib");
					break;
				case BT_BZLIB:
					strcpy(sztype, "bzlib");
					break;
				case BT_ZERO:
					strcpy(sztype, "zero");
					break;
				case BT_IGNORE:
					strcpy(sztype, "ignore");
					break;
				case BT_RAW:
					strcpy(sztype, "raw");
					break;
				case BT_COMMENT:
					strcpy(sztype, "comment ");
					strcat(sztype, reserved);
					break;
				case BT_TERM:
					strcpy(sztype, "terminator");
					break;
				default:
					sztype[0] = '\0';
				}
				fprintf(FDBG, " 0x%08lX 0x%08lX 0x%08lX 0x%016llX 0x%016llX 0x%016llX 0x%016llX %s\n",
					(unsigned long)bi,
					(unsigned long)block_type,
					(unsigned long)dw_reserved,
					(unsigned long long)out_offs / 0x200,
					(unsigned long long)out_size / 0x200,
					(unsigned long long)in_offs,
					(unsigned long long)in_size,
					sztype
					);
				fflush(FDBG);
				bi++;
			}
			if (verbose >= 3)
				printf("offset = %u  block_type = 0x%08x\n", offset, block_type);

			if (block_type == BT_ZLIB) {
				if (verbose >= 3)
					printf("zlib inflate (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size);
				if (inflateInit(&z) != Z_OK) {
					printf("ERROR: Can't initialize inflate stream\n");
					return 0;
				}
				fseeko(FIN, in_offs + add_offs, SEEK_SET);
				to_read = in_size;
				do {
					if (!to_read)
						break;
					if (to_read > CHUNKSIZE)
						chunk = CHUNKSIZE;
					else
						chunk = to_read;
					z.avail_in = fread(tmp, 1, chunk, FIN);
					if (ferror(FIN)) {
						(void)inflateEnd(&z);
						printf("ERROR: reading file %s \n", input_file);
						return 0;
					}
					if (z.avail_in == 0)
						break;
					to_read -= z.avail_in;
					z.next_in = tmp;
					do {
						z.avail_out = CHUNKSIZE;
						z.next_out = otmp;
						err = inflate(&z, Z_NO_FLUSH);
						assert(err != Z_STREAM_ERROR);	/* state not clobbered */
						switch (err) {
						case Z_NEED_DICT:
							err = Z_DATA_ERROR;	/* and fall through */
						case Z_DATA_ERROR:
						case Z_MEM_ERROR:
							(void)inflateEnd(&z);
							printf("ERROR: Inflation failed\n");
							return 0;
						}
						to_write = CHUNKSIZE - z.avail_out;
						if (fwrite(otmp, 1, to_write, FOUT) != to_write || ferror(FOUT)) {
							(void)inflateEnd(&z);
							printf("ERROR: writing file %s \n", output_file);
							return 0;
						}
					} while (z.avail_out == 0);
				} while (err != Z_STREAM_END);

				(void)inflateEnd(&z);
			} else if (block_type == BT_BZLIB) {
				if (verbose >= 3)
					printf("bzip2 decompress (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size);
				if (BZ2_bzDecompressInit(&bz, 0, 0) != BZ_OK) {
					printf("ERROR: Can't initialize inflate stream\n");
					return 0;
				}
				fseeko(FIN, in_offs + add_offs, SEEK_SET);
				to_read = in_size;
				do {
					if (!to_read)
						break;
					if (to_read > CHUNKSIZE)
						chunk = CHUNKSIZE;
					else
						chunk = to_read;
					bz.avail_in = fread(tmp, 1, chunk, FIN);
					if (ferror(FIN)) {
						(void)BZ2_bzCompressEnd(&bz);
						printf("ERROR: reading file %s \n", input_file);
						return 0;
					}
					if (bz.avail_in == 0)
						break;
					to_read -= bz.avail_in;
					bz.next_in = (char *)tmp;
					do {
						bz.avail_out = CHUNKSIZE;
						bz.next_out = (char *)otmp;
						err = BZ2_bzDecompress(&bz);
						switch (err) {
						case BZ_PARAM_ERROR:
						case BZ_DATA_ERROR:
						case BZ_DATA_ERROR_MAGIC:
						case BZ_MEM_ERROR:
							(void)BZ2_bzDecompressEnd(&bz);
							printf("ERROR: Inflation failed\n");
							return 0;
						}
						to_write = CHUNKSIZE - bz.avail_out;
						if (fwrite(otmp, 1, to_write, FOUT) != to_write || ferror(FOUT)) {
							(void)BZ2_bzDecompressEnd(&bz);
							printf("ERROR: writing file %s \n", output_file);
							return 0;
						}
					} while (bz.avail_out == 0);
				} while (err != BZ_STREAM_END);

				(void)BZ2_bzDecompressEnd(&bz);
			} else if (block_type == BT_ADC) {
				if (verbose >= 3)
					printf("ADC decompress (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size);
				fseeko(FIN, in_offs + add_offs, SEEK_SET);
				to_read = in_size;
				while (to_read > 0) {
					chunk = to_read > CHUNKSIZE ? CHUNKSIZE : to_read;
					to_write = fread(tmp, 1, chunk, FIN);
					if (ferror(FIN) || to_write < chunk) {
						printf("ERROR: reading file %s\n", input_file);
						return 0;
					}
					int bytes_written;
					int read_from_input = adc_decompress(to_write, tmp, DECODEDSIZE, dtmp, &bytes_written);
					fwrite(dtmp, 1, bytes_written, FOUT);
					to_read -= read_from_input;
				}
			} else if (block_type == BT_RAW) {
				fseeko(FIN, in_offs + add_offs, SEEK_SET);
				to_read = in_size;
				while (to_read > 0) {
					if (to_read > CHUNKSIZE)
						chunk = CHUNKSIZE;
					else
						chunk = to_read;
					to_write = fread(tmp, 1, chunk, FIN);
					if (ferror(FIN) || to_write < chunk) {
						printf("ERROR: reading file %s \n", input_file);
						return 0;
					}
					fwrite(tmp, 1, chunk, FOUT);
					//copy
						to_read -= chunk;
				}
				if (verbose >= 3)
					printf("copy data  (in_addr=%llu in_size=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_size);
			} else if (block_type == BT_ZERO || block_type == BT_IGNORE) {
				memset(tmp, 0, CHUNKSIZE);
				to_write = out_size;
				while (to_write > 0) {
					if (to_write > CHUNKSIZE)
						chunk = CHUNKSIZE;
					else
						chunk = to_write;
					fwrite(tmp, 1, chunk, FOUT);
					to_write -= chunk;
				}
				if (verbose >= 3)
					printf("null bytes (out_size=%llu)\n",
						   (unsigned long long)out_size);
			} else if (block_type == BT_COMMENT) {
				if (verbose >= 3)
					printf("0x%08x (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu) comment %s\n", block_type, (unsigned long long)in_offs,
						   (unsigned long long)in_size,
						   (unsigned long long)out_offs,
						   (unsigned long long)out_size, reserved);
			} else if (block_type == BT_TERM) {
				if (in_offs == 0 && partnum > i+1) {
					if (convert_char8((unsigned char *)parts[i+1].Data + 24) != 0)
						in_offs_add = kolyblk.DataForkOffset;
				} else
					in_offs_add = kolyblk.DataForkOffset;

				if (verbose >= 3)
					printf("terminator\n");
			} else {
				if (verbose)
					printf("\n Unsupported or corrupted block found: %d\n", block_type);
			}
			offset += 0x28;
			if (verbose) {
				percent = 100 * (double)offset / ((double)parts[i].BlocksRunCount * 0x28);
				percentage();
			}
		}
		if (verbose)
			printf("  ok\n");
	}
	if (verbose)
		printf("\nArchive successfully decompressed as %s\n", output_file);

	if (tmp != NULL)
		free(tmp);
	if (otmp != NULL)
		free(otmp);
	if (dtmp != NULL)
		free(dtmp);
	for (i = 0; i < partnum; i++) {
		if (parts[i].Data != NULL)
			free(parts[i].Data);
	}
	if (parts != NULL)
		free(parts);
	if (partlen != NULL)
		free(partlen);
	if (plist != NULL)
		free(plist);
	if (blkx != NULL)
		free(blkx);
	if (FIN != NULL)
		fclose(FIN);
	if (FOUT != NULL)
		fclose(FOUT);
	if (FDBG != NULL)
		fclose(FDBG);

#if defined(__linux__)
	if (verbose && extractpart > -1)
		print_mountcmd(output_file);
#endif

	return 0;
}
Пример #25
0
void convertInt(types::InternalType* _pIn, T* _pOut)
{
    switch (_pIn->getType())
    {
        case types::InternalType::ScilabBool :
        {
            types::Bool* pBool = _pIn->getAs<types::Bool>();
            convert_int(pBool->get(), pBool->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabDouble :
        {
            types::Double* pD = _pIn->getAs<types::Double>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabInt8 :
        {
            types::Int8* pD = _pIn->getAs<types::Int8>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabUInt8 :
        {
            types::UInt8* pD = _pIn->getAs<types::UInt8>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabInt16 :
        {
            types::Int16* pD = _pIn->getAs<types::Int16>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabUInt16 :
        {
            types::UInt16* pD = _pIn->getAs<types::UInt16>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabInt32 :
        {
            types::Int32* pD = _pIn->getAs<types::Int32>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabUInt32 :
        {
            types::UInt32* pD = _pIn->getAs<types::UInt32>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabInt64 :
        {
            types::Int64* pD = _pIn->getAs<types::Int64>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        case types::InternalType::ScilabUInt64 :
        {
            types::UInt64* pD = _pIn->getAs<types::UInt64>();
            convert_int(pD->get(), pD->getSize(), _pOut->get());
            break;
        }
        default:
            return;
    }
}