Example #1
0
File: cnf.c Project: genesi/luatex
static void
read_all_cnf (kpathsea kpse)
{
  string *cnf_files;
  string *cnf;
  const_string cnf_path = kpathsea_init_format (kpse, kpse_cnf_format);

  kpse->cnf_hash = hash_create (CNF_HASH_SIZE);

  cnf_files = kpathsea_all_path_search (kpse, cnf_path, CNF_NAME);
  if (cnf_files && *cnf_files) {
    for (cnf = cnf_files; *cnf; cnf++) {
      string line;
      FILE *cnf_file = xfopen (*cnf, FOPEN_R_MODE);
      if (kpse->record_input)
        kpse->record_input (*cnf);

      while ((line = read_line (cnf_file)) != NULL) {
        unsigned len = strlen (line);
        /* Strip trailing spaces. */
        while (len > 0 && ISSPACE(line[len-1])) {
          line[len - 1] = 0;
          --len;
        }
        /* Concatenate consecutive lines that end with \.  */
        while (len > 0 && line[len - 1] == '\\') {
          string next_line = read_line (cnf_file);
          line[len - 1] = 0;
          if (!next_line) {
            WARNING1 ("%s: Last line ends with \\", *cnf);
          } else {
            string new_line;
            new_line = concat (line, next_line);
            free (line);
            line = new_line;
            len = strlen (line);
          }
        }

        do_line (kpse, line);
        free (line);
      }

      xfclose (cnf_file, *cnf);
      free (*cnf);
    }
    free (cnf_files);
  } else {
    string warn = getenv ("KPATHSEA_WARNING");
    if (!(warn && STREQ (warn, "0"))) {
      WARNING1
 ("kpathsea: configuration file texmf.cnf not found in these directories: %s", 
        cnf_path);
    }
  }
}
Example #2
0
static void
expand P3C(fn_type *, expansion,  const_string, start,  const_string, end)
{
  string value;
  unsigned len = end - start + 1;
  string var = xmalloc (len + 1);
  strncpy (var, start, len);
  var[len] = 0;

  if (expanding_p (var)) {
    WARNING1 ("kpathsea: variable `%s' references itself (eventually)", var);
  } else {
#if 1
    /* The mktex.c replacement for shell scripts needs a more sophisticated
       lookup for variables */
    value = getval(var);
#else
    /* Check for an environment variable.  */
    value = getenv (var);
#endif
    /* If no envvar, check the config files.  */
    if (!value)
      value = kpse_cnf_get (var);

    if (value) {
      expanding (var, true);
      value = mktex_var_expand (value);
      expanding (var, false);
      fn_grow (expansion, value, strlen (value));
      free (value);
    }

    free (var);
  }
}
Example #3
0
static
void router_receive(receiver_t* self,
		    bytecode_stream_t* message, context_t* context)
{
    router_t* router = (router_t*) self;
    bytecode_t* selector = message->pop(message);

    if(selector && selector->verb == route_atom) {
	bytecode_t* destination = message->pop(message);

	if(!destination) {
	    WARNING1("no destination provided.");
	    return;
	} else {
	    atom_t dest = destination->verb;
	    if(!router_route(get_slot(router, dest), message, context)) {
		WARNING2("route '%s' not defined.", 
			 atom_get_cstring_value(dest));
	    }
	}
    } else {
	message->push(message, selector);
	router->receive_backup(self, message, context);
    }
}
Example #4
0
int
mm_decode_video(mm_file *mf, SDL_Overlay *ovl)
{
    int rv = 0;
    ogg_packet pkt;
    yuv_buffer yuv;

    assert(mf);

    if (!mf->video) {
        return -1;
    }

    if (mf->drop_packets & MEDIA_VIDEO) {
        WARNING1("requested decode but MEDIA_VIDEO is set to ignore");
        return -1;
    }

    for (;;) {
        rv = get_packet(mf, &pkt, MEDIA_VIDEO);

        if (rv <= 0) {
            return rv;
        }

        /* we got packet, decode */
        if (theora_decode_packetin(mf->video_ctx, &pkt) == 0) {
            break;
        } else {
            WARNING1("packet does not contain theora frame");
            /* get next packet */
        }
    }

    theora_decode_YUVout(mf->video_ctx, &yuv);

    if (yuv_to_overlay(mf, &yuv, ovl) < 0) {
        return -1;
    }

    return 1;
}
Example #5
0
string
mktex_var_expand P1C(const_string, src)
{
  const_string s;
  string ret;
  fn_type expansion;
  expansion = fn_init ();
  
  /* Copy everything but variable constructs.  */
  for (s = src; *s; s++) {
    if (IS_VAR_START (*s)) {
      s++;

      /* Three cases: `$VAR', `${VAR}', `$<anything-else>'.  */
      if (IS_VAR_CHAR (*s)) {
        /* $V: collect name constituents, then expand.  */
        const_string var_end = s;

        do {
          var_end++;
        } while (IS_VAR_CHAR (*var_end));

        var_end--; /* had to go one past */
        expand (&expansion, s, var_end);
        s = var_end;

      } else if (IS_VAR_BEGIN_DELIMITER (*s)) {
        /* ${: scan ahead for matching delimiter, then expand.  */
        const_string var_end = ++s;

        while (*var_end && !IS_VAR_END_DELIMITER (*var_end))
          var_end++;

        if (! *var_end) {
          WARNING1 ("%s: No matching } for ${", src);
          s = var_end - 1; /* will incr to null at top of loop */
        } else {
          expand (&expansion, s, var_end - 1);
          s = var_end; /* will incr past } at top of loop*/
        }

      } else {
        /* $<something-else>: error.  */
        WARNING2 ("%s: Unrecognized variable construct `$%c'", src, *s);
        /* Just ignore those chars and keep going.  */
      }
    } else
     fn_1grow (&expansion, *s);
  }
  fn_1grow (&expansion, 0);
          
  ret = FN_STRING (expansion);
  return ret;
}
Example #6
0
static void
dispatch_message (Atom a, message_data_type data)
{
  if (a == foserver_exit_atom)
    foserver_exit ();
  
  else if (a == foserver_update_pixmap_atom)
    foserver_update_pixmap (data.l[0]);

  else
    WARNING1 ("foserver: Unknown message `%s'", XGetAtomName (display, a));
}
Example #7
0
static
void wildcard_router_receive(receiver_t* self,
			     bytecode_stream_t* message, context_t* context)
{
    router_t* router = (router_t*) self;
    bytecode_t* selector = message->pop(message);

    if(selector && selector->verb == route_atom) {
	bytecode_t* destination = message->pop(message);

	if(!destination) {
	    WARNING1("no destination provided.");
	    return;
	} else {
	    atom_t dest = destination->verb;

	    TRACE2("routing towards selector '%s' requested.", atom_get_cstring_value(dest));
	    if(dest == star_atom) {
		map_iterator_t i; 
		map_value_t pslot = NULL_MAP_VALUE;
		
		map_get_iterator(&router->children, &i);
		
		while (map_value_is_there (pslot = map_iterator_next(&i))) {
		    router_slot_t* slot = map_value_obtain (pslot);
		    // clone each message
		    bytecode_stream_t* message_copy = bytecode_stream_instantiate_toplevel(NULL);
		    message_copy->copy(message_copy, message);

		    TRACE2("sending event to slot: '%s'", 
			   atom_get_cstring_value(slot->name));
		    if(!router_route(slot, message_copy, context)) {
			WARNING2("route '%s' not defined.", 
				 atom_get_cstring_value(slot->name));
		    }
		}
		map_iterator_destroy (&i);
		map_iterator_retire (&i);

		bytecode_stream_retire (message);
	    } else {
		if(!router_route(get_slot(router, dest), message, context)) {
		    WARNING2("route '%s' not defined.", 
			     atom_get_cstring_value(dest));
		}
	    }
	}
    } else {
	message->push(message, selector);
	router->receive_backup(self, message, context);
    }
}
static void res_set_fopen(struct rloader_t *self, const char *protocol,
                          const fopen_function f)
{
    unsigned int i =
        find_slot(self->protocols, self->f_next, self->f_max, protocol);
    if (i >= self->f_max)
        WARNING1(__FILE__ ": reached static limit in set_fopen.");
    else {
        if (i == self->f_next)
            self->f_next++;

        self->protocols[i] = strdup(protocol);
        self->functions[i] = f;
    }
}
Example #9
0
static
void router_set_child(router_t* self, atom_t name, receiver_t* child)
{
    router_slot_t* slot = get_slot(self, name);

    if(child == &self->super) {
	/* detect stupid errors, but not complicated loops */
	WARNING1("what the f**k are you trying to do.");
    }

    if(!slot) {
	slot = calloc(sizeof(router_slot_t), 1);
	map_put (&self->children, (unsigned long) name, slot);
	TRACE2("added slot for selector: '%s'", atom_get_cstring_value(name));
    }

    slot->name = name;
    slot->receiver = child;
}
Example #10
0
static void
read_all_cnf P1H(void)
{
  string *cnf_files;
  const_string cnf_path = kpse_init_format (kpse_cnf_format);

  cnf_hash = hash_create (CNF_HASH_SIZE);

  for (cnf_files = kpse_all_path_search (cnf_path, CNF_NAME);
       cnf_files && *cnf_files; cnf_files++) {
    string line;
    string cnf_filename = *cnf_files;
    FILE *cnf_file = xfopen (cnf_filename, FOPEN_R_MODE);

    while ((line = read_line (cnf_file)) != NULL) {
      unsigned len = strlen (line);
      /* Strip trailing spaces. */
      while (len > 0 && ISSPACE(line[len-1])) {
        line[len - 1] = 0;
        --len;
      }
      /* Concatenate consecutive lines that end with \.  */
      while (len > 0 && line[len - 1] == '\\') {
        string next_line = read_line (cnf_file);
        line[len - 1] = 0;
        if (!next_line) {
          WARNING1 ("%s: Last line ends with \\", cnf_filename);
        } else {
          string new_line;
          new_line = concat (line, next_line);
          free (line);
          line = new_line;
          len = strlen (line);
        }
      }

      do_line (line);
      free (line);
    }

    xfclose (cnf_file, cnf_filename);
  }
}
Example #11
0
struct atomType *
getAtomTypeByIndex(int atomTypeIndex)
{
  char buf[256];
  struct atomType *entry;

  if (periodicHashtable == NULL) {
    ERROR("getAtomTypeByIndex called before periodic table initialization");
    return NULL;
  }
  sprintf(buf, "%d", atomTypeIndex);
  entry = (struct atomType *)hashtable_get(periodicHashtable, buf);
  if (entry == NULL) {
    entry = (struct atomType *)hashtable_get(periodicHashtable, "0");
    WARNING1("using undefined atomType %d", atomTypeIndex);
    hashtable_put(periodicHashtable, buf, entry); // this should suppress further warnings
  }
  return entry;
}
Example #12
0
/* read a line, trying to find 'variable = value' 
   Currently groks two constructs:
   VAR=value
   : {VAR=value}
   using regex to analyze them.
   The variable is added to the symbol table. In the first case, it
   overrides an old value, not in the second case.
 */
boolean parse_variable(string line)
{
  char **vars;

  static char *r1 = "^[[:space:]]*([[:alnum:]_]+)=[[:space:]]*([^[:space:]]*)[[:space:]]*.*$";
  static char *r2 = "^:[[:space:]]+\\$\\{([[:alnum:]_]+)=([^\\}]*)\\}[[:space:]]*.*$";

  if ((vars = grep(r1, line, 2))) {
    setval(vars[1], vars[2]);
    return true;
  }
  else if ((vars = grep(r2, line, 2))) {
    setval_default(vars[1], vars[2]);
    return true;
  }
  else
    WARNING1("The following line has not been parsed:\n%s\n", line);
  return false;
}
Example #13
0
int *
scan_unsigned_list (string l)
{
    string map;
    unsigned length = 1;
    int *vector = xmalloc (sizeof (int));

    for (map = strtok (l, ","); map != NULL; map = strtok (NULL, ","))
    {
        length++;
        vector = xrealloc (vector, length * sizeof (int));
        vector[length - 2] = atou (map);
        if (vector[length - 2] < 0)
            WARNING1 ("Unsigned number %u is too large", vector[length - 2]);
    }

    vector[length - 1] = -1;
    return vector;
}
Example #14
0
int
get_command_line_args_utf8 (const_string enc, int *p_ac, char ***p_av)
{
    int argc;
    string *argv;

    if (!enc || !strncmp(enc,"",1)) return 0;

#ifdef DEBUG
    fprintf(stderr, "command_line_encoding (%s)\n", enc);
#endif /* DEBUG */
    if (!(strncmp(enc,"utf8",5) && strncmp(enc,"utf-8",6))) {
      LPWSTR *argvw;
      INT argcw, i;
      string s;
#ifdef DEBUG
      DWORD ret;
      HANDLE hStderr;
      hStderr = GetStdHandle( STD_ERROR_HANDLE );
#endif /* DEBUG */
      file_system_codepage = CP_UTF8;
      is_cp932_system = 0;
      argvw = CommandLineToArgvW(GetCommandLineW(), &argcw);
      argc = argcw;
      argv = xmalloc(sizeof(char *)*(argcw+1));
      for (i=0; i<argcw; i++) {
        s = get_utf8_from_wstring(argvw[i], s=NULL);
        argv[i] = s;
#ifdef DEBUG
        fprintf(stderr, "Commandline arguments %d:(%s) [", i, argv[i]);
        WriteConsoleW( hStderr, argvw[i], wcslen(argvw[i]), &ret, NULL);
        fprintf(stderr, "]\n");
#endif /* DEBUG */
      }
      argv[argcw] = NULL;
      *p_ac = argc;
      *p_av = argv;
      return file_system_codepage;
    } else {
      WARNING1("kpathsea: Ignoring unknown encoding `%s'", enc);
      return 0;
    }
}
Example #15
0
static boolean
expand (kpathsea kpse, fn_type *expansion,
        const_string start, const_string end)
{
  boolean ret = false;
  const_string value;
  unsigned len = end - start + 1;
  string var = (string)xmalloc (len + 1);
  strncpy (var, start, len);
  var[len] = 0;

  if (expanding_p (kpse, var)) {
    WARNING1 ("kpathsea: variable `%s' references itself (eventually)", var);
  } else {
    string vtry = concat3 (var, "_", kpse->program_name);
    /* Check for an environment variable.  */
    value = getenv (vtry);
    free (vtry);

    if (!value || !*value)
      value = getenv (var);

    /* If no envvar, check the config files.  */
    if (!value || !*value)
      value = kpathsea_cnf_get (kpse, var);

    if (value) {
      string tmp;
      ret = true;
      expanding (kpse, var, true);
      tmp = kpathsea_expand (kpse, value);
      expanding (kpse, var, false);

      fn_grow (expansion, tmp, strlen (tmp));
      free (tmp);
    }
  }

  free (var);
  return ret;
}
Example #16
0
void
kpathsea_init_fallback_resolutions (kpathsea kpse, string envvar)
{
  string size;
  const_string size_var = ENVVAR (envvar, "TEXSIZES");
  string size_str = getenv (size_var);
  unsigned *last_resort_sizes = NULL;
  unsigned size_count = 0;
  const_string default_sizes = kpse->fallback_resolutions_string
                         ? kpse->fallback_resolutions_string
                         : DEFAULT_FONT_SIZES;
  string size_list = kpathsea_expand_default (kpse, size_str, default_sizes);

  /* Initialize the list of last-resort sizes.  */
  for (size = kpathsea_path_element (kpse, size_list); size != NULL;
       size = kpathsea_path_element (kpse, NULL))
    {
      unsigned s;
      if (! *size) /* Skip empty elements.  */
        continue;

      s = atoi (size);
      if (size_count && s < last_resort_sizes[size_count - 1]) {
    WARNING1 ("kpathsea: last resort size %s not in ascending order; ignored",
          size);
      } else {
        size_count++;
        XRETALLOC (last_resort_sizes, size_count, unsigned);
        last_resort_sizes[size_count - 1] = atoi (size);
      }
    }

  /* Add a zero to mark the end of the list.  */
  size_count++;
  XRETALLOC (last_resort_sizes, size_count, unsigned);
  last_resort_sizes[size_count - 1] = 0;

  free (size_list);

  kpse->fallback_resolutions = last_resort_sizes;
}
Example #17
0
static str_list_type brace_expand P1C(const_string *, text)
{
    str_list_type result, partial, recurse;
    const_string p;
    result = str_list_init();
    partial = str_list_init();
    for (p = *text; *p && *p != '}'; ++p) {
        /* FIXME: Should be IS_ENV_SEP(*p) */
        if (*p == ENV_SEP || *p == ',') {
            expand_append(&partial, *text, p);
            str_list_concat(&result, partial);
            str_list_free(&partial);
            *text = p+1;
            partial = str_list_init();
        } else if (*p == '{') {
            expand_append(&partial, *text, p);
            ++p;
            recurse = brace_expand(&p);
            str_list_concat_elements(&partial, recurse);
            str_list_free(&recurse);
            /* Check for missing closing brace. */
            if (*p != '}') {
                WARNING1 ("%s: Unmatched {", *text);
            }
            *text = p+1;
        } else if (*p == '$') {
            /* Skip ${VAR} */
            if (*(p+1) == '{')
                for (p+=2; *p!='}';++p);
        }
    }
    expand_append(&partial, *text, p);
    str_list_concat(&result, partial);
    str_list_free(&partial);
    *text = p;
    return result;
}
Example #18
0
static string
maketex P2C(kpse_file_format_type, format, string*, args)
{
  /* New implementation, use fork/exec pair instead of popen, since
   * the latter is virtually impossible to make safe.
   */
  unsigned len;
  string *s;
  string ret;
  string fn;
  
  if (!kpse_make_tex_discard_errors) {
    fprintf (stderr, "kpathsea: Running");
    for (s = &args[0]; *s != NULL; s++)
      fprintf (stderr, " %s", *s);
    fputc('\n', stderr);
  }

#if defined (AMIGA)
  /* Amiga has a different interface. */
  {
    string cmd;
    string newcmd;
    cmd = xstrdup(args[0]);
    for (s = &args[1];  *s != NULL; s++) {
      newcmd = concat(cmd, *s);
      free (cmd);
      cmd = newcmd;
    }
    ret = system(cmd) == 0 ? getenv ("LAST_FONT_CREATED"): NULL;
    free (cmd);
  }
#elif defined (MSDOS)
#error Implement new MSDOS mktex call interface here
#elif defined (WIN32)
  /* We would vastly prefer to link directly with mktex.c here.
     Unfortunately, it is not quite possible because kpathsea
     is not reentrant. The progname is expected to be set in mktex.c
     and various initialisations occur. So to be safe, we implement
     a call sequence equivalent to the Unix one. */
  {
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    HANDLE child_in, child_out, child_err;
    HANDLE father_in, father_out_dup;
    HANDLE current_pid;
    SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
    string new_cmd = NULL, app_name = NULL;

    char buf[1024+1];
    int num;
    extern char *quote_args(char **argv);

    if (look_for_cmd(args[0], &app_name) == FALSE) {
      ret = NULL;
      goto error_exit;
    }

    /* Compute the command line */
    new_cmd = quote_args(args);

    /* We need this handle to duplicate other handles */
    current_pid = GetCurrentProcess();

    ZeroMemory( &si, sizeof(STARTUPINFO) );
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW ;
    si.wShowWindow = /* 0 */ SW_HIDE ;

    /* Child stdin */
    child_in = CreateFile("nul",
                          GENERIC_READ,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          &sa,  /* non inheritable */
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          NULL);
    si.hStdInput = child_in;

    if (CreatePipe(&father_in, &child_out, NULL, 0) == FALSE) {
      fprintf(stderr, "popen: error CreatePipe\n");
      goto error_exit;
    }
    if (DuplicateHandle(current_pid, child_out,
                        current_pid, &father_out_dup,
                        0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE) {
      fprintf(stderr, "popen: error DuplicateHandle father_in\n");
      CloseHandle(father_in);
      CloseHandle(child_out);
      goto error_exit;
    }
    CloseHandle(child_out);
    si.hStdOutput = father_out_dup;

    /* Child stderr */
    if (kpse_make_tex_discard_errors) {
      child_err = CreateFile("nul",
                             GENERIC_WRITE,
                             FILE_SHARE_READ | FILE_SHARE_WRITE,
                             &sa,       /* non inheritable */
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL,
                             NULL);
    }
    else {
      DuplicateHandle(current_pid, GetStdHandle(STD_ERROR_HANDLE),
                      current_pid, &child_err,
                      0, TRUE,
                      DUPLICATE_SAME_ACCESS);
    }
    si.hStdError = child_err;

    /* creating child process */
    if (CreateProcess(app_name, /* pointer to name of executable module */
                      new_cmd,  /* pointer to command line string */
                      NULL,     /* pointer to process security attributes */
                      NULL,     /* pointer to thread security attributes */
                      TRUE,     /* handle inheritance flag */
                      0,                /* creation flags */
                      NULL,     /* pointer to environment */
                      NULL,     /* pointer to current directory */
                      &si,      /* pointer to STARTUPINFO */
                      &pi               /* pointer to PROCESS_INFORMATION */
                      ) == 0) {
      FATAL2("kpathsea: CreateProcess() failed for `%s' (Error %x)\n", new_cmd, GetLastError());
    }

    CloseHandle(child_in);
    CloseHandle(father_out_dup);
    CloseHandle(child_err);

    /* Only the process handle is needed */
    CloseHandle(pi.hThread);

    /* Get stdout of child from the pipe. */
    fn = xstrdup("");
    while (ReadFile(father_in,buf,sizeof(buf)-1, &num, NULL) != 0
           && num > 0) {
      if (num <= 0) {
        if (GetLastError() != ERROR_BROKEN_PIPE) {
          FATAL1("kpathsea: read() error code for `%s' (Error %d)", GetLastError());
          break;
        }
      } else {
        string newfn;
        buf[num] = '\0';
        newfn = concat(fn, buf);
        free(fn);
        fn = newfn;
      }
    }
    /* End of file on pipe, child should have exited at this point. */
    CloseHandle(father_in);

    if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0) {
      WARNING2("kpathsea: failed to wait for process termination: %s (Error %d)\n",
               new_cmd, GetLastError());
    }

    CloseHandle(pi.hProcess);

    if (new_cmd) free(new_cmd);
    if (app_name) free(app_name);

    if (fn) {
      len = strlen(fn);

      /* Remove trailing newlines and returns.  */
      while (len && (fn[len - 1] == '\n' || fn[len - 1] == '\r')) {
        fn[len - 1] = '\0';
        len--;
      }

      ret = len == 0 ? NULL : kpse_readable_file (fn);
      if (!ret && len > 1) {
        WARNING1 ("kpathsea: mktexpk output `%s' instead of a filename", fn);
      }

      /* Free the name if we're not returning it.  */
      if (fn != ret)
        free (fn);
    }
  error_exit:
    ;
  }
#else
  {
    /* Standard input for the child.  Set to /dev/null */
    int childin;
    /* Standard output for the child, what we're interested in. */
    int childout[2];
    /* Standard error for the child, same as parent or /dev/null */
    int childerr;
    /* Child pid. */
    pid_t childpid;

    /* Open the channels that the child will use. */
    /* A fairly horrible uses of gotos for here for the error case. */
    if ((childin = open("/dev/null", O_RDONLY)) < 0) {
      perror("kpathsea: open(\"/dev/null\", O_RDONLY)");
      goto error_childin;
    }
    if (pipe(childout) < 0) {
      perror("kpathsea: pipe()");
      goto error_childout;
    }
    if ((childerr = open("/dev/null", O_WRONLY)) < 0) {
      perror("kpathsea: open(\"/dev/null\", O_WRONLY)");
      goto error_childerr;
    }
    if ((childpid = fork()) < 0) {
      perror("kpathsea: fork()");
      close(childerr);
     error_childerr:
      close(childout[0]);
      close(childout[1]);
     error_childout:
      close(childin);
     error_childin:
      fn = NULL;
    } else if (childpid == 0) {
      /* Child
       *
       * We can use vfork, provided we're careful about what we
       * do here: do not return from this function, do not modify
       * variables, call _exit if there is a problem.
       *
       * Complete setting up the file descriptors.
       * We use dup(2) so the order in which we do this matters.
       */
      close(childout[0]);
      /* stdin -- the child will not receive input from this */
      if (childin != 0) {
        close(0);
        dup(childin);
        close(childin);
      }
      /* stdout -- the output of the child's action */
      if (childout[1] != 1) {
        close(1);
        dup(childout[1]);
        close(childout[1]);
      }
      /* stderr -- use /dev/null if we discard errors */
      if (childerr != 2) {
        if (kpse_make_tex_discard_errors) {
          close(2);
          dup(childerr);
        }
        close(childerr);
      }
      /* FIXME: We could/should close all other file descriptors as well. */
      /* exec -- on failure a call of _exit(2) it is the only option */
      if (execvp(args[0], args))
        perror(args[0]);
      _exit(1);
    } else {
      /* Parent */
      char buf[1024+1];
      int num;
      int status;

      /* Clean up child file descriptors that we won't use anyway. */
      close(childin);
      close(childout[1]);
      close(childerr);
      /* Get stdout of child from the pipe. */
      fn = xstrdup("");
      while ((num = read(childout[0],buf,sizeof(buf)-1)) != 0) {
        if (num == -1) {
          if (errno != EINTR) {
            perror("kpathsea: read()");
            break;
          }
        } else {
          string newfn;
          buf[num] = '\0';
          newfn = concat(fn, buf);
          free(fn);
          fn = newfn;
        }
      }
      /* End of file on pipe, child should have exited at this point. */
      close(childout[0]);
      /* We don't really care about the exit status at this point. */
      wait(NULL);
    }

    if (fn) {
      len = strlen(fn);

      /* Remove trailing newlines and returns.  */
      while (len && (fn[len - 1] == '\n' || fn[len - 1] == '\r')) {
        fn[len - 1] = '\0';
        len--;
      }

      ret = len == 0 ? NULL : kpse_readable_file (fn);
      if (!ret && len > 1) {
        WARNING1 ("kpathsea: mktexpk output `%s' instead of a filename", fn);
      }

      /* Free the name if we're not returning it.  */
      if (fn != ret)
        free (fn);
    } else {
      ret = NULL;
    }
  }
#endif

  if (ret == NULL)
    misstex (format, args);
  else
    kpse_db_insert (ret);
  
  return ret;
}
Example #19
0
static void receiver_receive(receiver_t *self, bytecode_stream_t *message,
                             context_t *context)
{
    atom_t selector;
    message_fifo_t *fifo;
    message_node_t *node;
    node_iterator_t it;

    if (!message || !message->end) {
        WARNING1("message === NULL");
        return;
    }

    selector = message->end->code.verb;
    fifo = get_fifo(self, selector);
    node = calloc(sizeof(message_node_t), 1);

    if (!fifo)
        fifo = add_fifo(self, selector);

    if (fifo->closed_p) {
        /* destroy the message and the context objects */
        bytecode_stream_retire(message);
        context_retire(context);

        return;
    }

    /*
       insert message in the right position

       messages are ordered by decreasing context from beginning to end.
    */
    if (get_node_iterator(fifo, &it)) {
        message_node_t *current = NULL;
        message_node_t *last = NULL;

        TRACE3("adding at: %f in fifo: %s", context->ms,
               atom_get_cstring_value(fifo->atom));

        while ((current = node_iterator_next(&it)) &&
               context->is_in(context, current->context)) {
            /* advance until context is not anymore in current context */
            TRACE2("current at: %f", current->context->ms);
            last = current;
        }

        if (last == NULL) {
            if (fifo->end == NULL) {
                TRACE1("append to empty fifo");
                node->next = node;
                node->prev = node;
                fifo->end = node;
            } else {
                if (context->is_in(context, current->context)) {
                    TRACE2("insert after current at %f", current->context->ms);
                    node->prev = current;
                    node->next = current->next;
                    current->next = node;
                    node->next->prev = node;
                } else {
                    TRACE2("insert before current at %f", current->context->ms);
                    node->next = current;
                    node->prev = current->prev;
                    current->prev = node;
                    node->prev->next = node;
                }
                if (current == fifo->end)
                    fifo->end = node;
            }
        } else {
            if (context->is_in(context, last->context)) {
                TRACE2("insert after last at %f", last->context->ms);
                node->prev = last;
                node->next = last->next;
                last->next = node;
                node->next->prev = node;
            } else {
                TRACE2("insert before last at %f", last->context->ms);
                node->next = last;
                node->prev = last->prev;
                last->prev = node;
                node->prev->next = node;
            }
            if (last == fifo->end)
                fifo->end = node;
        }
    }
    node->bytecodes = message;
    node->context = context;
    node->dispatched_p = 0;

    if (node->context->dispatch_now_p) {
        self->eval(self, node->bytecodes, node->context);
        node->dispatched_p = 1;
    }
}
Example #20
0
/*! \fn int simplex_initialization(DATA* data, INIT_DATA* initData)
 *
 *  This function performs initialization by using the simplex algorithm.
 *  This does not require a jacobian for the residuals.
 */
int simplex_initialization(INIT_DATA* initData)
{
  int ind = 0;
  double funcValue = 0;
  double STOPCR = 0, SIMP = 0;
  long IPRINT = 0, NLOOP = 0, IQUAD = 0, IFAULT = 0, MAXF = 0;

  double *STEP = (double*)malloc(initData->nVars * sizeof(double));
  double *VAR = (double*)malloc(initData->nVars * sizeof(double));
  ASSERT(STEP, "out of memory");
  ASSERT(VAR, "out of memory");

  /* Start with stepping .5 in each direction. */
  for(ind = 0; ind<initData->nVars; ind++)
  {
    /* some kind of scaling */
    STEP[ind] = (initData->vars[ind] !=0.0 ? fabs(initData->vars[ind])/1000.0 : 1);    /* 1.0 */
    VAR[ind]  = 0.0;
  }

  /* Set max. no. of function evaluations = 5000, print every 100. */

  MAXF = 1000 * initData->nVars;
  IPRINT = ACTIVE_STREAM(LOG_INIT) ? MAXF/10 : -1;

  /* Set value for stopping criterion.   Stopping occurs when the
  * standard deviation of the values of the objective function at
  * the points of the current simplex < stopcr. */

  STOPCR = 1.e-12;
  NLOOP = initData->nVars;

  /* Fit a quadratic surface to be sure a minimum has been found. */

  IQUAD = 0;

  /* As function value is being evaluated in DOUBLE PRECISION, it
  * should be accurate to about 15 decimals.   If we set simp = 1.d-6,
  * we should get about 9 dec. digits accuracy in fitting the surface. */

  SIMP = 1.e-12;

  /* Now call NELMEAD to do the work. */
  funcValue = leastSquareWithLambda(initData, 1.0);

  if(fabs(funcValue) != 0)
  {
    globalData = initData->simData;
    globalInitialResiduals = initData->initialResiduals;

    NELMEAD(initData->vars, STEP, &initData->nVars, &funcValue, &MAXF, &IPRINT, &STOPCR, &NLOOP, &IQUAD, &SIMP, VAR, leastSquare, &IFAULT);

    globalData = NULL;
    globalInitialResiduals = NULL;
  }
  else
  {
    INFO1(LOG_INIT, "simplex_initialization | Result of leastSquare method = %g. The initial guess fits to the system", funcValue);
  }

  funcValue = leastSquareWithLambda(initData, 1.0);
  INFO1(LOG_INIT, "leastSquare=%g", funcValue);

  if(IFAULT == 1)
  {
    if(SIMP < funcValue)
    {
      WARNING1(LOG_INIT, "Error in initialization. Solver iterated %d times without finding a solution", (int)MAXF);
      return -1;
    }
  }
  else if(IFAULT == 2)
  {
    WARNING(LOG_INIT, "Error in initialization. Inconsistent initial conditions.");
    return -2;
  }
  else if(IFAULT == 3)
  {
    WARNING(LOG_INIT, "Error in initialization. Number of initial values to calculate < 1");
    return -3;
  }
  else if(IFAULT == 4)
  {
    WARNING(LOG_INIT, "Error in initialization. Internal error, NLOOP < 1.");
    return -4;
  }
  return reportResidualValue(initData);
}
Example #21
0
void CsLibGen::save_source(const char *filename, const CompilerInterface &compiler_wrapper,const char *default_csexe,bool lock_csexe)
{
  FUNCTION_TRACE;
  int i;
  FILE *f;
  char signature_str[CHAINE_LEN];
  char tmp[CHAINE_LEN];
  char indexstr[CHAINE_LEN];
  char *default_csexe_escaped=NULL;
  if (default_csexe)
  {
    default_csexe_escaped = (char*)MALLOC(strlen(default_csexe)*2+1) ;
    escape(default_csexe,default_csexe_escaped);
  }
  DEBUG1("==== begin generating __cs_libgen.cs source code ====\n");

  if (filename==NULL)
    f=stdout;
  else
    f=fopen(filename,"w");

  if (f==NULL)
  {
    FATAL2("Could not open %s with write access\n",filename);
  }
  if (nb_data==0)
  {
    WARNING1("No object files compiled with code coverage support\n");
  }
  fputs_trace("#pragma warning disable\n",f);
  fputs_trace("using System;\n",f);
  fputs_trace("using System.IO;\n",f);
  fputs_trace("using System.Text;\n",f);
  if (compiler_wrapper.setupMS())
    fputs_trace("using System.Runtime.InteropServices;\n",f);
  fputs_trace("class CoverageScanner\n",f);
  fputs_trace("{\n",f);
  if (lock_csexe)
  {
    fputs_trace("const int  CS_TIMEOUT=3000;\n",f);
  }
  fputs_trace("static string __cs_appname=\"",f);
  fputs_trace(default_csexe_escaped,f);
  fputs_trace(".csexe\";\n",f);
  fputs_trace("static System.IO.Stream __fopenread(string name) { return new FileStream(name,FileMode.Create,FileAccess.Read); }\n",f);
  fputs_trace("static System.IO.Stream __fopenappend(string name) { return new FileStream(name,FileMode.Append,FileAccess.Write); }\n",f);
  fputs_trace("static System.IO.Stream __fopenwrite(string name) { return new FileStream(name,FileMode.Create,FileAccess.Write); }\n",f);
  fputs_trace("static void __remove(string name) { System.IO.File.Delete(name); }\n",f);
  fputs_trace("static void __fputs(string data,System.IO.Stream stream) { System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();stream.Write(encoding.GetBytes(data),0,data.Length); }\n",f);
  fputs_trace("static string __fgets(System.IO.Stream stream) \n",f);
  fputs_trace(" { byte[] bytes= new byte[1024];  int numBytesToRead=1024; int numBytesRead=0; int n=stream.Read(bytes,numBytesRead,numBytesToRead); return Encoding.ASCII.GetString(bytes,0,n);}\n",f);
  fputs_trace("static void __fclose(System.IO.Stream stream) { stream.Close(); }\n",f);
  fputs_trace("static string __cs_testname=\"\";\n",f);
  fputs_trace("static string __cs_teststate=\"\";\n",f);

  /* Custom IO delegates */
  fputs_trace("public delegate string __cs_fgets_delegate(System.IO.Stream stream);\n",f);
  fputs_trace("public delegate void __cs_fputs_delegate(string s, System.IO.Stream stream);\n",f);
  fputs_trace("public delegate System.IO.Stream __cs_fopenappend_delegate(string path);\n",f);
  fputs_trace("public delegate System.IO.Stream __cs_fopenread_delegate(string path);\n",f);
  fputs_trace("public delegate System.IO.Stream __cs_fopenwrite_delegate(string path);\n",f);
  fputs_trace("public delegate void __cs_fclose_delegate(System.IO.Stream fp);\n",f);
  fputs_trace("public delegate void __cs_remove_delegate(string n);\n",f);
  /* Custom IO */
  fputs_trace("static __cs_fgets_delegate __cs_fgets =  new __cs_fgets_delegate(__fgets);\n",f);
  fputs_trace("static __cs_fputs_delegate __cs_fputs =  new __cs_fputs_delegate(__fputs);\n",f);
  fputs_trace("static __cs_fopenappend_delegate __cs_fopenappend =  new __cs_fopenappend_delegate(__fopenappend);\n",f);
  fputs_trace("static __cs_fopenread_delegate __cs_fopenread =  new __cs_fopenread_delegate(__fopenread);\n",f);
  fputs_trace("static __cs_fopenwrite_delegate __cs_fopenwrite =  new __cs_fopenwrite_delegate(__fopenwrite);\n",f);
  fputs_trace("static __cs_fclose_delegate __cs_fclose =  new __cs_fclose_delegate(__fclose);\n",f);
  fputs_trace("static __cs_remove_delegate __cs_remove =  new __cs_remove_delegate(__remove);\n",f);

  fputs_trace("static string __out_buffer=\"\";\n",f);
  fputs_trace("static string cs_fgets(System.IO.Stream stream)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  return __cs_fgets(stream);\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static void cs_fputs(string s, System.IO.Stream stream)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  const int max_lg=1024;\n",f);
  fputs_trace("  int lg=s.Length;\n",f);
  fputs_trace("  int __out_buffer_lg=__out_buffer.Length;\n",f);
  fputs_trace("  if  (lg+__out_buffer_lg>=max_lg)\n",f);
  fputs_trace("  {\n",f);
  fputs_trace("    if (__out_buffer_lg>0) __cs_fputs(__out_buffer,stream);\n",f);
  fputs_trace("    __out_buffer=\"\";\n",f);
  fputs_trace("  }\n",f);
  fputs_trace("  if  (lg>=max_lg)\n",f);
  fputs_trace("  {\n",f);
  fputs_trace("    __cs_fputs(s,stream);\n",f);
  fputs_trace("    return ;\n",f);
  fputs_trace("  }\n",f);
  fputs_trace("  __out_buffer+=s;\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static System.IO.Stream cs_fopenappend(string path)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __out_buffer=\"\";\n",f);
  fputs_trace("  return __cs_fopenappend(path);\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static System.IO.Stream cs_fopenread(string path)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __out_buffer=\"\";\n",f);
  fputs_trace("  return __cs_fopenread(path);\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static System.IO.Stream cs_fopenwrite(string path)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __out_buffer=\"\";\n",f);
  fputs_trace("  return __cs_fopenwrite(path);\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static void cs_fclose(System.IO.Stream fp)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  if (__out_buffer.Length!=0) __cs_fputs(__out_buffer,fp);\n",f);
  fputs_trace("  __out_buffer=\"\";\n",f);
  fputs_trace("  __cs_fclose(fp);\n",f);
  fputs_trace("}\n",f);
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_set_custom_io(",f);
  fputs_trace("__cs_fgets_delegate cs_fgets,\n",f);
  fputs_trace("__cs_fputs_delegate cs_fputs,\n",f);
  fputs_trace("__cs_fopenappend_delegate cs_fopenappend,\n",f);
  fputs_trace("__cs_fopenread_delegate cs_fopenread,\n",f);
  fputs_trace("__cs_fopenwrite_delegate cs_fopenwrite,\n",f);
  fputs_trace("__cs_fclose_delegate cs_fclose,\n",f);
  fputs_trace("__cs_remove_delegate cs_remove\n",f);
  fputs_trace(")\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __cs_fgets=cs_fgets;\n",f);
  fputs_trace("  __cs_fputs=cs_fputs;\n",f);
  fputs_trace("  __cs_fopenappend=cs_fopenappend;\n",f);
  fputs_trace("  __cs_fopenread=cs_fopenread;\n",f);
  fputs_trace("  __cs_fopenwrite=cs_fopenwrite;\n",f);
  fputs_trace("  __cs_fclose=cs_fclose;\n",f);
  fputs_trace("  __cs_remove=cs_remove;\n",f);
  fputs_trace("}\n",f);

  fputs_trace("struct __cs_exec_t { public int size; public int signature; public string name;public int []values;} ;\n",f);
  fputs_trace("static __cs_exec_t []__cs_exec= null;\n",f);

  /* Checksum for lockfile */
  fputs_trace("static int __checksum_over_coverage()\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  int i,item;\n",f);
  fputs_trace("  int chksum=0;\n",f);
  fputs_trace("  for (item=0;__cs_exec[item].name!=null;item++)\n",f);
  fputs_trace("  {\n",f);
  fputs_trace("    for (i=0;i<__cs_exec[item].size;i++)\n",f);
  fputs_trace("      {\n",f);
  fputs_trace("          chksum += __cs_exec[item].values[i];\n",f);
  fputs_trace("      }\n",f);
  fputs_trace("  }\n",f);
  fputs_trace("  return chksum;\n",f);
  fputs_trace("}\n",f);
  fputs_trace("\n",f);

  /* init function of the table */
  fputs_trace("static string __cs_int2hex(int v)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  string h=\"\";\n",f);
  fputs_trace("  int i;\n",f);
  fputs_trace("  for (i=0;i<8;i++)\n",f);
  fputs_trace("  {\n",f);
  fputs_trace("    char c;\n",f);
  fputs_trace("    c=(char)((v>>(4*(7-i))) & 0xF);\n",f);
  fputs_trace("    if (c<=9)\n",f);
  fputs_trace("      c+='0';\n",f);
  fputs_trace("    else\n",f);
  fputs_trace("      c+=(char)('A'-10);\n",f);
  fputs_trace("    h+=c;\n",f);
  fputs_trace("  }\n",f);
  fputs_trace("  return h;\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static void __cs_sem_init()\n",f);
  fputs_trace("{\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static int __cs_sem_lock()\n",f);
  fputs_trace("{\n",f);
  if (lock_csexe)
  {
    fputs_trace("  System.DateTime start_time=System.DateTime.Now;\n",f);
    fputs_trace("  System.DateTime end_time;\n",f);
    fputs_trace("  string lockfile;\n",f);
    fputs_trace("  string str;\n",f);
    fputs_trace("  string str2;\n",f);
    fputs_trace("  System.IO.Stream f=null;\n\n",f);
    fputs_trace("  if (__cs_fgets==null) return 1;\n",f);
    fputs_trace("  str=\"cs:\";\n",f);
    fputs_trace("  str+=__cs_int2hex(System.Diagnostics.Process.GetCurrentProcess().Id);\n",f);
    fputs_trace("  str+=\":\";\n",f);
    fputs_trace("  str+=__cs_int2hex(start_time.Second*1000+start_time.Minute*60000+start_time.Millisecond);\n",f);
    fputs_trace("  str+=\":\";\n",f);
    fputs_trace("  str+=__cs_int2hex(__checksum_over_coverage());\n",f);
    fputs_trace("  lockfile=__cs_appname;\n",f);
    fputs_trace("  lockfile+=\".lck\";\n",f);
    fputs_trace("  start_time=System.DateTime.Now;\n",f);
    fputs_trace("  for (end_time=start_time;(end_time-start_time).Seconds<CS_TIMEOUT;end_time=System.DateTime.Now)\n",f);
    fputs_trace("  {\n",f);
    fputs_trace("    int canlock=0;\n",f);
    fputs_trace("    try {\n",f);
    fputs_trace("      f=cs_fopenread(lockfile);\n",f);
    fputs_trace("    } \n",f);
    fputs_trace("    catch \n",f);
    fputs_trace("    {\n",f);
    fputs_trace("      canlock=1;\n",f);
    fputs_trace("      f=null;\n",f);
    fputs_trace("    }\n",f);
    fputs_trace("    if (f!=null)\n",f);
    fputs_trace("    {\n",f);
    fputs_trace("      try {\n",f);
    fputs_trace("        f=cs_fopenread(lockfile);\n",f);
    fputs_trace("        str2=cs_fgets(f);  \n",f);
    fputs_trace("        cs_fclose(f);\n",f);
    fputs_trace("        if (str2==\"\")\n",f);
    fputs_trace("          canlock=1;\n",f);
    fputs_trace("      } catch {}\n",f);
    fputs_trace("    } \n",f);
    fputs_trace("    if (canlock==1)\n",f);
    fputs_trace("    {\n",f);
    fputs_trace("      try \n",f);
    fputs_trace("      {\n",f);
    fputs_trace("        f=cs_fopenwrite(lockfile);  \n",f);
    fputs_trace("        cs_fputs(str,f);  \n",f);
    fputs_trace("        cs_fclose(f);\n",f);
    fputs_trace("        f=cs_fopenread(lockfile);  \n",f);
    fputs_trace("        str2=cs_fgets(f);  \n",f);
    fputs_trace("        cs_fclose(f);\n",f);
    fputs_trace("        if (str2==str)\n",f);
    fputs_trace("          return 1;\n",f);
    fputs_trace("      } catch {}\n",f);
    fputs_trace("    }\n",f);
    fputs_trace("  }\n",f);
    fputs_trace("  return 0;\n",f);
  }
  else
    fputs_trace("  return 1;\n",f);
  fputs_trace("}\n",f);
  fputs_trace("static void __cs_sem_unlock()\n",f);
  fputs_trace("{\n",f);
  if (lock_csexe)
  {
    fputs_trace("try \n",f);
    fputs_trace("{\n",f);
    fputs_trace("  string lockfile;\n",f);
    fputs_trace("  if (__cs_fgets==null) return ;\n",f);
    fputs_trace("  lockfile=__cs_appname;\n",f);
    fputs_trace("  lockfile+=\".lck\";\n",f);
    fputs_trace("  if (__cs_remove!=null)\n",f);
    fputs_trace("    __cs_remove(lockfile);\n",f);
    fputs_trace("  else\n",f);
    fputs_trace("  {\n",f);
    fputs_trace("    System.IO.Stream f;\n\n",f);
    fputs_trace("    f=cs_fopenwrite(lockfile);  \n",f);
    fputs_trace("    cs_fclose(f);\n",f);
    fputs_trace("  }\n",f);
    fputs_trace("} catch {}\n",f);
  }
  fputs_trace("}\n",f);
  fputs_trace("static void __cs_exec_init()\n",f);
  fputs_trace("{\n",f);
  fputs_trace("try \n",f);
  fputs_trace("{\n",f);

  fputs_trace("  if (__cs_exec!=null) return ;\n\n",f);
  fputs_trace("  __cs_exec_t []exectab = new __cs_exec_t[",f);
  sprintf(tmp,"%lu",nb_data+1);
  fputs_trace(tmp,f);
  fputs_trace("  ];\n\n",f);
  fputs_trace("  __cs_exec=exectab;\n\n",f);
  for (i=0;i<nb_data;i++)
  {
    char table_name[INSTRUMENTATION_CODE_MAX_LENGTH] ;
    char filename_abs[MAX_PATH];
    realPath(datas[i].filename,filename_abs);
    Source::instrumentation_table(filename_abs,table_name);

    fputs_trace("  /* ",f);
    fputs_trace(filename_abs,f);
    fputs_trace(" */\n",f);
    sprintf(indexstr,"%i",i);
    sprintf(tmp,"  __cs_exec[%i]",i);

    fputs_trace(tmp,f);
    fputs_trace(".signature=",f);
    sprintf(signature_str,"%lu",datas[i].signature);
    fputs_trace(signature_str,f);
    fputs_trace(";\n",f);

    fputs_trace(tmp,f);
    fputs_trace(".name=",f);
    fputs_trace("\"",f);
    {
      char table_name[INSTRUMENTATION_CODE_MAX_LENGTH] ;
      char filename_abs_escape[MAX_PATH*2];
      char filename_abs[MAX_PATH];
      realPath(datas[i].filename,filename_abs);
      Source::instrumentation_table(filename_abs,table_name);
      escape(filename_abs,filename_abs_escape);
      fputs_trace(filename_abs_escape,f);
    }
    fputs_trace("\";\n",f);

    fputs_trace(tmp,f);
    fputs_trace(".values=",f);
    fputs_trace(table_name,f);
    fputs_trace(".val;\n",f);

    fputs_trace(tmp,f);
    fputs_trace(".size=",f);
    fputs_trace(table_name,f);
    fputs_trace(".nb;\n",f);
  }
  sprintf(tmp,"  __cs_exec[%i]",i);
  fputs_trace(tmp,f);
  fputs_trace(".signature=0;\n",f);

  fputs_trace(tmp,f);
  fputs_trace(".name=null;\n",f);

  fputs_trace(tmp,f);
  fputs_trace(".values=null;\n",f);

  fputs_trace(tmp,f);
  fputs_trace(".size=0;\n",f);
  fputs_trace("} catch {}\n",f);
  fputs_trace("}\n",f);


  /* __coveragescanner_save */
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_save()\n",f);
  fputs_trace("{\n",f);
  fputs_trace("try \n",f);
  fputs_trace("{\n",f);
  fputs_trace("  int i,item;\n",f);
  fputs_trace("  System.IO.Stream f;\n\n",f);

  fputs_trace("  __cs_sem_init();\n",f);
  fputs_trace("  __cs_exec_init();\n",f);
  fputs_trace("  if (__cs_sem_lock()==0) return ;\n",f);
  fputs_trace("  f=cs_fopenappend(__cs_appname);\n",f);
  fputs_trace("  if (f==null) return ;\n",f);

  fputs_trace("  try {\n",f);
  fputs_trace("  if (__cs_testname!=\"\") {\n",f);
  fputs_trace("    cs_fputs(\"*\",f);\n",f);
  fputs_trace("    cs_fputs(__cs_testname,f);\n",f);
  fputs_trace("    cs_fputs(\"\\n\",f);\n",f);
  fputs_trace("  }\n",f);

  fputs_trace("  cs_fputs(\"# Measurements\\n\",f);\n",f);

  /* Recording code */
  fputs_trace("  for (item=0;__cs_exec[item].name!=null;item++)\n",f);
  fputs_trace("  {\n",f);
  fputs_trace("    if (__cs_exec[item].size==0) continue;\n",f);
  fputs_trace("    bool empty=true;\n",f);
  fputs_trace("    for (i=0;i<__cs_exec[item].size;i++)\n",f);
  fputs_trace("      {\n",f);
  fputs_trace("          if (__cs_exec[item].values[i]!=0)\n",f);
  fputs_trace("             empty=false;\n",f);
  fputs_trace("      }\n",f);
  fputs_trace("    if (empty) continue;\n",f);
  fputs_trace("    cs_fputs(\"/\",f);\n",f);
  fputs_trace("    cs_fputs(Convert.ToString(__cs_exec[item].size),f);\n",f);
  fputs_trace("    cs_fputs(\":\",f);\n",f);
  fputs_trace("    cs_fputs(Convert.ToString(__cs_exec[item].signature),f);\n",f);
  fputs_trace("    cs_fputs(\":\",f);\n",f);
  fputs_trace("    cs_fputs(__cs_exec[item].name,f);\n",f);
  fputs_trace("    cs_fputs(\"\\n\",f);\n",f);

  fputs_trace("    cs_fputs(\"\\\\\",f);\n",f);

  fputs_trace("    for (i=0;i<__cs_exec[item].size;i++)\n",f);

  fputs_trace("      {\n",f);
  fputs_trace("        {\n",f);
  fputs_trace("          switch (__cs_exec[item].values[i])\n",f);
  fputs_trace("          {\n",f);
  fputs_trace("            case 1:\n",f);
  fputs_trace("              cs_fputs(\"+\",f);\n",f);
  fputs_trace("              break;\n",f);
  fputs_trace("            case 0:\n",f);
  fputs_trace("              cs_fputs(\"-\",f);\n",f);
  fputs_trace("              break;\n",f);
  fputs_trace("            default:\n",f);
  fputs_trace("              cs_fputs(__cs_int2hex(__cs_exec[item].values[i]),f);\n",f);
  fputs_trace("              break;\n",f);
  fputs_trace("          }\n",f);
  fputs_trace("        }\n",f);
  fputs_trace("        __cs_exec[item].values[i]=0;\n",f);
  fputs_trace("      }\n",f);
  fputs_trace("    cs_fputs(\"\\n\",f);\n",f);
  fputs_trace("  }\n",f);

  /* saving the execution statue */
  fputs_trace("  if (__cs_teststate!=\"\") {\n",f);
  fputs_trace("    cs_fputs(\"!\",f);\n",f);
  fputs_trace("    cs_fputs(__cs_teststate,f);\n",f);
  fputs_trace("    cs_fputs(\"\\n\",f);\n",f);
  fputs_trace("    __cs_teststate=\"\";\n",f);
  fputs_trace("  }\n",f);

  fputs_trace("  cs_fclose(f);\n",f);
  fputs_trace("  } catch  { cs_fclose(f); }\n",f);
  fputs_trace("  __cs_sem_unlock();\n",f);
  fputs_trace("} catch {}\n",f);
  fputs_trace("}\n",f);
  fputs_trace("\n",f);

  /* __coveragescanner_testname */
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_testname(string name)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __cs_testname=name;\n",f);
  fputs_trace("}\n",f);

  /* __coveragescanner_filename */
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_filename(string name)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("try \n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __cs_appname=name;\n",f);
  fputs_trace("  __cs_appname+=\".csexe\";\n",f);
  fputs_trace("} catch {}\n",f);
  fputs_trace("}\n",f);

  /* __coveragescanner_clear */
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_clear()\n",f);
  fputs_trace("{\n",f);
  fputs_trace("try \n",f);
  fputs_trace("{\n",f);
  fputs_trace("  int i,item;\n",f);
  fputs_trace("  __cs_sem_init();\n",f);
  fputs_trace("  __cs_exec_init();\n",f);
  fputs_trace("  for (item=0;__cs_exec[item].values!=null;item++)\n",f);
  fputs_trace("    for (i=0;i<__cs_exec[item].size;i++)\n",f);
  fputs_trace("        __cs_exec[item].values[i]=0;\n",f);
  fputs_trace("} catch {}\n",f);
  fputs_trace("}\n",f);
  fputs_trace("\n",f);

  /* __coveragescanner_teststate */
  fputs_trace("public static \n",f);
  fputs_trace("void ",f);
  fputs_trace(" __coveragescanner_teststate(string state)\n",f);
  fputs_trace("{\n",f);
  fputs_trace("  __cs_teststate=state;\n",f);
  fputs_trace("}\n",f);

  if (!compiler_wrapper.customSetup())
  {
    fputs_trace("static bool __cs_default_exit=true;\n",f);
    fputs_trace("static void __cs_exit()\n",f);
    fputs_trace("{\n",f);
    fputs_trace("  __coveragescanner_save();\n",f);
    fputs_trace("}\n",f);
    fputs_trace("static void __cs_exit_default()\n",f);
    fputs_trace("{\n",f);
    fputs_trace("  if (__cs_default_exit)\n",f);
    fputs_trace("    __cs_exit();\n",f);
    fputs_trace("}\n",f);
    fputs_trace("static void __cs_init()\n",f);
    fputs_trace("{\n",f);
    fputs_trace("  try {\n",f);
    fputs_trace("  __coveragescanner_filename(System.Environment.GetCommandLineArgs()[0]);\n",f);
    fputs_trace("  } catch\n",f);
    fputs_trace("  {__coveragescanner_filename(\"",f);
    fputs_trace(default_csexe_escaped,f);
    fputs_trace("\");}\n",f);
    fputs_trace("}\n",f);
  }
  fputs_trace("public class __cs_lib_t {\n",f);
  fputs_trace("  public",f);
  fputs_trace("  __cs_lib_t()\n",f);
  fputs_trace("    {\n",f);
  if (!compiler_wrapper.customSetup())
    fputs_trace("       CoverageScanner.__cs_init();\n",f);
  fputs_trace("    }\n",f);
  if (!compiler_wrapper.customSetup())
  {
    fputs_trace("  ~__cs_lib_t()\n",f);
    fputs_trace("    {\n",f);
    fputs_trace("       CoverageScanner.__cs_exit();\n",f);
    fputs_trace("    }\n",f);
  }
  fputs_trace("};\n",f);
  fputs_trace("}\n",f);

  if (filename!=NULL)
    fclose(f);
  DEBUG1("==== end generating __cs_libgen.cs source code ====\n");
  FREE(default_csexe_escaped);
}
Example #22
0
void
kpse_set_program_name P2C(const_string, argv0, const_string, progname)
{
  string ext, sdir, sdir_parent, sdir_grandparent;
  string s = getenv ("KPATHSEA_DEBUG");
#ifdef WIN32
  string debug_output = getenv("KPATHSEA_DEBUG_OUTPUT");
  string append_debug_output = getenv("KPATHSEA_DEBUG_APPEND");
  int err, olderr;
#endif
  
  /* Set debugging stuff first, in case we end up doing debuggable stuff
     during this initialization.  */
  if (s) {
    kpathsea_debug |= atoi (s);
  }

#ifndef HAVE_PROGRAM_INVOCATION_NAME
#if defined(WIN32)
  /* Set various info about user. Among many things,
     ensure that HOME is set. If debug_paths is on, 
     turn on some message if $HOME is not found. */
  if (KPSE_DEBUG_P(KPSE_DEBUG_PATHS)) {
    set_home_warning();
  }
  init_user_info();

  /* redirect stderr to debug_output. Easier to send logfiles. */
  if (debug_output) {
    int flags =  _O_CREAT | _O_TRUNC | _O_RDWR;
    err = -1;
    if (_stricmp(debug_output, "con") == 0
       || _stricmp(debug_output, "con:") == 0) {
      err = _fileno(stdout);
    } else {
      if (append_debug_output) {
        flags =  _O_CREAT | _O_APPEND | _O_WRONLY;
      } else {
        flags =  _O_CREAT | _O_TRUNC | _O_WRONLY;
        xputenv("KPATHSEA_DEBUG_APPEND", "yes");
      }
    }

    if ((err < 0)
        && (err = _open(debug_output, flags, _S_IREAD | _S_IWRITE)) == -1)
    {
      WARNING1("Can't open %s for stderr redirection!\n", debug_output);
      perror(debug_output);
    } else if ((olderr = _dup(fileno(stderr))) == -1) {
      WARNING("Can't dup() stderr!\n");
      close(err);
    } else if (_dup2(err, fileno(stderr)) == -1) {
      WARNING1("Can't redirect stderr to %s!\n", debug_output);
      close(olderr);
      close(err);
    } else {
      close(err);
    }
  }
  /* Win95 always gives the short filename for argv0, not the long one.
     There is only this way to catch it. It makes all the selfdir stuff
     useless for win32. */
  {
    char short_path[PATH_MAX], path[PATH_MAX], *fp;
      
    /* SearchPath() always gives back an absolute directory */
    if (SearchPath(NULL, argv0, ".exe", PATH_MAX, short_path, &fp) == 0)
        FATAL1("Can't determine where the executable %s is.\n", argv0);
    if (!win32_get_long_filename(short_path, path, sizeof(path))) {
        FATAL1("This path points to an invalid file : %s\n", short_path);
    }
    /* slashify the dirname */
    for (fp = path; fp && *fp; fp++)
        if (IS_DIR_SEP(*fp)) *fp = DIR_SEP;
    /* sdir will be the directory of the executable, ie: c:/TeX/bin */
    sdir = xdirname(path);
    program_invocation_name = xstrdup(xbasename(path));
  }

#elif defined(__DJGPP__)

  /* DJGPP programs support long filenames on Windows 95, but ARGV0 there
     is always made with the short 8+3 aliases of all the pathname elements.
     If long names are supported, we need to convert that to a long name.

     All we really need is to call `_truename', but most of the code
     below is required to deal with the special case of networked drives.  */
  if (pathconf (argv0, _PC_NAME_MAX) > 12) {
    char long_progname[PATH_MAX];

    if (_truename (argv0, long_progname)) {
      char *fp;

      if (long_progname[1] != ':') {
	/* A complication: `_truename' returns network-specific string at
	   the beginning of `long_progname' when the program resides on a
	   networked drive, and DOS calls cannot grok such pathnames.  We
	   need to convert the filesystem name back to a drive letter.  */
	char rootname[PATH_MAX], rootdir[4];

	if (argv0[0] && argv0[1] == ':')
	  rootdir[0] = argv0[0]; /* explicit drive in `argv0' */
	else
	  rootdir[0] = getdisk () + 'A';
	rootdir[1] = ':';
	rootdir[2] = '\\';
	rootdir[3] = '\0';
	if (_truename (rootdir, rootname)) {
	  /* Find out where `rootname' ends in `long_progname' and replace
	     it with the drive letter.  */
	  int root_len = strlen (rootname);

 	  if (IS_DIR_SEP (rootname[root_len - 1]))
            root_len--;	/* keep the trailing slash */
	  long_progname[0] = rootdir[0];
	  long_progname[1] = ':';
	  memmove (long_progname + 2, long_progname + root_len,
		   strlen (long_progname + root_len) + 1);
	}
      }

      /* Convert everything to canonical form.  */
      if (long_progname[0] >= 'A' && long_progname[0] <= 'Z')
	long_progname[0] += 'a' - 'A'; /* make drive lower case, for beauty */
      for (fp = long_progname; *fp; fp++)
	if (IS_DIR_SEP (*fp))
	  *fp = DIR_SEP;

      program_invocation_name = xstrdup (long_progname);
    }
    else
      /* If `_truename' failed, God help them, because we won't...  */
      program_invocation_name = xstrdup (argv0);
  }
  else
    program_invocation_name = xstrdup (argv0);

#else /* !WIN32 && !__DJGPP__ */

  program_invocation_name = xstrdup (argv0);

#endif
#endif /* not HAVE_PROGRAM_INVOCATION_NAME */

  /* We need to find SELFAUTOLOC *before* removing the ".exe" suffix from
     the program_name, otherwise the PATH search inside selfdir will fail,
     since `prog' doesn't exists as a file, there's `prog.exe' instead.  */
#ifndef WIN32
  sdir = selfdir (program_invocation_name);
#endif
  /* SELFAUTODIR is actually the parent of the invocation directory,
     and SELFAUTOPARENT the grandparent.  This is how teTeX did it.  */
  xputenv ("SELFAUTOLOC", sdir);
  sdir_parent = xdirname (sdir);
  xputenv ("SELFAUTODIR", sdir_parent);
  sdir_grandparent = xdirname (sdir_parent);
  xputenv ("SELFAUTOPARENT", sdir_grandparent);

  free (sdir);
  free (sdir_parent);
  free (sdir_grandparent);

#ifndef HAVE_PROGRAM_INVOCATION_NAME
  program_invocation_short_name = (string)xbasename (program_invocation_name);
#endif

  if (progname) {
    kpse_program_name = xstrdup (progname);
  } else {
    /* If configured --enable-shared and running from the build directory
       with the wrapper scripts (e.g., for make check), the binaries will
       be named foo.exe instead of foo.  Or possibly if we're running on a
       DOSISH system.  */
    ext = find_suffix (program_invocation_short_name);
    if (ext && FILESTRCASEEQ (ext, "exe")) {
      kpse_program_name = remove_suffix (program_invocation_short_name);
    } else {
      kpse_program_name = xstrdup (program_invocation_short_name);
    }
  }
  xputenv("progname", kpse_program_name);
}
Example #23
0
/* for now just 16bit signed values, mono channels FIXME
 * maybe use SDL_AudioConvert() for this */
int
mm_decode_audio(mm_file *mf, void *buf, int buflen)
{
    const int max_val = 32767;
    const int min_val = -32768;
    const int bytes_per_sample = 2;

    int rv = 0, samples = 0, left = 0, total = 0;
    unsigned channels = 0;

    assert(mf);

    if (-1 == mm_audio_info(mf, &channels, NULL)) {
        return -1;
    }

    if (mf->drop_packets & MEDIA_AUDIO) {
        WARNING1("requested decode but MEDIA_AUDIO is set to ignore");
        return -1;
    }

    /* convert buflen [bytes] to left [samples] */
    left = buflen;
    left = left / channels / bytes_per_sample;

    while (left > 0) {
        float **pcm;
        ogg_packet pkt;

        /* also outputs any samples left from last decoding */
        while (left > 0
               && (samples = vorbis_synthesis_pcmout(mf->audio_ctx, &pcm)) > 0) {
            int i = 0;
            unsigned ch = 0;

            samples = MIN(samples, left);

            for (i = 0; i < samples; ++i) {
                for (ch = 0; ch < channels; ++ch) {
                    // lrint is not available on MSVC
#ifdef HAVE_LRINT
                    int val = lrint(pcm[ch][i] * max_val);
#else
                    int val = (int)floor(pcm[ch][i] * max_val);
#endif

                    if (val > max_val) {
                        val = max_val;
                    }

                    if (val < min_val) {
                        val = min_val;
                    }

                    *((int16_t *) buf + (total + i) * channels + ch) = val;
                }
            }

            total += samples;
            left -= samples;
            vorbis_synthesis_read(mf->audio_ctx, samples);

        }

        /* grab new packets if we need more */
        for (;;) {
            rv = get_packet(mf, &pkt, MEDIA_AUDIO);

            if (rv < 0) {
                return rv;
            } else if (rv == 0) {
                return total * channels * bytes_per_sample;
            }

            /* have packet, synthesize */
            if (vorbis_synthesis(mf->audio_blk, &pkt) == 0) {
                vorbis_synthesis_blockin(mf->audio_ctx, mf->audio_blk);
                break;
            } else {
                WARNING1("packet does not contain a valid vorbis frame");
                /* get next packet */
            }
        }
    }

    return total * channels * bytes_per_sample;
}
Example #24
0
static boolean
db_build (kpathsea kpse, hash_table_type *table,  const_string db_filename)
{
  string line;
  unsigned dir_count = 0, file_count = 0, ignore_dir_count = 0;
  unsigned len = strlen (db_filename) - sizeof (DB_NAME) + 1; /* Keep the /. */
  string top_dir = (string)xmalloc (len + 1);
  string cur_dir = NULL; /* First thing in ls-R might be a filename.  */
  FILE *db_file = fopen (db_filename, FOPEN_R_MODE);
#if defined(WIN32)
  string pp;
#endif

  strncpy (top_dir, db_filename, len);
  top_dir[len] = 0;

  if (db_file) {
    while ((line = read_line (db_file)) != NULL) {
      len = strlen (line);

#if defined(WIN32)
      for (pp = line; *pp; pp++) {
        if (IS_KANJI(pp))
          pp++;
        else
          *pp = TRANSFORM(*pp);
      }
#endif

      /* A line like `/foo:' = new dir foo.  Allow both absolute (/...)
         and explicitly relative (./...) names here.  It's a kludge to
         pass in the directory name with the trailing : still attached,
         but it doesn't actually hurt.  */
      if (len > 0 && line[len - 1] == ':'
          && kpathsea_absolute_p (kpse, line, true)) {
        /* New directory line.  */
        if (!ignore_dir_p (line)) {
          /* If they gave a relative name, prepend full directory name now.  */
          line[len - 1] = DIR_SEP;
          /* Skip over leading `./', it confuses `match' and is just a
             waste of space, anyway.  This will lose on `../', but `match'
             won't work there, either, so it doesn't matter.  */
          cur_dir = *line == '.' ? concat (top_dir, line + 2) : xstrdup (line);
          dir_count++;
        } else {
          cur_dir = NULL;
          ignore_dir_count++;
        }

      /* Ignore blank, `.' and `..' lines.  */
      } else if (*line != 0 && cur_dir   /* a file line? */
                 && !(*line == '.'
                      && (line[1] == 0 || (line[1] == '.' && line[2] == 0))))
      {
        /* Make a new hash table entry with a key of `line' and a data
           of `cur_dir'.  An already-existing identical key is ok, since
           a file named `foo' can be in more than one directory.  Share
           `cur_dir' among all its files (and hence never free it).

           Note that we assume that all names in the ls-R file have already
           been case-smashed to lowercase where appropriate.
        */
        hash_insert_normalized (table, xstrdup (line), cur_dir);
        file_count++;

      } /* else ignore blank lines or top-level files
           or files in ignored directories*/

      free (line);
    }

    xfclose (db_file, db_filename);

    if (file_count == 0) {
      WARNING1 ("kpathsea: %s: No usable entries in ls-R", db_filename);
      WARNING ("kpathsea: See the manual for how to generate ls-R");
      db_file = NULL;
    } else {
      str_list_add (&(kpse->db_dir_list), xstrdup (top_dir));
    }

#ifdef KPSE_DEBUG
    if (KPATHSEA_DEBUG_P (KPSE_DEBUG_HASH)) {
      /* Don't make this a debugging bit, since the output is so
         voluminous, and being able to specify -1 is too useful.
         Instead, let people who want it run the program under
         a debugger and change the variable that way.  */
      boolean hash_summary_only = true;

      DEBUGF4 ("%s: %u entries in %d directories (%d hidden).\n",
               db_filename, file_count, dir_count, ignore_dir_count);
      DEBUGF ("ls-R hash table:");
      hash_print (*table, hash_summary_only);
      fflush (stderr);
    }
#endif /* KPSE_DEBUG */
  }

  free (top_dir);

  return db_file != NULL;
}
Example #25
0
static int
yuv_to_overlay(const mm_file *mf, const yuv_buffer *yuv, SDL_Overlay *ovl)
{
    unsigned i, h, w, xoff, yoff;
    uint8_t *yp, *up, *vp;

    assert(mf);
    assert(yuv);
    assert(ovl);

    h = MIN(mf->video_info->frame_height, (unsigned) ovl->h);
    w = MIN(mf->video_info->frame_width, (unsigned) ovl->w);
    xoff = mf->video_info->offset_x;
    yoff = mf->video_info->offset_y;

    switch (ovl->format) {
    case SDL_IYUV_OVERLAY:
        up = yuv->u;
        vp = yuv->v;
        break;

    case SDL_YV12_OVERLAY:
        up = yuv->v;
        vp = yuv->u;
        break;

    default:
        WARNING1("only IYUV and YV12 SDL overlay formats supported");
        return -1;
    }

    yp = yuv->y;

    switch (mf->video_info->pixelformat) {
    case OC_PF_420:
        break;

    case OC_PF_422:
    case OC_PF_444:
    default:
        WARNING1("unknown/unsupported theora pixel format");
        return -1;
    }

    if (SDL_LockYUVOverlay(ovl) < 0) {
        WARNING1("unable to lock overlay");
        return -1;
    }

    /* luna goes first */
    for (i = 0; i < h; ++i) {
        memcpy(ovl->pixels[0] + i * ovl->pitches[0],
               yp + (i + yoff) * yuv->y_stride + xoff, w);
    }

    xoff /= 2;
    yoff /= 2;
    /* round up */
    w = w / 2 + w % 2;
    h = h / 2 + h % 2;

    /* handle 2x2 subsampled u and v planes */
    for (i = 0; i < h; ++i) {
        memcpy(ovl->pixels[1] + i * ovl->pitches[1],
               up + (i + yoff) * yuv->uv_stride + xoff, w);
        memcpy(ovl->pixels[2] + i * ovl->pitches[2],
               vp + (i + yoff) * yuv->uv_stride + xoff, w);
    }

    SDL_UnlockYUVOverlay(ovl);
    return 0;
}
Example #26
0
/* rval < 0: error, > 0: have audio or video */
int
mm_open_fp(mm_file *mf, FILE *file)
{
    int retval = -1;
    int res = 0;
    int have_vorbis = 0;
    int have_theora = 0;
    ogg_page pg;

    assert(mf);
    memset(mf, 0, sizeof(*mf));

    mf->file = file;

    // This is important.  If there is no file
    // then we need to reset the audio and video
    // pointers so that the other functions
    // ignore the file.
    if (!mf->file) {
        mf->audio = NULL;
        mf->video = NULL;
        return retval;
    }

    ogg_sync_init(&mf->sync);

    /* get first page to start things up */
    if (get_page(mf, &pg) <= 0) {
        goto err;
    }

    DEBUG1("trying theora decoder...");
    res = init_theora(mf, &pg);

    if (res < 0) {
        goto err;
    } else {
        have_theora = !!res * MEDIA_VIDEO;
    }

    DEBUG1("trying vorbis decoder...");
    res = init_vorbis(mf, &pg);

    if (res < 0) {
        goto err;
    } else {
        have_vorbis = !!res * MEDIA_AUDIO;
    }

    if (have_vorbis) {
        unsigned c = 0, r = 0;
        mm_audio_info(mf, &c, &r);
        INFO3("audio %u channel(s) at %u Hz", c, r);
    }

    if (have_theora) {
        unsigned w, h;
        float fps;
        mm_video_info(mf, &w, &h, &fps);
        INFO4("video %ux%u pixels at %g fps", w, h, fps);
    }

    return have_vorbis | have_theora;
err:
    WARNING1("unable to decode stream");
    mm_close(mf);
    return retval;
}
Example #27
0
string
kpathsea_var_expand (kpathsea kpse, const_string src)
{
  const_string s;
  string ret;
  fn_type expansion;
  expansion = fn_init ();

  /* Copy everything but variable constructs.  */
  for (s = src; *s; s++) {
    if (IS_VAR_START (*s)) {
      s++;

      /* Three cases: `$VAR', `${VAR}', `$<anything-else>'.  */
      if (IS_VAR_CHAR (*s)) {
        /* $V: collect name constituents, then expand.  */
        const_string var_end = s;

        do {
          var_end++;
        } while (IS_VAR_CHAR (*var_end));

        var_end--; /* had to go one past */
        if (!expand (kpse, &expansion, s, var_end)) {
          /* If no expansion, include the literal $x construct,
             so filenames containing dollar signs can be read.
             The first +1 is to get the full variable name,
             the other +1 is to get the dollar sign; we've moved past it.  */
          fn_grow (&expansion, s - 1, var_end - s + 1 + 1);
        }
        s = var_end;

      } else if (IS_VAR_BEGIN_DELIMITER (*s)) {
        /* ${: scan ahead for matching delimiter, then expand.  */
        const_string var_end = ++s;

        while (*var_end && !IS_VAR_END_DELIMITER (*var_end)) {
#if defined(WIN32)
          if (kpathsea_IS_KANJI(kpse, var_end))
            var_end++;
#endif
          var_end++;
        }

        if (! *var_end) {
          WARNING1 ("kpathsea: %s: No matching } for ${", src);
          s = var_end - 1; /* will incr to null at top of loop */
        } else {
          expand (kpse, &expansion, s, var_end - 1);
          s = var_end; /* will incr past } at top of loop*/
        }

      } else {
        /* $<something-else>: warn, but preserve characters; again, so
           filenames containing dollar signs can be read.  */
        WARNING2 ("kpathsea: %s: Unrecognized variable construct `$%c'",
                  src, *s);
        fn_grow (&expansion, s - 1, 2);  /* moved past the $  */
      }
    } else
     fn_1grow (&expansion, *s);
  }
  fn_1grow (&expansion, 0);

  ret = FN_STRING (expansion);
  return ret;
}
Example #28
0
int printModelInfo(DATA *data, const char *filename, const char *plotfile, const char *plotFormat, const char *method, const char *outputFormat, const char *outputFilename)
{
  static char buf[256];
  FILE *fout = fopen(filename, "w");
  FILE *plotCommands;
  time_t t;
  int i;
#if defined(__MINGW32__) || defined(_MSC_VER) || defined(NO_PIPE)
  plotCommands = fopen(plotfile, "w");
#else
  plotCommands = popen("gnuplot", "w");
#endif
  if(!plotCommands)
    WARNING1(LOG_UTIL, "Plots of profiling data were disabled: %s\n", strerror(errno));

  ASSERT2(fout, "Failed to open %s: %s\n", filename, strerror(errno));

  if(plotCommands) {
    fputs("set terminal svg\n", plotCommands);
    fputs("set nokey\n", plotCommands);
    fputs("set format y \"%g\"\n", plotCommands);
    /* The column containing the time spent to calculate each step */
    printPlotCommand(plotCommands, plotFormat, "Execution time of global steps", data->modelData.modelFilePrefix, data->modelData.modelDataXml.nFunctions+data->modelData.modelDataXml.nProfileBlocks, -1, 999, "");
  }
  /* The doctype is needed for id() lookup to work properly */
  fprintf(fout, "<!DOCTYPE doc [\
  <!ELEMENT simulation (modelinfo, variables, functions, equations)>\
  <!ATTLIST variable id ID #REQUIRED>\
  <!ELEMENT equation (refs)>\
  <!ATTLIST equation id ID #REQUIRED>\
  <!ELEMENT profileblocks (profileblock*)>\
  <!ELEMENT profileblock (refs, ncall, time, maxTime)>\
  <!ELEMENT refs (ref*)>\
  <!ATTLIST ref refid IDREF #REQUIRED>\
  ]>\n");
  if(time(&t) < 0)
  {
    WARNING1(LOG_UTIL, "time() failed: %s", strerror(errno));
    fclose(fout);
    return 1;
  }
  if(!strftime(buf, 250, "%Y-%m-%d %H:%M:%S", localtime(&t)))
  {
    WARNING(LOG_UTIL, "strftime() failed");
    fclose(fout);
    return 1;
  }
  fprintf(fout, "<simulation>\n");
  fprintf(fout, "<modelinfo>\n");
  indent(fout, 2); fprintf(fout, "<name>");printStrXML(fout,data->modelData.modelName);fprintf(fout,"</name>\n");
  indent(fout, 2); fprintf(fout, "<prefix>");printStrXML(fout,data->modelData.modelFilePrefix);fprintf(fout,"</prefix>\n");
  indent(fout, 2); fprintf(fout, "<date>");printStrXML(fout,buf);fprintf(fout,"</date>\n");
  indent(fout, 2); fprintf(fout, "<method>");printStrXML(fout,data->simulationInfo.solverMethod);fprintf(fout,"</method>\n");
  indent(fout, 2); fprintf(fout, "<outputFormat>");printStrXML(fout,data->simulationInfo.outputFormat);fprintf(fout,"</outputFormat>\n");
  indent(fout, 2); fprintf(fout, "<outputFilename>");printStrXML(fout,outputFilename);fprintf(fout,"</outputFilename>\n");
  indent(fout, 2); fprintf(fout, "<outputFilesize>%ld</outputFilesize>\n", (long) fileSize(outputFilename));
  indent(fout, 2); fprintf(fout, "<overheadTime>%f</overheadTime>\n", rt_accumulated(SIM_TIMER_OVERHEAD));
  indent(fout, 2); fprintf(fout, "<preinitTime>%f</preinitTime>\n", rt_accumulated(SIM_TIMER_PREINIT));
  indent(fout, 2); fprintf(fout, "<initTime>%f</initTime>\n", rt_accumulated(SIM_TIMER_INIT));
  indent(fout, 2); fprintf(fout, "<eventTime>%f</eventTime>\n", rt_accumulated(SIM_TIMER_EVENT));
  indent(fout, 2); fprintf(fout, "<outputTime>%f</outputTime>\n", rt_accumulated(SIM_TIMER_OUTPUT));
  indent(fout, 2); fprintf(fout, "<linearizeTime>%f</linearizeTime>\n", rt_accumulated(SIM_TIMER_LINEARIZE));
  indent(fout, 2); fprintf(fout, "<totalTime>%f</totalTime>\n", rt_accumulated(SIM_TIMER_TOTAL));
  indent(fout, 2); fprintf(fout, "<totalStepsTime>%f</totalStepsTime>\n", rt_total(SIM_TIMER_STEP));
  indent(fout, 2); fprintf(fout, "<numStep>%d</numStep>\n", (int) rt_ncall_total(SIM_TIMER_STEP));
  indent(fout, 2); fprintf(fout, "<maxTime>%.9f</maxTime>\n", rt_max_accumulated(SIM_TIMER_STEP));
  fprintf(fout, "</modelinfo>\n");

  fprintf(fout, "<modelinfo_ext>\n");
  indent(fout, 2); fprintf(fout, "<odeTime>%f</odeTime>\n", rt_accumulated(SIM_TIMER_FUNCTION_ODE));
  indent(fout, 2); fprintf(fout, "<odeTimeTicks>%lu</odeTimeTicks>\n", rt_ncall(SIM_TIMER_FUNCTION_ODE));
  fprintf(fout, "</modelinfo_ext>\n");

  fprintf(fout, "<profilingdataheader>\n");
  printProfilingDataHeader(fout, data);
  fprintf(fout, "</profilingdataheader>\n");

  fprintf(fout, "<variables>\n");
  for(i=0;i<data->modelData.nVariablesReal;++i){
    printVar(fout, 2, &(data->modelData.realVarsData[i].info));
  }
  for(i=0;i<data->modelData.nParametersReal;++i){
    printVar(fout, 2, &data->modelData.realParameterData[i].info);
  }
  for(i=0;i<data->modelData.nVariablesInteger;++i){
    printVar(fout, 2, &data->modelData.integerVarsData[i].info);
  }
  for(i=0;i<data->modelData.nParametersInteger;++i){
    printVar(fout, 2, &data->modelData.integerParameterData[i].info);
  }
  for(i=0;i<data->modelData.nVariablesBoolean;++i){
    printVar(fout, 2, &data->modelData.booleanVarsData[i].info);
  }
  for(i=0;i<data->modelData.nParametersBoolean;++i){
    printVar(fout, 2, &data->modelData.booleanParameterData[i].info);
  }
  for(i=0;i<data->modelData.nVariablesString;++i){
    printVar(fout, 2, &data->modelData.stringVarsData[i].info);
  }
  for(i=0;i<data->modelData.nParametersString;++i){
    printVar(fout, 2, &data->modelData.stringParameterData[i].info);
  }
  fprintf(fout, "</variables>\n");

  fprintf(fout, "<functions>\n");
  printFunctions(fout, plotCommands, plotFormat, data->modelData.modelFilePrefix, data);
  fprintf(fout, "</functions>\n");

  fprintf(fout, "<equations>\n");
  printEquations(fout, data->modelData.modelDataXml.nEquations, &data->modelData.modelDataXml);
  fprintf(fout, "</equations>\n");

  fprintf(fout, "<profileblocks>\n");
  printProfileBlocks(fout, plotCommands, plotFormat, data);
  fprintf(fout, "</profileblocks>\n");

  fprintf(fout, "</simulation>\n");

  fclose(fout);
  if(plotCommands) {
    const char *omhome = data->simulationInfo.OPENMODELICAHOME;
    char *buf = NULL;
    int genHtmlRes;
    buf = (char*)malloc(230 + 2*strlen(plotfile) + 2*(omhome ? strlen(omhome) : 0));
    assert(buf);
#if defined(__MINGW32__) || defined(_MSC_VER) || defined(NO_PIPE)
    if(omhome) {
#if defined(__MINGW32__) || defined(_MSC_VER)
      sprintf(buf, "%s/lib/omc/libexec/gnuplot/binary/gnuplot.exe %s", omhome, plotfile);
#else
      sprintf(buf, "gnuplot %s", plotfile);
#endif
      fclose(plotCommands);
      if(0 != system(buf)) {
        WARNING1(LOG_UTIL, "Plot command failed: %s\n", buf);
      }
    }
#else
    if(0 != pclose(plotCommands)) {
      WARNING(LOG_UTIL, "Warning: Plot command failed\n");
    }
#endif
    if(omhome)
    {
#if defined(__MINGW32__) || defined(_MSC_VER)
      char *xsltproc;
      sprintf(buf, "%s/lib/omc/libexec/xsltproc/xsltproc.exe", omhome);
      xsltproc = strdup(buf);
#else
      const char *xsltproc = "xsltproc";
#endif
      sprintf(buf, "%s -o %s_prof.html %s/share/omc/scripts/default_profiling.xsl %s_prof.xml", xsltproc, data->modelData.modelFilePrefix, omhome, data->modelData.modelFilePrefix);
#if defined(__MINGW32__) || defined(_MSC_VER)
      free(xsltproc);
#endif
      genHtmlRes = system(buf);
    }
    else
    {
      strcpy(buf, "OPENMODELICAHOME missing");
      genHtmlRes = 1;
    }
    if(genHtmlRes)
    {
      WARNING1(LOG_STDOUT, "Failed to generate html version of profiling results: %s\n", buf);
    }
    INFO2(LOG_STDOUT, "Time measurements are stored in %s_prof.html (human-readable) and %s_prof.xml (for XSL transforms or more details)", data->modelData.modelFilePrefix, data->modelData.modelFilePrefix);
    free(buf);
  }
  return 0;
}
image_t* image_load_jpg(image_t* x, stream_t* stream)
{
  image_t* im;

  TRACE1 ("loading jpeg file");

  if (!stream) {
    im = NULL;
  } else {
    int load;
    im = image_instantiate_toplevel (x);

    struct jpeg_decompress_struct cinfo;
    myerror_mgr errmgr;

    errmgr.im = im;
    errmgr.image_is_owned_p = (im != x);

    if (setjmp (errmgr.env)) {
	    jpeg_destroy_decompress(&cinfo);

	// coming back from an error
	return NULL;
    }

    /* insert here useless error test */
    /* jpeg object initialisation */
    jpeg_create_decompress (&cinfo);

    /* specify data source */
    jpeg_stream_src (&cinfo, stream);

    /* standard error */
    cinfo.err               = jpeg_std_error (&errmgr.super);
    errmgr.super.error_exit = image_load_jpeg_error_exit;

    if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
	    return NULL;
    }

    if (jpeg_start_decompress(&cinfo) < 0) {
	    return NULL;
    }

    if (!cinfo.output_width || !cinfo.output_height) {
	    WARNING1("null size image.");
	    return NULL;
    }

    image_new(im,
	      cinfo.output_width,
	      cinfo.output_height,
	      cinfo.output_width);

    switch (cinfo.output_components) {
    case 1: /* GRAY */
	load = 1;
	break;
    case 3: // RGB
	load = 1;
	break;
    default:
	/* don't know how to load that */
	image_destroy (im);
	if(im != x) {
		image_retire (im);
	}
	im = NULL;

	load = 0;
    }

    if (load) {
	JSAMPARRAY scanline_buf;

	scanline_buf = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE,
		 cinfo.output_width *
		 cinfo.output_components,
		 cinfo.rec_outbuf_height);

	while (cinfo.output_scanline < cinfo.output_height) {
	    int n;

	    uint32_t* dest = im->pixels + im->pitch * cinfo.output_scanline;

	    n = jpeg_read_scanlines(&cinfo,
				    scanline_buf,
				    cinfo.rec_outbuf_height);

	    int s;
	    for (s = 0; s < n; s++) {
		    unsigned char* scanline = scanline_buf [s];

		    /* copy to image */
		    int i;
		    for (i = 0; i < im->width; i++) {
			    if(cinfo.output_components == 1) {
				    dest[i] = 0xff000000 |
					    (scanline[i] << 16) |
					    (scanline[i] << 8) |
					    (scanline[i]);
			    } else if(cinfo.output_components == 3) {
#if (BYTE_ORDER == LITTLE_ENDIAN && defined (PIXEL_RGBA8888)) ||	\
	(BYTE_ORDER == BIG_ENDIAN && defined (PIXEL_BGRA8888))
				    dest[i] =
					    0xff000000 |
					    (scanline [3*i + 0] << 16) |
					    (scanline [3*i + 1] << 8) |
					    (scanline [3*i + 2] << 0);
#else
				    /*dest[i] = 0xff000000 | //alpha
					    (scanline [3*i + 2] << 0) |
					    (scanline [3*i + 1] << 8) |
					    (scanline [3*i + 2] << 16);
				    */
				    dest[i] = 0xff000000 | // alpha
					    (scanline [3 * i + 0] << 0) | // r
					    (scanline [3 * i + 1] << 8) | // g
					    (scanline [3 * i + 2] << 16); // b

#endif
			    }
		    }
		    dest += im->pitch;
	    }
	}
    }

    jpeg_finish_decompress(&cinfo);

  }

    return im;
}