示例#1
0
// Populate both the drop-down on the import tab and within the file browse dialog
void populate_polsarpro_classification_optionmenu()
{
  // Set up the menus (one on the import tab, the other on the input file browse dialog
  GtkWidget *browse_menu = NULL;
  GtkWidget *browse_option_menu = get_widget_checked("browse_select_colormap_optionmenu");
  if (browse_option_menu) {
    browse_menu = gtk_option_menu_get_menu(GTK_OPTION_MENU(browse_option_menu));
    if (browse_menu) {
      gtk_option_menu_remove_menu(GTK_OPTION_MENU(browse_option_menu));
    }
  }
  browse_menu = gtk_menu_new();

  GtkWidget *browse_item = gtk_menu_item_new_with_label("None");
  gtk_menu_append(GTK_MENU(browse_menu), browse_item);
  gtk_widget_show(browse_item);

  browse_item = gtk_separator_menu_item_new();
  gtk_menu_append(GTK_MENU(browse_menu), browse_item);
  gtk_widget_show(browse_item);

  char lut_loc[1024];
  sprintf(lut_loc, "%s%clook_up_tables", get_asf_share_dir(), DIR_SEPARATOR);
  if (g_polsarpro_classification_optionmenu_ht == NULL) {
    g_polsarpro_classification_optionmenu_ht = g_hash_table_new(g_str_hash,g_str_equal);
  }

  // Open up the share dir's look up tables list, populate dropdown
  // from the files in that directory.
  GDir *lut_dir = g_dir_open(lut_loc, 0, NULL);
  if (lut_dir) {
    unsigned int i, n=0;
    char **names = (char**)MALLOC(sizeof(char*)*MAX_LUTS);

    while (1) {
      const char *name = (char*)g_dir_read_name(lut_dir);
      if (name) {
        char *name_dup = STRDUP(name);
        char *p = findExt(name_dup);
        if (p && strcmp(p, ".pal") == 0 && is_jasc_palette_lut(name)) {
          *p = '\0'; // don't show ".pal" extension in menu
          names[n++] = name_dup;
          // quit when we get too many
          if (n > MAX_LUTS)
            break;
        }
      } else
        break;
    }
    g_dir_close(lut_dir);

    // alphabetize
    qsort(names, n, sizeof(char*), my_strcmp);

    // now populate the menus
    for (i=0; i<n; ++i) {
      browse_item = gtk_menu_item_new_with_label(names[i]);
      g_object_set_data(G_OBJECT(browse_item), "file", (gpointer)names[i]);
      g_object_set_data(G_OBJECT(browse_item), "index", GUINT_TO_POINTER(i+2));
      gtk_menu_append(GTK_MENU(browse_menu), browse_item);
      gtk_widget_show(browse_item);
      g_hash_table_insert(g_polsarpro_classification_optionmenu_ht,
                          (gpointer)g_strdup(names[i]),
                           GUINT_TO_POINTER(i+2));
    }
  }

  browse_option_menu = get_widget_checked("browse_select_colormap_optionmenu");

  gtk_option_menu_set_menu(GTK_OPTION_MENU(browse_option_menu), browse_menu);
  gtk_option_menu_set_history(GTK_OPTION_MENU(browse_option_menu), 0);

  gtk_widget_show(browse_menu);
  gtk_widget_show(browse_option_menu);
}
示例#2
0
文件: dload.c 项目: moben/pacman
static int curl_download_internal(struct dload_payload *payload,
		const char *localpath, char **final_file)
{
	int ret = -1;
	FILE *localf = NULL;
	char *effective_url;
	/* RFC1123 states applications should support this length */
	char hostname[256];
	char error_buffer[CURL_ERROR_SIZE] = {0};
	struct stat st;
	long timecond, respcode = 0, remote_time = -1;
	double remote_size, bytes_dl;
	struct sigaction orig_sig_pipe, orig_sig_int;
	/* shortcut to our handle within the payload */
	alpm_handle_t *handle = payload->handle;
	CURL *curl = get_libcurl_handle(handle);
	handle->pm_errno = 0;

	payload->tempfile_openmode = "wb";
	if(!payload->remote_name) {
		payload->remote_name = strdup(get_filename(payload->fileurl));
	}
	if(!payload->remote_name || curl_gethost(payload->fileurl, hostname) != 0) {
		_alpm_log(handle, ALPM_LOG_ERROR, _("url '%s' is invalid\n"), payload->fileurl);
		RET_ERR(handle, ALPM_ERR_SERVER_BAD_URL, -1);
	}

	if(strlen(payload->remote_name) > 0 && strcmp(payload->remote_name, ".sig") != 0) {
		payload->destfile_name = get_fullpath(localpath, payload->remote_name, "");
		payload->tempfile_name = get_fullpath(localpath, payload->remote_name, ".part");
		if(!payload->destfile_name || !payload->tempfile_name) {
			goto cleanup;
		}
	} else {
		/* URL doesn't contain a filename, so make a tempfile. We can't support
		 * resuming this kind of download; partial transfers will be destroyed */
		payload->unlink_on_fail = 1;

		localf = create_tempfile(payload, localpath);
		if(localf == NULL) {
			goto cleanup;
		}
	}

	curl_set_handle_opts(payload, curl, error_buffer);

	if(localf == NULL) {
		localf = fopen(payload->tempfile_name, payload->tempfile_openmode);
		if(localf == NULL) {
			goto cleanup;
		}
	}

	_alpm_log(handle, ALPM_LOG_DEBUG,
			"opened tempfile for download: %s (%s)\n", payload->tempfile_name,
			payload->tempfile_openmode);

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, localf);

	/* ignore any SIGPIPE signals- these may occur if our FTP socket dies or
	 * something along those lines. Store the old signal handler first. */
	mask_signal(SIGPIPE, SIG_IGN, &orig_sig_pipe);
	mask_signal(SIGINT, &inthandler, &orig_sig_int);

	/* perform transfer */
	payload->curlerr = curl_easy_perform(curl);

	/* disconnect relationships from the curl handle for things that might go out
	 * of scope, but could still be touched on connection teardown.  This really
	 * only applies to FTP transfers. See FS#26327 for an example. */
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, (char *)NULL);

	/* was it a success? */
	switch(payload->curlerr) {
		case CURLE_OK:
			/* get http/ftp response code */
			curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respcode);
			if(respcode >= 400) {
				payload->unlink_on_fail = 1;
				goto cleanup;
			}
			break;
		case CURLE_ABORTED_BY_CALLBACK:
			/* handle the interrupt accordingly */
			if(dload_interrupted == ABORT_OVER_MAXFILESIZE) {
				payload->curlerr = CURLE_FILESIZE_EXCEEDED;
				handle->pm_errno = ALPM_ERR_LIBCURL;
				/* the hardcoded 'size exceeded' message is same as libcurl's normal */
				_alpm_log(handle, ALPM_LOG_ERROR,
						_("failed retrieving file '%s' from %s : %s\n"),
						payload->remote_name, hostname, "Maximum file size exceeded");
			}
			goto cleanup;
		default:
			/* delete zero length downloads */
			if(stat(payload->tempfile_name, &st) == 0 && st.st_size == 0) {
				payload->unlink_on_fail = 1;
			}
			if(!payload->errors_ok) {
				handle->pm_errno = ALPM_ERR_LIBCURL;
				_alpm_log(handle, ALPM_LOG_ERROR,
						_("failed retrieving file '%s' from %s : %s\n"),
						payload->remote_name, hostname, error_buffer);
			} else {
				_alpm_log(handle, ALPM_LOG_DEBUG,
						"failed retrieving file '%s' from %s : %s\n",
						payload->remote_name, hostname, error_buffer);
			}
			goto cleanup;
	}

	/* retrieve info about the state of the transfer */
	curl_easy_getinfo(curl, CURLINFO_FILETIME, &remote_time);
	curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &remote_size);
	curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &bytes_dl);
	curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &timecond);
	curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);

	/* time condition was met and we didn't download anything. we need to
	 * clean up the 0 byte .part file that's left behind. */
	if(timecond == 1 && DOUBLE_EQ(bytes_dl, 0)) {
		_alpm_log(handle, ALPM_LOG_DEBUG, "file met time condition\n");
		ret = 1;
		unlink(payload->tempfile_name);
		goto cleanup;
	}

	/* remote_size isn't necessarily the full size of the file, just what the
	 * server reported as remaining to download. compare it to what curl reported
	 * as actually being transferred during curl_easy_perform() */
	if(!DOUBLE_EQ(remote_size, -1) && !DOUBLE_EQ(bytes_dl, -1) &&
			!DOUBLE_EQ(bytes_dl, remote_size)) {
		handle->pm_errno = ALPM_ERR_RETRIEVE;
		_alpm_log(handle, ALPM_LOG_ERROR, _("%s appears to be truncated: %jd/%jd bytes\n"),
				payload->remote_name, (intmax_t)bytes_dl, (intmax_t)remote_size);
		goto cleanup;
	}

	if(payload->content_disp_name) {
		/* content-disposition header has a better name for our file */
		free(payload->destfile_name);
		payload->destfile_name = get_fullpath(localpath, payload->content_disp_name, "");
	} else {
		const char *effective_filename = strrchr(effective_url, '/');
		if(effective_filename && strlen(effective_filename) > 2) {
			effective_filename++;

			/* if destfile was never set, we wrote to a tempfile. even if destfile is
			 * set, we may have followed some redirects and the effective url may
			 * have a better suggestion as to what to name our file. in either case,
			 * refactor destfile to this newly derived name. */
			if(!payload->destfile_name || strcmp(effective_filename,
						strrchr(payload->destfile_name, '/') + 1) != 0) {
				free(payload->destfile_name);
				payload->destfile_name = get_fullpath(localpath, effective_filename, "");
			}
		}
	}

	ret = 0;

cleanup:
	if(localf != NULL) {
		fclose(localf);
		utimes_long(payload->tempfile_name, remote_time);
	}

	if(ret == 0) {
		const char *realname = payload->tempfile_name;
		if(payload->destfile_name) {
			realname = payload->destfile_name;
			if(rename(payload->tempfile_name, payload->destfile_name)) {
				_alpm_log(handle, ALPM_LOG_ERROR, _("could not rename %s to %s (%s)\n"),
						payload->tempfile_name, payload->destfile_name, strerror(errno));
				ret = -1;
			}
		}
		if(ret != -1 && final_file) {
			STRDUP(*final_file, strrchr(realname, '/') + 1,
					RET_ERR(handle, ALPM_ERR_MEMORY, -1));
		}
	}

	if((ret == -1 || dload_interrupted) && payload->unlink_on_fail &&
			payload->tempfile_name) {
		unlink(payload->tempfile_name);
	}

	/* restore the old signal handlers */
	unmask_signal(SIGINT, orig_sig_int);
	unmask_signal(SIGPIPE, orig_sig_pipe);
	/* if we were interrupted, trip the old handler */
	if(dload_interrupted) {
		raise(SIGINT);
	}

	return ret;
}
示例#3
0
/**
 * Complete filename (a la shell) from abbrevition.
 * @param fil the name of the file, may contain ~/ or
 *        be relative to the current directory
 * @returns the full file name,
 *          NULL is returned on error
 */
static char * expandFileName(const char * fil) {
  char buffer[512];
  char * fn;
#ifndef MINGW
  char * fm;
  const char *fil_ptr;
#else
  long lRet;
#endif

  if (fil == NULL)
    return NULL;

#ifndef MINGW
  if (fil[0] == DIR_SEPARATOR) {
    /* absolute path, just copy */
    return STRDUP(fil);
  }
  if (fil[0] == '~') {
    fm = getenv("HOME");
    if (fm == NULL) {
      /* keep it symbolic to show error to user! */
      fm = "$HOME";
    }

    /* do not copy '~' */
    fil_ptr = fil + 1;

	/* skip over dir seperator to be consistent */
    if (fil_ptr[0] == DIR_SEPARATOR)
      fil_ptr++;
  } else {
    fil_ptr = fil;
    if (getcwd(buffer, 512) != NULL)
      fm = buffer;
    else
      fm = "$PWD";
  }
  fn = MALLOC(strlen(fm) + 1 + strlen(fil_ptr) + 1);

  sprintf(fn, "%s/%s", fm, fil_ptr);
#else
  fn = MALLOC(MAX_PATH + 1);

  if ((lRet = conv_to_win_path(fil, buffer)) != ERROR_SUCCESS)
  {
  	SetErrnoFromWinError(lRet);

    return NULL;
  }
  /* is the path relative? */
  if ((strncmp(buffer + 1, ":\\", 2) != 0) &&
      (strncmp(buffer, "\\\\", 2) != 0))
  {
    char szCurDir[MAX_PATH + 1];
    lRet = GetCurrentDirectory(MAX_PATH + 1, szCurDir);
    if (lRet + strlen(fn) + 1 > (_MAX_PATH + 1))
    {
      SetErrnoFromWinError(ERROR_BUFFER_OVERFLOW);

      return NULL;
    }
    sprintf(fn, "%s\\%s", szCurDir, buffer);
  }
  else
  {
    strcpy(fn, buffer);
  }
#endif
  return fn;
}
示例#4
0
int asf_import(radiometry_t radiometry, int db_flag, int complex_flag,
	       int multilook_flag, int azimuth_look_count, int range_look_count,
	       int amp0_flag, input_format_t format_type,
	       char *band_id, char *data_type, char *image_data_type, 
	       char *lutName, char *prcPath, double lowerLat, double upperLat, 
	       double lowerLon, double upperLon, int line, int sample, 
	       int width, int height, int save_intermediates,
	       double *p_range_scale, double *p_azimuth_scale,
	       double *p_correct_y_pixel_size, int apply_ers2_gain_fix,
	       char *inMetaNameOption, char *inBaseName, char *ancillary_file,
	       char *colormapName, char *slave_file, char *interferogram_file,
	       char *coherence_file, char *baseline_file, 
	       int complex_gamma, char *uavsar_type,
	       int metaonly, char *outBaseName)
{
  char outDataName[256], outMetaName[256];

  asfPrintStatus("   Importing: %s\n", inBaseName);

  /*
  printf("\nradiometry: %d\n", radiometry);
  printf("db_flag: %d\n", db_flag);
  printf("complex_flag: %d\n", complex_flag);
  printf("multilook_flag: %d\n", multilook_flag);
  printf("amp0_flag: %d\n", amp0_flag);
  printf("format_type: %d\n", format_type);
  printf("band_id: %s\n", band_id);
  printf("data_type: %s\n", data_type);
  printf("image_data_type: %s\n", image_data_type);
  printf("lutName: %s\n", lutName);
  printf("line: %d\n", line);
  printf("sample: %d\n", sample);
  printf("width: %d\n", width);
  printf("height: %d\n", height);
  printf("p_range_scale: %f\n", &p_range_scale);
  printf("p_azimuth_scale: %f\n", &p_azimuth_scale);
  printf("p_correct_y_pixel_size: %f\n", &p_correct_y_pixel_size);
  printf("apply_ers2_gain_fix: %d\n", apply_ers2_gain_fix);
  printf("inMetaNameOption: %s\n", inMetaNameOption);
  printf("inBaseName: %s\n", inBaseName);
  printf("outBaseName: %s\n\n", outBaseName);
  */

  strcpy(outDataName, outBaseName);
  strcpy(outMetaName, outBaseName);
  strcat(outMetaName, TOOLS_META_EXT);

  if (metaonly) {
    create_xml_meta(inBaseName, outBaseName, format_type);
    return 0;
  }

  if ((radiometry == r_SIGMA ||
       radiometry == r_BETA  ||
       radiometry == r_GAMMA ||
       radiometry == r_POWER)   &&
       !(format_type == CEOS || format_type == STF || format_type == AIRSAR ||
	 format_type == ALOS_MOSAIC || format_type == TERRASAR))
  {
    // A power flag is on, but the input file is not CEOS or STF format
    // so it will be ignored
    asfPrintWarning("Power flags %s%s will be only accepted for the following\n"
		    "data formats since other formats do not indicate what "
                    "type of data is in the file:\n"
		    "CEOS, TERRASAR, STF, AirSAR and ALOS mosaics.\n"
		    "Assuming the input data is an AMPLITUDE image...\n",
                    radiometry == r_SIGMA ? "SIGMA" :
                    radiometry == r_BETA  ? "BETA"  :
                    radiometry == r_GAMMA ? "GAMMA" :
                    radiometry == r_POWER ? "POWER" : "UNKNOWN",
                    db_flag               ? " scaled to DECIBELS" : "");
  }

  // Ingest all sorts of flavors of CEOS data/
  if (format_type == CEOS) {
    asfPrintStatus("   Data format: CEOS\n");
    import_ceos(inBaseName, outBaseName, band_id, lutName,
                p_range_scale, p_azimuth_scale, p_correct_y_pixel_size,
                line, sample, width, height, inMetaNameOption, radiometry,
                db_flag, complex_flag, multilook_flag, azimuth_look_count,
		range_look_count, amp0_flag, apply_ers2_gain_fix);
    // Replace the restituted state vectors that comes with the image data with
    // precision state vectors from Delft
    if (prcPath != NULL && strlen(prcPath) > 0) {
      update_state_vectors(outBaseName, prcPath);
    }
  }
  // Ingest Vexcel Sky Telemetry Format (STF) data
  else if (format_type == STF) {
    asfPrintStatus("   Data format: STF\n");
    int lat_constrained = upperLat != -99 && lowerLat != -99;
    import_stf(inBaseName, outBaseName, radiometry, inMetaNameOption,
               lat_constrained, lowerLat, upperLat, prcPath);
  }
  else if (format_type == GENERIC_GEOTIFF) {
    asfPrintStatus("   Data format: GEOTIFF\n");
    if (band_id != NULL &&
      strlen(band_id) > 0 &&
      strncmp(uc(band_id), "ALL", 3) != 0) {
      asfPrintWarning("The -band option is not supported for data files containing\n"
          "multiple bands within a single file (such as GeoTIFF or TIFF)\n"
          "rather than in individual band files (such as ALOS etc).\n"
          "\nThe import will continue, but all available bands will be\n"
          "imported into a single ASF-format file.  You may select any\n"
          "individual band for export however.\n");
    }

    char *ext = findExt(inBaseName);
    if (ext != NULL) {
      *ext = '\0';
    }
    GString *inGeotiffName = find_geotiff_name (inBaseName);
    if ( inGeotiffName == NULL ) {
      asfPrintError ("Couldn't find a GeoTIFF file (i.e. a file with "
         "extension '.tif', '.tiff',\n'.TIF', or '.TIFF') "
         "corresponding to specified inBaseName:\n"
         "%s\n", inBaseName);
    }
    if (strlen(image_data_type)               &&
        strncmp(image_data_type, MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0)
    {
      import_generic_geotiff (inGeotiffName->str, outBaseName, image_data_type);
    }
    else {
      import_generic_geotiff (inGeotiffName->str, outBaseName, NULL);
    }
    g_string_free(inGeotiffName,TRUE);
  }
  else if (format_type == BIL) {
    asfPrintStatus("   Data format: BIL\n");
    import_bil(inBaseName, outBaseName);
  }
  else if (format_type == GRIDFLOAT) {
    asfPrintStatus("   Data format: GRIDFLOAT\n");
    import_gridfloat(inBaseName, outBaseName);
  }
  else if (format_type == AIRSAR) {
    asfPrintStatus("   Data format: AIRSAR\n");
    import_airsar(inBaseName, update(radiometry, db_flag), outBaseName);
  }
  else if (format_type == UAVSAR) {
    asfPrintStatus("   Data format: UAVSAR\n");
    import_uavsar(inBaseName, line, sample, width, height, 
		  update(radiometry, db_flag), uavsar_type, outBaseName);
  }
  else if (format_type == VP) {
    asfPrintStatus("   Data format: VP\n");
    import_vexcel_plain(inBaseName, outBaseName);
  }
  else if (format_type == JAXA_L0) {
      asfPrintStatus("   Data format: JAXA_L0 (ALOS AVNIR-2 Level 0)\n");
      import_jaxa_L0(inBaseName, outBaseName);
  }
  else if (format_type == ALOS_MOSAIC) {
    asfPrintStatus("   Data format: ALOS MOSAIC\n");
    import_alos_mosaic(inBaseName, update(radiometry, db_flag), outBaseName);
  }
  else if (format_type == TERRASAR) {
    asfPrintStatus("   Data format: TERRASAR\n");
    import_terrasar(inBaseName, update(radiometry, db_flag), outBaseName, 0);
  }
  else if (format_type == RADARSAT2) {
    asfPrintStatus("   Data format: RADARSAT2\n");
    import_radarsat2(inBaseName, update(radiometry, db_flag), outBaseName, 0);
  }
  else if (format_type == POLSARPRO) {
    asfPrintStatus("   Data format: POLSARPRO\n");
    import_polsarpro(inBaseName, ancillary_file, colormapName, image_data_type,
		     db_flag, outBaseName);
  }
  else if (format_type == GAMMA) {
    asfPrintStatus("   Data format: GAMMA\n");
    import_gamma(inBaseName, inMetaNameOption, slave_file, interferogram_file,
		 coherence_file, baseline_file, complex_gamma, 
		 outBaseName);
  }
  else if (format_type == ROIPAC) {
    asfPrintStatus("   Data format: ROI_PAC\n");
    import_roipac(inBaseName, outBaseName);
  }
  else if (format_type == SMAP) {
    asfPrintStatus("   Data format: SMAP\n");
    import_smap(inBaseName, outBaseName, 
		upperLat, upperLon, lowerLat, lowerLon);
  }
  // Don't recognize this data format; report & quit
  else {
    asfPrintError("Unrecognized data format: '%d'\n",format_type);
  }
  int num_elements = 0;
  int is_jasc_palette = 0;
  if (format_type == AIRSAR && colormapName != NULL)
    asfPrintError("Colormaps not supported for AirSAR data.\n");
  if (format_type != AIRSAR && format_type != UAVSAR) {
    meta_parameters *meta = meta_read(outMetaName);
    if (meta->colormap) {
      if (!(colormapName != NULL && 
            (meta->general->data_type == ASF_BYTE || is_PolSARpro(inBaseName)))) {
        // Ooops.  Tried to apply a colormap to the wrong type of data
        asfPrintWarning(
          "Color map specified with the -colormap option (%s) not\n"
          "applied during ingest.  Color maps can only be applied to byte or\n"
          "PolSARpro data.  Data was imported as-is.\n", colormapName);
      }
      else {
        // Apply the user-selected color map to the metadata
        FILE *fp = NULL;
        unsigned char * lut_buffer;
        char *lut_basename = STRDUP(colormapName);
        char *ext = findExt(lut_basename);
        if (ext) *ext = '\0';
        
        // Check LUT file validity and allocate appropriately sized buffer
        // to read into
        char magic_str[1024];
        char version_s[1024];
        char num_elements_s[1024];
        char lut_path[1024];
        sprintf(lut_path, "%s%clook_up_tables%c%s.pal", get_asf_share_dir(),
                DIR_SEPARATOR, DIR_SEPARATOR, lut_basename);
        if (fileExists(lut_path)) {
          fp = (FILE*)FOPEN(lut_path, "rt");
          fgets(magic_str, 1024, fp);
          fgets(version_s, 1024, fp);
          fgets(num_elements_s, 1024, fp);
          FCLOSE(fp);
          int version = atoi(version_s);
          num_elements = atoi(num_elements_s);
          is_jasc_palette =
            (strncmp(magic_str, "JASC", 4) == 0 && version == 100) ? 1 : 0;
          if (is_jasc_palette && (num_elements <= 0 || num_elements > 512)) {
            asfPrintWarning(
              "Found invalid JASC-PAL type color map file (%s) ...color map\n"
              "not applied.\n", colormapName);
          }
          if (num_elements > 256) {
            asfPrintWarning(
              "PolSARpro look-up table contains more than 256 elements (%d).\n"
              "Only the first 256 will be read and mapped to data.\n",
              num_elements);
          }
        }
        else {
          sprintf(lut_path, "%s%clook_up_tables%c%s.lut", get_asf_share_dir(),
                  DIR_SEPARATOR, DIR_SEPARATOR, lut_basename);
          if (fileExists(lut_path)) {
            is_jasc_palette = 0; // Assume ASF format
          }
          else {
            strcpy(lut_path, "");
          }
        }
        lut_buffer = MALLOC(sizeof(unsigned char) * 3 * MAX_LUT_DN);
      
        // Read the LUT
        if (strlen(lut_path) > 0) {
          int max_dn = read_lut(lut_path, lut_buffer);
	
          // Populate the metadata colormap
          if (!meta->colormap) meta->colormap = meta_colormap_init();
          if (is_jasc_palette) {
            meta->colormap->num_elements =
              (num_elements <= 256) ? num_elements : 256;
            sprintf(meta->colormap->look_up_table, "%s.pal", lut_basename);
          }
          else {
            num_elements = max_dn + 1;
            meta->colormap->num_elements = num_elements;
            sprintf(meta->colormap->look_up_table, "%s.lut", lut_basename);
          }
          meta->colormap->rgb =
            (meta_rgb*)CALLOC(meta->colormap->num_elements, sizeof(meta_rgb));
          int i;
          for (i = 0; i < meta->colormap->num_elements; i++) {
            meta->colormap->rgb[i].red   = lut_buffer[i*3];
            meta->colormap->rgb[i].green = lut_buffer[i*3+1];
            meta->colormap->rgb[i].blue  = lut_buffer[i*3+2];
          }
        }
        FREE(lut_basename);
        meta_write(meta, outMetaName);
      }
    }
    
    meta_free(meta);
  }

  asfPrintStatus("Import complete.\n\n");
  return 0;
}
示例#5
0
static int
get_bladehpi_hostlist(struct pluginDevice *dev)
{
	struct blade_info *	bi;
	SaErrorT		ohrc;
	SaHpiEntryIdT		ohnextid;
	SaHpiRptEntryT		ohRPT;
	SaHpiDomainInfoT 	ohdi;
	SaHpiUint32T		ohupdate;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called, dev->device=%s"
		,	__FUNCTION__,	dev->device);
	}

	if (dev->device == NULL || *dev->device == 0) {
		LOG(PIL_CRIT, "Unconfigured stonith object in %s"
		,	__FUNCTION__);
		return S_BADCONFIG;
	}

	ohrc = saHpiDomainInfoGet(dev->ohsession, &ohdi);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to get domain info in %s (%d)"
		,	__FUNCTION__, ohrc);
		return S_BADCONFIG;
	}
	
try_again:
	ohupdate = ohdi.RptUpdateCount;
	dev->ohdevid = dev->ohsensid = dev->ohsensnum = 0;
	ohnextid = SAHPI_FIRST_ENTRY;
	do {
		char blname[SAHPI_MAX_TEXT_BUFFER_LENGTH];
		int  blnum;

		ohrc = saHpiRptEntryGet(dev->ohsession, ohnextid
				       , &ohnextid, &ohRPT);
		if (ohrc != SA_OK) {
			LOG(PIL_CRIT, "Unable to get RPT entry in %s (%d)"
			,	__FUNCTION__, ohrc);
			free_bladehpi_hostlist(dev);
			return S_BADCONFIG;
		}

		switch (get_resource_type(dev->device, &ohRPT)) {
		case OHRES_BLADECENT:
			dev->ohdevid = ohRPT.ResourceId;

			if (Debug) {
				LOG(PIL_DEBUG, "BladeCenter '%s' has id %d"
				,	(char*)ohRPT.ResourceTag.Data
				,	dev->ohdevid);
			}
			break;

		case OHRES_MGMTMOD:
			if (ohRPT.ResourceCapabilities&SAHPI_CAPABILITY_SENSOR){
 				dev->ohsensnum = get_sensor_num(dev->ohsession
							, ohRPT.ResourceId);

				if (dev->ohsensnum) {
					dev->ohsensid = ohRPT.ResourceId;

					if (Debug) {
						LOG(PIL_DEBUG
						, "MgmtModule '%s' has id %d "
						"with sensor #%d"
						, (char*)ohRPT.ResourceTag.Data
						, dev->ohsensid
						, dev->ohsensnum);
					}
				}
			} 
			break;

		case OHRES_BLADE:
			if ((bi = (struct blade_info *)
				MALLOC(sizeof(struct blade_info))) == NULL) {
			        LOG(PIL_CRIT, "Out of memory in %s"
				,	__FUNCTION__);
				free_bladehpi_hostlist(dev);
			        return S_OOPS;
			}

			/*
			 * New format consists of "Blade N - name" while older
			 * format consists only of "name"; we only need to
			 * stash name because ResourceID is the important info
			 */
			if (sscanf((char*)ohRPT.ResourceTag.Data, "Blade %d - %s"
					, &blnum, blname) == 2) {
				bi->name = STRDUP(blname);
			} else {
				bi->name = STRDUP((char*)ohRPT.ResourceTag.Data);
			}
			if (bi->name == NULL) {
				LOG(PIL_CRIT, "Out of memory for strdup in %s"
				,	__FUNCTION__);
				free_bladehpi_hostlist(dev);
			        return S_OOPS;
			}

			bi->resourceId = ohRPT.ResourceId;
			bi->resourceCaps = ohRPT.ResourceCapabilities;
			dev->hostlist = g_list_append(dev->hostlist, bi);

			if (Debug) {
				LOG(PIL_DEBUG, "Blade '%s' has id %d, caps %x"
				, bi->name, bi->resourceId, bi->resourceCaps);
			}
			break;
		}
	} while (ohrc == SA_OK && ohnextid != SAHPI_LAST_ENTRY);

	ohrc = saHpiDomainInfoGet(dev->ohsession, &ohdi);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to get domain info in %s (%d)"
		,	__FUNCTION__, ohrc);
		free_bladehpi_hostlist(dev);
		return S_BADCONFIG;
	}

	if (ohupdate != ohdi.RptUpdateCount) {
		free_bladehpi_hostlist(dev);
		if(Debug){
			LOG(PIL_DEBUG, "Looping through entries again,"
				" count changed from %d to %d"
			,	ohupdate, ohdi.RptUpdateCount);
		}
		goto try_again;
	}

	dev->ohrptcnt = ohupdate;

	return S_OK;
}
示例#6
0
           string may change without harm.
           The fields structure is also allocated to store English fields
 * Description: allocate a new, empty struct template.
 * Assumptions: NEW succeeds
 * Todo: 
 */

struct template *template_new(const char *tag)
{
	struct template_l10n_fields *f = NEW(struct template_l10n_fields);
	struct template *t = NEW(struct template);
	memset(f, 0, sizeof(struct template_l10n_fields));
	f->language = strdup("");
	memset(t, 0, sizeof(struct template));
	t->ref = 1;
	t->tag = STRDUP(tag);
	t->fields = f;
	return t;
}

void template_delete(struct template *t)
{
	struct template_l10n_fields *p, *q;

	DELETE(t->tag);
	DELETE(t->type);
	p = t->fields;
	DELETE(t);
	while (p != NULL)
	{
		q = p->next;
示例#7
0
void gen_EXPRESSION ( node_t *root, int scopedepth )
{
	/*
	 * Expressions:
	 * Handle any nested expressions first, then deal with the
	 * top of the stack according to the kind of expression
	 * (single variables/integers handled in separate switch/cases)
	 */
	tracePrint ( "Starting EXPRESSION of type %s\n", (char*) root->expression_type.text);

	switch(root->expression_type.index) {

	case FUNC_CALL_E:
        {
            if (root->children[1] != NULL) {
                // Push arguments on stack
                gen_default(root->children[1], scopedepth);
            }
            char *func_label = root->function_entry->label;
            instruction_add(CALL, STRDUP(func_label), NULL, 0, 0);
            // There is an issue where, if the parent node does not use the returned result,
            // this will pollute the stack, and offset any new local variables declared.
            // I see no easy way to fix this, and it also doesn't seem to be covered by 
            // the tests.
            instruction_add(PUSH, r0, NULL, 0, 0);
        }
		break;
    case METH_CALL_E:
        {
            if (root->children[2] != NULL) {
                // Push arguments on stack
                gen_default(root->children[2], scopedepth);
            }
            tracePrint( "Pushing THIS\n" );
            root->children[0]->generate(root->children[0], scopedepth);
            char *class_label = root->children[0]->data_type.class_name;
            char *func_label = root->function_entry->label;
            int len = strlen(class_label) + strlen(func_label);
            char *meth_label = malloc(sizeof(char) * (len+1));
            meth_label[0] = 0;
            strcat(meth_label, class_label);
            strcat(meth_label, "_");
            strcat(meth_label, func_label);
            instruction_add(CALL, STRDUP(meth_label), NULL, 0, 0);
            // There is an issue where, if the parent node does not use the returned result,
            // this will pollute the stack, and offset any new local variables declared.
            // I see no easy way to fix this, and it also doesn't seem to be covered by 
            // the tests.
            instruction_add(PUSH, r0, NULL, 0, 0);
        }
        break;
    case NEW_E:
        {
            class_symbol_t *class_entry = root->children[0]->class_entry;
            char class_size[10];
            int32_t class_entry_size = (int32_t)class_entry->size * 8;
            sprintf(class_size, "#%d", class_entry_size);
            instruction_add(MOVE32, STRDUP(class_size), r0, 0, 0);
            instruction_add(PUSH, r0, NULL, 0, 0);
            instruction_add(CALL, STRDUP("malloc"), NULL, 0, 0);
            instruction_add(PUSH, r0, NULL, 0, 0);
        }
        break;
    case CLASS_FIELD_E:
        {
            root->children[0]->generate(root->children[0], scopedepth);
            char stack_offset[10];
            sprintf(stack_offset, "#%d", root->entry->stack_offset);

            instruction_add(POP, r1, NULL, 0, 0);
            instruction_add(MOVE, r2, STRDUP(stack_offset), 0, 0);
            instruction_add3(ADD, r3, r1, r2);
            instruction_add(LOAD, r0, r3, 0, 0);
            instruction_add(PUSH, r0, NULL, 0, 0);
        }
        break;
    case THIS_E:
        {
            instruction_add(LOAD, r1, fp, 0, 8);
            instruction_add(PUSH, r1, NULL, 0, 0);
        }
        break;
    default:
        gen_default(root, scopedepth);
    }

    switch (root->expression_type.index) {

    case ADD_E:
    case OR_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add3(ADD, r0, r1, r2);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case SUB_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add3(SUB, r0, r1, r2);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case MUL_E:
    case AND_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add3(MUL, r0, r1, r2);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case DIV_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add3(DIV, r0, r1, r2);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case UMINUS_E:
        instruction_add(MOVE, r1, STRDUP("#0"), 0, 0);
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add3(SUB, r0, r1, r2);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case EQUAL_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVEQ, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case NEQUAL_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#1"), 0, 0);
        instruction_add(MOVEQ, r0, STRDUP("#0"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case GEQUAL_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVGE, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case LEQUAL_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVLE, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case LESS_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVLT, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case GREATER_E:
        instruction_add(POP, r2, NULL, 0, 0);
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, r2, 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVGT, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;
    case NOT_E:
        instruction_add(POP, r1, NULL, 0, 0);
        instruction_add(CMP, r1, STRDUP("#0"), 0, 0);
        instruction_add(MOVE, r0, STRDUP("#0"), 0, 0);
        instruction_add(MOVEQ, r0, STRDUP("#1"), 0, 0);
        instruction_add(PUSH, r0, NULL, 0, 0);
        break;

	}

	tracePrint ( "Ending EXPRESSION of type %s\n", (char*) root->expression_type.text);
}
示例#8
0
文件: v3dgl.c 项目: hsanjuan/sar2
/*
 *	Sets the given gl resources structure's gl interpritation
 *	legend to the given glinterp.
 *
 *	Returns non-zero on error.
 */
int V3DGLResourceSetInterpritation(
	v3d_glresource_struct *glres,
	const v3d_glinterprite_struct *glinterp
)
{
	unsigned int flags;
	v3d_glinterprite_struct *t_glinterp;


	if((glres == NULL) || (glinterp == NULL))
	    return(-1);

	flags = glinterp->flags;

	/* Get target gl interpritation structure from the given gl
	 * resource structure.
	 */
	t_glinterp = glres->glinterprite;
	if(t_glinterp == NULL)
	    return(-1);

	if(flags & V3D_GLFLAG_COORDINATE_AXIS)
	    t_glinterp->coordinate_axis = glinterp->coordinate_axis;

	if(flags & V3D_GLFLAG_TEXTURE_KEEP)
	    t_glinterp->texture_keep = glinterp->texture_keep;

	if(flags & V3D_GLFLAG_ALLOW_TRANSLATIONS)
	    t_glinterp->allow_translations = glinterp->allow_translations;

	if(flags & V3D_GLFLAG_ALLOW_ROTATIONS)
	    t_glinterp->allow_rotations = glinterp->allow_rotations;


	if(flags & V3D_GLFLAG_FLIP_WINDING)
	    t_glinterp->flip_winding = glinterp->flip_winding;

	if(flags & V3D_GLFLAG_PASS_NORMALS)
	    t_glinterp->pass_normals = glinterp->pass_normals;

	if(flags & V3D_GLFLAG_UNITLIZE_NORMALS)
	    t_glinterp->unitlize_normals = glinterp->unitlize_normals;

	if(flags & V3D_GLFLAG_PASS_TEXCOORDS)
	    t_glinterp->pass_texcoords = glinterp->pass_texcoords;

	if(flags & V3D_GLFLAG_TEXTURE_NAME_CASE_SENSITIVE)
	    t_glinterp->texture_name_case_sensitive =
		glinterp->texture_name_case_sensitive;

	if(flags & V3D_GLFLAG_MATERIAL_PROPERTIES)
	    t_glinterp->material_properties = glinterp->material_properties;

	if(flags & V3D_GLFLAG_FACES)
	    t_glinterp->faces = glinterp->faces;


	if(flags & V3D_GLFLAG_ENABLE_BLENDING)
	    t_glinterp->enable_blending = glinterp->enable_blending;

	if(flags & V3D_GLFLAG_SET_BLEND_FUNC)
	    t_glinterp->set_blend_func = glinterp->set_blend_func;

	if(flags & V3D_GLFLAG_HEIGHTFIELD_BASE_DIR)
	{
	    const char *src_str = glinterp->heightfield_base_dir;

	    free(t_glinterp->heightfield_base_dir);
	    t_glinterp->heightfield_base_dir = STRDUP(src_str);
	}

	if(flags & V3D_GLFLAG_TEXTURE_BASE_DIR)
	{
	    const char *src_str = glinterp->texture_base_dir;

	    free(t_glinterp->texture_base_dir);
	    t_glinterp->texture_base_dir = STRDUP(src_str);
	}


	/* Update flags on the target glinterp. */
	t_glinterp->flags |= flags;

	return(0);
}
示例#9
0
文件: block.c 项目: ab25cq/xyzsh
static void sCommand_copy_deeply_stack(sCommand* dest, sCommand* src)
{
    dest->mArgs = MALLOC(sizeof(char*)*src->mArgsSize);
    dest->mArgsFlags = MALLOC(sizeof(int)*src->mArgsSize);
    dest->mArgsNum = src->mArgsNum;
    dest->mArgsSize = src->mArgsSize;

    int i;
    for(i=0; i<src->mArgsNum; i++) {
        dest->mArgs[i] = STRDUP(src->mArgs[i]);
        dest->mArgsFlags[i] = src->mArgsFlags[i];
    }
    dest->mArgs[i] = NULL;

    if(src->mEnvsNum == 0) {
        dest->mEnvs = NULL;
        dest->mEnvsNum = 0;
        dest->mEnvsSize = 0;
    }
    else {
        dest->mEnvs = MALLOC(sizeof(sEnv)*src->mEnvsSize);
        for(i=0; i<src->mEnvsNum; i++) {
            dest->mEnvs[i].mFlags = src->mEnvs[i].mFlags;

            if(src->mEnvs[i].mFlags & ENV_FLAGS_KIND_ENV) {
                dest->mEnvs[i].mName = STRDUP(src->mEnvs[i].mName);
                dest->mEnvs[i].mKey = STRDUP(src->mEnvs[i].mKey);
                dest->mEnvs[i].mInitValue = STRDUP(src->mEnvs[i].mInitValue);
            }
            else {
                dest->mEnvs[i].mBlock = block_clone_on_stack(src->mEnvs[i].mBlock, T_BLOCK);
            }
        }
        dest->mEnvsNum = src->mEnvsNum;
        dest->mEnvsSize = src->mEnvsSize;
    }

    if(src->mBlocksNum == 0) {
        dest->mBlocks = NULL;
        dest->mBlocksNum = 0;
        dest->mBlocksSize = 0;
    }
    else {
        dest->mBlocks = MALLOC(sizeof(sObject*)*src->mBlocksSize);
        dest->mBlocksNum = src->mBlocksNum;
        dest->mBlocksSize = src->mBlocksSize;

        for(i=0; i<src->mBlocksNum; i++) {
            dest->mBlocks[i] = block_clone_on_stack(src->mBlocks[i], T_BLOCK);
        }
    }

    if(src->mRedirectsNum == 0) {
        dest->mRedirectsFileNames = NULL;
        dest->mRedirects = NULL;
        dest->mRedirectsSize = 0;
        dest->mRedirectsNum = 0;
    }
    else {
        dest->mRedirectsFileNames = MALLOC(sizeof(char*)*src->mRedirectsSize);
        for(i=0; i<src->mRedirectsNum; i++) {
            dest->mRedirectsFileNames[i] = STRDUP(src->mRedirectsFileNames[i]);
        }
        dest->mRedirects = MALLOC(sizeof(int)*src->mRedirectsSize);
        for(i=0; i<src->mRedirectsNum; i++) {
            dest->mRedirects[i] = src->mRedirects[i];
        }
        dest->mRedirectsSize = src->mRedirectsSize;
        dest->mRedirectsNum = src->mRedirectsNum;
    }

    if(src->mMessagesNum == 0) {
        dest->mMessages = NULL;
        dest->mMessagesNum = 0;
        dest->mMessagesSize = 0;
    }
    else {
        dest->mMessages = MALLOC(sizeof(char*)*src->mMessagesSize);
        if(src->mMessagesNum > 0) {
            for(i=0; i<src->mMessagesNum; i++) {
                dest->mMessages[i] = STRDUP(src->mMessages[i]);
            }
            dest->mMessagesNum = src->mMessagesNum;
        }
    }
}
示例#10
0
v8Function TS_GetFileList(V8ARGS){
    v8::HandleScope TS_GetFileListscope;
	filehandle dir;
    filedata data;

	const char *directory;

	if(args.Length()>0){
			CHECK_ARG_STR(0);
		    v8::String::Utf8Value str(args[0]);


			if(strnlen(*str, 1022)<1){
				directory = "";
			}
			else{
				if(DEBUG) printf("[scriptfs] GetFileList Info: The relative directory was %s\n", *str);
				char * tdir = (char *)malloc(strlen(*str)+1);
				if(DEBUG) printf("[scriptfs] GetFileList Info: tdir = %s\n", tdir);
				tdir = strcat(tdir, *str);
                char * ls = strrchr(tdir, '/');
                if(ls[1]!='\0'){
                    strcat(tdir, "/");
                }
                if(DEBUG) printf("[scriptfs] GetFileList Info: The directory as concated was %s\n", tdir);

                directory = STRDUP(tdir);
                free(tdir);
			}
		}
	else{
		directory = "";
	}

    const char ** filenames = NULL;
	int i = 0;
	const char *fulldir = STRDUP((string(GetDirs()->save).append(directory)).c_str());
	if(DEBUG) printf("[scriptfs] GetFileList Info: The directory specified is %s\n", fulldir);
	#ifdef _WIN32

	const char *fulldirlist = STRDUP((string(GetDirs()->save).append(directory)+"*.*").c_str());
	DWORD attribs = ::GetFileAttributesA(fulldir);
	if ((attribs != INVALID_FILE_ATTRIBUTES) && (attribs & FILE_ATTRIBUTE_DIRECTORY)) {
		if(DEBUG) printf("[scriptfs] GetFileList Info: the directory was valid.");
		dir = FindFirstFile(fulldirlist, &data);

		if (dir!=INVALID_HANDLE_VALUE){
			do{
#else
	    if ((dir=opendir(GetDirs()->save))!=NULL){
	        while((data=readdir(dir))!=NULL){
#endif
				if((!ISDIRECTORY(data))&&(FILENAME(data)[0]!='.')){
					filenames = (const char **)realloc(filenames, (i+1)*sizeof(const char *));
					filenames[i] = STRDUP(FILENAME(data));
					i++;
				}
#ifdef _WIN32
		    } while(FindNextFile(dir, &data));
		    FindClose(dir);
		}//dir!=INVALID_HANDLE_VALUE
		free((void*)fulldirlist);
	}//attribs!=INVALID_FILE_ATTRIBUTES
#if DEBUG
	else{
		printf("[scriptfs] GetFileList Info: Directory does not exist.\n");
	}
#endif
#else
        }
        closedir(dir);
	}
#endif
	v8::Local<v8::Array> files = v8::Array::New(i);
	for(int e = 0; e<i; e++){
		files->Set(e, v8::String::New(filenames[e]));
        free((void*)filenames[e]);
	}
	free(filenames);
	free((void*)fulldir);
	if(directory!=NULL){
		free((void*)directory);
	}
	return TS_GetFileListscope.Close(files);

}
示例#11
0
文件: netlist.c 项目: bert/pcb-rnd
static void
netlist_style (LibraryMenuType *net, const char *style)
{
  free (net->Style);
  net->Style = STRDUP ((char *)style);
}
示例#12
0
int plan(const char *satellite, const char *beam_mode, double look_angle,
         long startdate, long enddate, double min_lat, double max_lat,
         double clat, double clon, int pass_type,
         int zone, Poly *aoi, const char *tle_filename,
         PassCollection **pc_out, char **errorstring)
{
  BeamModeInfo *bmi = get_beam_mode_info(satellite, beam_mode);
  if (!bmi) {
    *errorstring = STRDUP("Unknown satellite/beam mode combination.\n");
    return -1;
  }

  // Convert the input start/end times from longdates (dates as long ints)
  // to seconds from some reference time.  (midnight jan 1, 1900)
  // We add a day to the end date, so that the passed-in range is inclusive
  double start_secs = seconds_from_long(startdate);
  double end_secs = seconds_from_long(add_a_day(enddate));

  sat_t sat;
  read_tle(tle_filename, satellite, &sat);

  // if the planned acquisition period is further away than this amount,
  // we subtract multiples of the repeat cyle time until we are within
  // this threshold time of this tle
  double tle_time =
    time_to_secs(sat.tle.epoch_year, sat.tle.epoch_day, sat.tle.epoch_fod);

  // FIXME this is alos specific FIXME!!
  // should really read this out of a config file... or calculate it
  // from the TLE info?
  const double repeat_days = 46;
  const double orbits_per_cycle = 671;

  // repeat time, in seconds, all time references are in seconds
  double repeat_cycle_time = repeat_days * 24.*60.*60.;

  // how many days to pad the repeat cycle time, before modding the
  // start/end time
  const double days_of_padding = 5;

  // this is the cutoff, 
  double threshold = repeat_cycle_time + 24*60*60 * days_of_padding;

  int cycles_adjustment=0;
  if (start_secs-tle_time > threshold) {
    while (start_secs-tle_time > threshold) {
      start_secs -= repeat_cycle_time;
      end_secs -= repeat_cycle_time;
      ++cycles_adjustment;
    }
  }
  else if (tle_time-start_secs > threshold) { // planning backwards...
    while (tle_time-start_secs > threshold) {
      start_secs += repeat_cycle_time;
      end_secs += repeat_cycle_time;
      --cycles_adjustment;
    }
  }

  double time_adjustment = cycles_adjustment*repeat_cycle_time;
  if (cycles_adjustment != 0)
    asfPrintStatus("Adjusted start/end times %s by %d repeat cycle%s.\n",
           cycles_adjustment > 0 ? "forward" : "backward",
           cycles_adjustment > 0 ? cycles_adjustment : -cycles_adjustment,
           cycles_adjustment == 1 || cycles_adjustment == -1 ? "" : "s");

  // no deep space orbits can be planned
  assert((sat.flags & DEEP_SPACE_EPHEM_FLAG) == 0);

  if (is_utm(zone)) {
    asfPrintStatus("Target: UTM zone %d\n"
                   "  (%10.2f, %10.2f)  (%10.2f, %10.2f)\n"
                   "  (%10.2f, %10.2f)  (%10.2f, %10.2f)\n",
                   zone,
                   aoi->x[0], aoi->y[0],
                   aoi->x[1], aoi->y[1],
                   aoi->x[2], aoi->y[2],
                   aoi->x[3], aoi->y[3]);
  }
  else {
    asfPrintStatus("Target: Polar Stereo %s\n"
                   "  (%10.2f, %10.2f)  (%10.2f, %10.2f)\n"
                   "  (%10.2f, %10.2f)  (%10.2f, %10.2f)\n",
                   zone>0 ? "North" : "South",
                   aoi->x[0], aoi->y[0],
                   aoi->x[1], aoi->y[1],
                   aoi->x[2], aoi->y[2],
                   aoi->x[3], aoi->y[3]);
  }

  double curr = start_secs;
  double incr = bmi->image_time;
  stateVector st = tle_propagate(&sat, start_secs-incr);
  double lat_prev = sat.ssplat;
  int i,num_found = 0;

  // 
  // Calculate the number of frames to include before we hit the
  // area of interest.  Add 1 (i.e., round up), but if user puts in
  // zero seconds, then we want 0 lead-up frames.
  PassCollection *pc = pass_collection_new(clat, clon, aoi);

  asfPrintStatus("Searching...\n");
  while (curr < end_secs) {
    st = tle_propagate(&sat, curr);
    char dir = sat.ssplat > lat_prev ? 'A' : 'D';

    if ((dir=='A' && pass_type!=DESCENDING_ONLY) ||
        (dir=='D' && pass_type!=ASCENDING_ONLY))
    {
      OverlapInfo *oi =
        overlap(curr, &st, bmi, look_angle, zone, clat, clon, aoi);

      if (oi) {
        int n=0;

        // Calculate the orbit number -- we have to fudge this if we
        // modded the start time.
        int orbit_num = sat.orbit + orbits_per_cycle*cycles_adjustment;

        // This is an alternate way of calculating the orbit number that
        // was being used during testing... seems to produce numbers close
        // to (within 1) of the number obtained by sgpsdp...
        //double secs_per_orbit = repeat_cycle_time / orbits_per_cycle;
        // ALOS was launced on 1/24/06
        //double launch_secs = seconds_from_long(20060124);
        //double orbit_num2 = (curr - launch_secs) / secs_per_orbit;
        //orbit_num2 += orbits_per_cycle*cycles_adjustment;
        //printf("%f %f %f\n", orbit_num + sat.orbit_part,
        //       orbit_num2, orbit_num+sat.orbit_part-orbit_num2);

        // UPDATE!!  All this orbit number calculation business doesn't get
        // used for ALOS planning -- orbit number is re-calculated using
        // time since a refrence orbit.
        // See planner.c -- get_alos_orbit_number_at_time()

        PassInfo *pass_info = pass_info_new(orbit_num, sat.orbit_part, dir);
        double start_time = curr - bmi->num_buffer_frames*incr;

        // add on the buffer frames before the area of interest
        for (i=bmi->num_buffer_frames; i>0; --i) {
          double t = curr - i*incr;
          stateVector st1 = tle_propagate(&sat, t);
          double rclat, rclon; // viewable region center lat/lon

          Poly *region = get_viewable_region(&st1, bmi, look_angle,
                                             zone, clat, clon, &rclat, &rclon);

          if (region) {
            OverlapInfo *oi1 = overlap_new(0, 1000, region, zone, clat, clon,
                                           &st1, t);
            pass_info_add(pass_info, t+time_adjustment, oi1);

            if (pass_info->start_lat == -999) {
              // at the first valid buffer frame -- set starting latitude
              double start_lat, end_lat;
              get_latitude_range(region, zone, dir, &start_lat, &end_lat);
              pass_info_set_start_latitude(pass_info, start_lat);
            }
          }
        }

        // add the frames that actually image the area of interest
        while (curr < end_secs && oi) {
          pass_info_add(pass_info, curr+time_adjustment, oi);
          ++n;

          curr += incr;
          st = tle_propagate(&sat, curr);

          oi = overlap(curr, &st, bmi, look_angle, zone, clat, clon, aoi);
        }

        double end_time = curr + (bmi->num_buffer_frames-1)*incr;
        pass_info_set_duration(pass_info, end_time-start_time);

        // add on the buffer frames after the area of interest
        for (i=0; i<bmi->num_buffer_frames; ++i) {
          double t = curr + i*incr;
          stateVector st1 = tle_propagate(&sat, t);
          double rclat, rclon; // viewable region center lat/lon
          Poly *region = get_viewable_region(&st1, bmi, look_angle,
                                             zone, clat, clon, &rclat, &rclon);
          if (region) {
            OverlapInfo *oi1 = overlap_new(0, 1000, region, zone, clat, clon,
                                           &st1, t);
            pass_info_add(pass_info, t+time_adjustment, oi1);

            // set stopping latitude -- each frame overwrites the previous,
            // so the last valid frame will set the stopping latitude
            double start_lat, end_lat;
            get_latitude_range(region, zone, dir, &start_lat, &end_lat);
            pass_info_set_stop_latitude(pass_info, end_lat);
          }
        }

        // make sure we set all the required "after the fact" info
        // if not, then do not add the pass... must be invalid
        // (these used to be asserts, so it doesn't seem to ever happen)
        if (n>0 &&
            pass_info->start_lat != -999 &&
            pass_info->stop_lat != -999 &&
            pass_info->duration != -999)
        {
          // add the pass!
          pass_collection_add(pc, pass_info);
          ++num_found;
        }
        else
        {
          asfPrintStatus("Invalid pass found.  Skipped... \n"
                         " -- number of frames: %d, dir: %c\n"
                         " -- date: %s, orbit %d, %f\n --> (%f,%f,%f)\n",
                         n, pass_info->dir,
                         pass_info->start_time_as_string,
                         pass_info->orbit, pass_info->orbit_part,
                         pass_info->start_lat, pass_info->stop_lat,
                         pass_info->duration);
        }
      }
    }

    curr += incr;
    lat_prev = sat.ssplat;

    //printf("Lat: %f, Orbit: %d, Orbit Part: %f\n", sat.ssplat,
    //       (int)sat.orbit, sat.orbit_part);

    asfPercentMeter((curr-start_secs)/(end_secs-start_secs));
  }
  asfPercentMeter(1.0);

  *pc_out = pc;
  return num_found;
}
CompilerWrapperOption::CompilerWrapperOption(CompilerWrapperOptionPool &pool,const char *field_name) : _pool(pool)
{
  _description=NULL;
  _field_name=STRDUP(field_name);
  _pool.add(this);
}
示例#14
0
int iniparse_args(configctx_t *ctx, int argc, char *argv[])
{
    int  i;
    int  ret;
    char *arg;

    for ( i = 1; i < argc; i++ ) {
        if ( argv[i] && argv[i][0] == '-' ) {
            if ( argv[i][1] == '-' ) {
                char  *temp_section = ctx->current_group;
                char  *ptr, *option,*value = NULL;
                int    optc = i;

                arg = STRDUP(argv[i]);
                /* Long option handling - break out the section if present */
                if ( ( ptr = strchr(arg,':') ) != NULL ) {
                    *ptr = 0;  /* Truncate section */
                    ctx->current_group = &arg[2];
                    option = ptr + 1;
                } else {
                    option = &arg[2];
                    temp_section = NULL;
                }


                /* Now we have to find where the option is - it could either
                   be after an '=', or the next argument */
                if ( ( ptr = strchr(option,'=') ) != NULL ) {
                    *ptr = 0;
                    value = ptr + 1;
                } else if ( i + 1 < argc ) {
                    value = argv[i+1];
                    optc = i + 1;
                }

                if ( option ) {
                    if ( (ret = option_set(ctx, option,value) ) > 0 ) {
//                        argv[i] = NULL;
                        if ( ret > 0 ) {
//                            argv[optc] = NULL;
                            i = optc;
                        } else {
                            i++;
                        }
                    }
                }
                /* Restore the default section */
                if ( temp_section ) {
                    ctx->current_group = temp_section;
                }

                FREENULL(arg);
                if ( option == NULL ) {                    
                    return -1;
                }
            } else {   /* Short option handling */
                char sopt = argv[i][1];
                char *nextarg = NULL;

                if ( i + 1 < argc ) {
                    nextarg = argv[i+1];
                }

                if ( ( ret = option_set_sopt(ctx,sopt,nextarg) ) > 0 ) {
                    argv[i] = NULL;
                    argv[i + ret] = NULL;
                    i += ret;
                }
            }
        }
    }
    return 0;
}
示例#15
0
static GtkWidget * populate_predefined_projections(int projection)
{
    gchar * proj_dir=NULL;
    GDir * dir;
    GtkWidget * m;
    GtkWidget * item;

    m = gtk_menu_new();

    item = gtk_menu_item_new_with_label("User Defined");
    gtk_menu_append(GTK_MENU(m), item);
    gtk_widget_show(item);

    item = gtk_separator_menu_item_new();
    gtk_menu_append(GTK_MENU(m), item);
    gtk_widget_show(item);

    // do not populate the predefined projections for UTM -- too many,
    // the large dropdownlist causes crashes on windows. Also, no
    // predefined projections for the lat/lon psuedoprojection
    if (projection != PROJ_UTM && projection != PROJ_LATLON) {
      proj_dir = projection_directory(projection);
      if (proj_dir)
      {
        dir = g_dir_open(proj_dir, 0, NULL);
        
        if (dir)
        {
          int i, n;
          char *names[512];
          
          n = 0;
          while (TRUE)
          {
            const char * name;
            
            name = (char*) g_dir_read_name(dir);
            
            if (name)
            {
              char * name_dup;
              char * p;
              
              name_dup = STRDUP(name);
              p = strrchr(name_dup, '.');
              
              if (p && strcmp(p, ".proj") == 0)
              {
                *p = '\0';
                
                names[n] = name_dup;
                ++n;
                
                if (n >= sizeof(names)/sizeof(names[0]))
                  break;
              }
            }
            else
            {
              break;
            }
          }
          
          g_dir_close(dir);
          
          qsort(names, n, sizeof(char *), my_strcmp);
          for (i = 0; i < n; ++i)
          {
            item = gtk_menu_item_new_with_label(
              fudge_the_name(projection, names[i]));
            
            g_object_set_data(G_OBJECT(item),
                              "file", (gpointer)names[i]);
            
            gtk_menu_append(GTK_MENU(m), item);
            gtk_widget_show(item);
          }
        }
      }
    }

    if (proj_dir)
      g_free(proj_dir);

    return m;
}
示例#16
0
文件: block.c 项目: ab25cq/xyzsh
BOOL sCommand_add_command_without_command_name(sCommand* self, sCommand* command, char* sname, int sline)
{
    int i;
    for(i=1; i<command->mArgsNum; i++) {
        if(command->mArgsFlags[i] & XYZSH_ARGUMENT_ENV) {
            sBuf buf;
            memset(&buf, 0, sizeof(sBuf));
            buf.mBuf = MALLOC(64);
            buf.mBuf[0] = 0;
            buf.mSize = 64;

            char* p = command->mArgs[i];
            while(*p) {
                if(*p == PARSER_MAGIC_NUMBER_ENV) {
                    p++;

                    char buf2[128];
                    char* p2 = buf2;
                    while(*p != PARSER_MAGIC_NUMBER_ENV) {
                        *p2++ = *p++;
                    }
                    p++;
                    *p2 = 0;

                    int num = atoi(buf2) + self->mEnvsNum;
                    snprintf(buf2, 128, "%d", num);

                    add_char_to_buf(&buf, PARSER_MAGIC_NUMBER_ENV);
                    add_str_to_buf(&buf, buf2, strlen(buf2));
                    add_char_to_buf(&buf, PARSER_MAGIC_NUMBER_ENV);
                }
                else {
                    add_char_to_buf(&buf, *p++);
                }
            }
            if(!sCommand_add_arg(self, MANAGED buf.mBuf, command->mArgsFlags[i] & XYZSH_ARGUMENT_ENV, command->mArgsFlags[i] & XYZSH_ARGUMENT_QUOTED, command->mArgsFlags[i] & XYZSH_ARGUMENT_QUOTED_HEAD, command->mArgsFlags[i] & XYZSH_ARGUMENT_GLOB, command->mArgsFlags[i] & XYZSH_ARGUMENT_OPTION, sname, sline))
            {
                return FALSE;
            }
        }
        else {
            char* arg = STRDUP(command->mArgs[i]);
            if(!sCommand_add_arg(self, MANAGED arg, command->mArgsFlags[i] & XYZSH_ARGUMENT_ENV, command->mArgsFlags[i] & XYZSH_ARGUMENT_QUOTED, command->mArgsFlags[i] & XYZSH_ARGUMENT_QUOTED_HEAD, command->mArgsFlags[i] & XYZSH_ARGUMENT_GLOB, command->mArgsFlags[i] & XYZSH_ARGUMENT_OPTION, sname, sline))
            {
                return FALSE;
            }
        }
    }
    for(i=0; i<command->mEnvsNum; i++) {
        sEnv* env = command->mEnvs + i;

        if(env->mFlags & ENV_FLAGS_KIND_ENV) {
            if(!sCommand_add_env(self, MANAGED STRDUP(env->mName), MANAGED STRDUP(env->mInitValue), MANAGED STRDUP(env->mKey), env->mFlags & ENV_FLAGS_KEY_ENV, env->mFlags & ENV_FLAGS_KEY_QUOTED_STRING, sname, sline))
            {
                return FALSE;
            }
        }
        else {
            if(!sCommand_add_env_block(self, env->mBlock, env->mLineField, sname, sline)) {
                return FALSE;
            }
        }
    }
    for(i=0; i<command->mBlocksNum; i++) {
        sObject* block = block_clone_on_stack(command->mBlocks[i], T_BLOCK);
        if(!sCommand_add_block(self, block, sname, sline)) {
            return FALSE;
        }
    }
    for(i=0; i<command->mRedirectsNum; i++) {
        int flags = command->mRedirects[i];
        if(flags & REDIRECT_ENV) {
            sBuf buf;
            memset(&buf, 0, sizeof(sBuf));
            buf.mBuf = MALLOC(64);
            buf.mBuf[0] = 0;
            buf.mSize = 64;

            char* p = command->mRedirectsFileNames[i];
            while(*p) {
                if(*p == PARSER_MAGIC_NUMBER_ENV) {
                    p++;

                    char buf2[128];
                    char* p2 = buf2;
                    while(*p != PARSER_MAGIC_NUMBER_ENV) {
                        *p2++ = *p++;
                    }
                    p++;
                    *p2 = 0;

                    int num = atoi(buf2) + self->mEnvsNum;
                    snprintf(buf2, 128, "%d", num);

                    add_char_to_buf(&buf, PARSER_MAGIC_NUMBER_ENV);
                    add_str_to_buf(&buf, buf2, strlen(buf2));
                    add_char_to_buf(&buf, PARSER_MAGIC_NUMBER_ENV);
                }
                else {
                    add_char_to_buf(&buf, *p++);
                }
            }
            if(!sCommand_add_redirect(self, MANAGED buf.mBuf, flags & REDIRECT_ENV, flags & REDIRECT_QUOTED, flags & REDIRECT_GLOB, flags & REDIRECT_KIND, sname, sline)) 
            {
                return FALSE;
            }
        }
        else {
            if(!sCommand_add_redirect(self, MANAGED STRDUP(command->mRedirectsFileNames[i]), flags & REDIRECT_ENV, flags & REDIRECT_QUOTED, flags & REDIRECT_GLOB, flags & REDIRECT_KIND, sname, sline))
            {
                return FALSE;
            }
        }
    }

    return TRUE;
}
示例#17
0
SQLRETURN SQL_API
SQLDrivers_Internal (
  SQLHENV		  henv,
  SQLUSMALLINT		  fDir,
  SQLPOINTER		  szDrvDesc,
  SQLSMALLINT		  cbDrvDescMax,
  SQLSMALLINT 		* pcbDrvDesc,
  SQLPOINTER		  szDrvAttr,
  SQLSMALLINT		  cbDrvAttrMax,
  SQLSMALLINT 		* pcbDrvAttr,
  SQLCHAR		  waMode)
{
  GENV (genv, henv);
  char buffer[4096], desc[1024], *ptr;
  int i, j, usernum = 0;
  static int cur_entry = -1;
  static int num_entries = 0;
  static void **sect = NULL;
  SQLUSMALLINT fDirOld = fDir;

  waMode = waMode; /*UNUSED*/

  /* check argument */
  if (cbDrvDescMax < 0 || cbDrvAttrMax < 0)
    {
      PUSHSQLERR (genv->herr, en_S1090);
      return SQL_ERROR;
    }

  if (fDir != SQL_FETCH_FIRST && fDir != SQL_FETCH_NEXT)
    {
      PUSHSQLERR (genv->herr, en_S1103);
      return SQL_ERROR;
    }

  if (cur_entry < 0 || fDir == SQL_FETCH_FIRST)
    {
      cur_entry = 0;
      num_entries = 0;

      /*
      *  Free old section list
      */
      if (sect)
	{
	  for (i = 0; i < MAX_ENTRIES; i++)
	    if (sect[i])
	      free (sect[i]);
	  free (sect);
	}
      if ((sect = (void **) calloc (MAX_ENTRIES, sizeof (void *))) == NULL)
	{
	  PUSHSQLERR (genv->herr, en_S1011);
	  return SQL_ERROR;
	}

      if (fDirOld == SQL_FETCH_FIRST)
        fDir = SQL_FETCH_FIRST_USER;

      do {
        SQLSetConfigMode (fDir == SQL_FETCH_FIRST_SYSTEM ? ODBC_SYSTEM_DSN : ODBC_USER_DSN);
        SQLGetPrivateProfileString (SECT2, NULL, "", buffer, sizeof(buffer) / sizeof(SQLTCHAR), "odbcinst.ini");

        /* For each datasources */
        for(ptr = buffer, i = 1 ; *ptr && i ; ptr += STRLEN(ptr) + 1)
          {
            /* Add this section to the datasources list */
            if (fDirOld == SQL_FETCH_FIRST && fDir == SQL_FETCH_FIRST_SYSTEM)
              {
                for(j = 0 ; j<usernum ; j++)
                  {
                    if(STREQ(sect[j<<1], ptr))
                      j = usernum;
                  }
                if(j == usernum + 1)
                  continue;
              }

            if ((num_entries << 1) >= MAX_ENTRIES)
              {
                i = 0;
                break;
              }			/* Skip the rest */

            /* ... and its description */
            SQLSetConfigMode (fDir == SQL_FETCH_FIRST_SYSTEM ? ODBC_SYSTEM_DSN : ODBC_USER_DSN);
            SQLGetPrivateProfileString (SECT2, ptr, "", desc, sizeof(desc) / sizeof(SQLTCHAR), "odbcinst.ini");

            /* Check if the driver is installed */
				if(!STRCASEEQ(desc, "Installed"))
				  continue;

            /* Copy the driver name */
            sect[num_entries<<1] = STRDUP (ptr);
            sect[(num_entries++<<1) + 1] = STRDUP (desc);
          }

        switch(fDir)
          {
            case SQL_FETCH_FIRST_USER:
              fDir = SQL_FETCH_FIRST_SYSTEM;
              usernum = num_entries;
              break;
            case SQL_FETCH_FIRST_SYSTEM:
              fDir = SQL_FETCH_FIRST;
              break;
          };
      } while (fDir!=SQL_FETCH_FIRST && fDirOld==SQL_FETCH_FIRST);

      fDir = fDirOld;

      /*
       *  Sort all entries so we can present a nice list
       */
      if (num_entries > 1)
	{
          qsort (sect, num_entries, sizeof (char **) + sizeof (char **),
            SectSorter);
	}
    }

  /*
   *  Try to get to the next item
   */
  if (cur_entry >= num_entries)
    {
      cur_entry = 0;		/* Next time, start all over again */
      return SQL_NO_DATA_FOUND;
    }

  /*
   *  Copy Driver information 
   */
  STRNCPY (szDrvDesc, sect[cur_entry << 1], cbDrvDescMax);

  if (pcbDrvDesc)
    *pcbDrvDesc = STRLEN (szDrvDesc);

  /*
   *  And find the description that goes with this entry
   */
  STRNCPY (szDrvAttr, sect[(cur_entry << 1) + 1], cbDrvAttrMax);

  if (pcbDrvAttr)
    *pcbDrvAttr = STRLEN (szDrvAttr);

  /*
   *  Next record
   */
  cur_entry++;

  return SQL_SUCCESS;
}
示例#18
0
void DtPrinterIcon::DndCB(BaseUI *obj, char **value, int * /*len*/,
			  DNDProtocol dndProtocol)
{
   DtPrinterIcon *printer;
   if (obj->UIClass() == ICON)
      printer = (DtPrinterIcon *)obj;
   else
      printer = (DtPrinterIcon *)obj->Parent();
   DtActionArg ap[1];
   char *old_LPDEST = NULL;
   ap[0].argClass = DtACTION_FILE;

   char *buf = new char[100];
   switch (dndProtocol)
   {
   case FILENAME_TRANSFER: // Dropping an Object on a printer
      ap[0].u.file.name = *value;
      if (printer->PrintActionExists())
         sprintf(buf, "%s_Print", printer->queue->Name());
      else
       {
	 if (old_LPDEST = STRDUP(getenv("LPDEST")))
	  {
            sprintf(buf, "LPDEST=%s", printer->queue->Name());
	    putenv(buf);
	  }
         strcpy(buf, "Print");
       }

      DtActionInvoke(((AnyUI *)printer->mainw->Parent())->BaseWidget(), buf, ap,
		     1, NULL, NULL, NULL, True, NULL, NULL);
      if (old_LPDEST)
       {
	 sprintf(buf, "LPDEST=%s", old_LPDEST);
	 putenv(buf);
	 delete old_LPDEST;
       }
      break;
   case CONVERT_DATA: // Dragging a printer to an object
      if (printer->PrintActionExists())
       {
	 struct stat statbuff;
         *value = new char[strlen(homeDir) + strlen(PRINTERS_PERSONAL_DIR) +
			   strlen(printer->queue->Name()) + 10];
         sprintf(*value, "%s/%s/%s_Print", homeDir, PRINTERS_PERSONAL_DIR,
		 printer->queue->Name());
	 if (stat(*value, &statbuff) < 0)
	  {
	    int fd = creat(*value, 0755);
	    close(fd);
	  }
       }
      else
	 *value = NULL;
      break;
   case DROP_ON_ROOT:
      {
      char *x = *value;
      char *y = strchr(x, '\n');
      *y++ = '\0';
      char *filename = strchr(y, '\n');
      *filename++ = '\0';
      char *work_space = strchr(filename, '\n');
      if (work_space)
         *work_space++ = '\0';
      }
      break;
   case TEXT_TRANSFER:
      break;
   case BUFFER_TRANSFER:
      *value = new char[strlen(printer->queue->Name()) + 10];
      sprintf(*value, "%s_Print", printer->queue->Name());
      break;
   case CONVERT_DELETE:
      break;
   case ANIMATE:
      break;
   }
   delete [] buf;
}
示例#19
0
void generate ( FILE *stream, node_t *root )
{
    static int label_index = 0;
    int current_label_index;
    char *string_buffer;
    int elegant_solution;
    if ( root == NULL )
        return;

    switch ( root->type.index )
    {
    case PROGRAM:
        /* Output the data segment */
        strings_output ( stream );
        instruction_add ( STRING, STRDUP( ".text" ), NULL, 0, 0 );

        RECUR();
        TEXT_HEAD();

        instruction_add(CALL, root->children[0]->children[0]->children[0]->entry->label, NULL, 0, 0);

        TEXT_TAIL();

        instructions_print ( stream );
        instructions_finalize ();
        break;

    case FUNCTION:
        /*
         * Function definitions:
         * Set up/take down activation record for the function, return value
         */

        //Entering new scope, 'depth' is the depth of the current scope
        depth++;

        //Generating the string needed for the label instruction
        int len = strlen(root->children[0]->entry->label);
        char *temp = (char*) malloc(sizeof(char) * (len + 3));
        temp[0] = '_';
        for(int c = 0; c < len; c++) {
            temp[c+1] = root->children[0]->entry->label[c];
        }
        temp[len + 1] = ':';
        temp[len + 2] = 0;

        //Generate the label for the function, and the code to update the base ptr
        instruction_add(STRING, temp, NULL, 0, 0);
        instruction_add(PUSH, ebp, NULL, 0,0);
        instruction_add(MOVE, esp, ebp, 0,0);

        //Generating code for the functions body
        //The body is the last child, the other children are the name of the function
        //the arguments etc
        generate(stream, root->children[root->n_children - 1]);

        //Generating code to restore the base ptr, and to return
        instruction_add(LEAVE, NULL, NULL, 0,0);
        instruction_add(RET, NULL, NULL, 0,0);

        //Leaving the scope, decreasing depth
        depth--;
        break;

    case BLOCK:
        /*
         * Blocks:
         * Set up/take down activation record, no return value
         */

        //Entering new scope
        depth++;

        //Setting up the new activation record
        instruction_add(PUSH, ebp, NULL, 0,0);
        instruction_add(MOVE, esp, ebp, 0,0);

        //Generating code for the body of the block
        RECUR();

        //Restoring the old activation record
        instruction_add(LEAVE, NULL, NULL, 0,0);

        //Leaving scope
        depth--;
        break;

    case DECLARATION:
        /*
         * Declarations:
         * Add space on local stack
         */

        //The declarations first child is a VARIABLE_LIST, the number of children
        //of the VARIABLE_LIST is the number of variables declared. A 0 is pushed on
        //the stack for each
        for(uint32_t c = 0; c < root->children[0]->n_children; c++) {
            instruction_add(PUSH, STRDUP("$0"), NULL, 0,0);
        }
        break;

    case PRINT_LIST:
        /*
         * Print lists:
         * Emit the list of print items, followed by newline (0x0A)
         */

        //Generate code for all the PRINT_ITEMs
        RECUR();

        //Print a newline, push the newline, call 'putchar', and pop the argument
        //(overwriting the value returned from putchar...)
        instruction_add(PUSH, STRDUP("$0x0A"), NULL, 0, 0);
        instruction_add(SYSCALL, STRDUP("putchar"), NULL, 0,0);
        instruction_add(POP, eax, NULL, 0,0);
        break;

    case PRINT_ITEM:
        /*
         * Items in print lists:
         * Determine what kind of value (string literal or expression)
         * and set up a suitable call to printf
         */

        //Checking type of value, (of the child of the PRINT_ITEM,
        //which is what is going to be printed
        if(root->children[0]->type.index == TEXT) {
            //String, need to push '$.STRINGx' where x is the number of the string
            //The number can be found in the nodes data field, and must be transformed
            //to a string, and concatenated with the '$.STRING' part
            int32_t t = *((int32_t*)root->children[0]->data);
            char int_part[3]; //can have more than 999 strings...
            sprintf(int_part, "%d", t);
            char str_part[10] = "$.STRING";
            strcat(str_part, int_part);

            //Generating the instructions, pushing the argument of printf
            //(the string), calling printf, and removing the argument from
            //the stack (overwriting the returnvalue from printf)
            instruction_add(PUSH, STRDUP(str_part), NULL, 0,0);
            instruction_add(SYSCALL, STRDUP("printf"), NULL, 0,0);
            instruction_add(POP, eax,NULL,0,0);
        }
        else {
            //If the PRINT_ITEMs child isn't a string, it's an expression
            //The expression is evaluated, and its result, which is an integer
            //is printed

            //Evaluating the expression, the result is placed at the top of the stack
            RECUR();

            //Pushing the .INTEGER constant, which will be the second argument to printf,
            //and cause the first argument, which is the result of the expression, and is
            //allready on the stack to be printed as an integer
            instruction_add(PUSH, STRDUP("$.INTEGER"), NULL, 0,0);
            instruction_add(SYSCALL, STRDUP("printf"), NULL,0,0);

            //Poping both the arguments to printf
            instruction_add(POP, eax, NULL, 0,0);
            instruction_add(POP, eax, NULL, 0,0);
        }


        break;

    case EXPRESSION:
        /*
         * Expressions:
         * Handle any nested expressions first, then deal with the
         * top of the stack according to the kind of expression
         * (single variables/integers handled in separate switch/cases)
         */


        switch (root->n_children) {
        case 1:
            //One child, and some data, this is the -exp expression
            if(root->data != NULL) {
                //Computing the exp part of -exp, the result is placed on the top of the stack
                RECUR();

                //Negating the exp by computing 0 - exp
                instruction_add(POP, ebx, NULL, 0,0);
                instruction_add(MOVE, STRDUP("$0"), eax, 0,0);
                instruction_add(SUB, ebx, eax, 0,0);

                //Pushing the result on the stack
                instruction_add(PUSH, eax, NULL, 0,0);
            }
            else {
                //One child, and no data, this is variables
                //They are handeled later
                RECUR();
            }
            break;

        case 2:
            //Two children and no data, a function (call, not defenition)
            if(*(char*)(root->data) == 'F') {
                //Generate the code for the second child, the arguments, this will place them on the stack
                generate(stream, root->children[1]);

                //The call instruction
                instruction_add(CALL, STRDUP(root->children[0]->entry->label), NULL, 0,0);

                //Removing the arguments, changing the stack pointer directly, rather than poping
                //since the arguments aren't needed
                if(root->children[1] != NULL) {
                    for(int c = 0; c < root->children[1]->n_children; c++) {
                        instruction_add(ADD, STRDUP("$4"), esp, 0,0);
                    }
                }

                //Pushing the returnvalue from the function on the stack
                instruction_add(PUSH, eax, NULL, 0, 0);
                break;
            }


            //Two children and data, this is the arithmetic expressions
            //The two children are evaluated first, which places their values
            //at the top of the stack. More precisely, the result of the second
            //subexpression will be placed at the top of the stack, the result of
            //the first on the position below it
            RECUR();
            if(strlen((char*)root->data) == 1) {
                switch (*(char*)root->data) {

                // Addition and subtraction is handeled equally
                // The arguments are placed in the eax and ebx registers
                // they are added/subtracted, and the result is pushed on the stack
                case '+':
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(ADD, ebx, eax, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '-':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(SUB, ebx, eax, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;

                //With multiplication/division it's also necessary to sign extend the
                //arguments, using the CLTD instruction, the MUL/DIV instructions only need
                //one argument, the other one is eax
                case '*':
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(CLTD, NULL, NULL, 0,0);
                    instruction_add(MUL, ebx, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '/':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CLTD, NULL, NULL, 0,0);
                    instruction_add(DIV, ebx, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '>':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETG, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '<':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETL, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                }

            }
            else {
                switch (*(char*)root->data) {
                case '>':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETGE, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '<':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETLE, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '=':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETE, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                case '!':
                    instruction_add(POP, ebx, NULL, 0,0);
                    instruction_add(POP, eax, NULL, 0,0);
                    instruction_add(CMP, ebx, eax, 0,0);
                    instruction_add(SETNE, al, NULL, 0,0);
                    instruction_add(CBW, NULL, NULL, 0,0);
                    instruction_add(CWDE, NULL, NULL, 0,0);
                    instruction_add(PUSH, eax, NULL, 0,0);
                    break;
                }
            }
        }


        break;

    case VARIABLE:
        /*
         * Occurrences of variables: (declarations have their own case)
         * - Find the variable's stack offset
         * - If var is not local, unwind the stack to its correct base
         */

        //Finding the scope of the variable. If the difference is 0, it is
        //defined in this scope, if it is 1, the previous one and so on
        depth_difference = depth - root->entry->depth;

        //The offset of the variable is relative to its ebp. The current ebp is saved
        //on the stack, and the needed one retrived
        instruction_add(PUSH, ebp, NULL, 0,0);

        //The ebp points to the previous ebp, which points to the ebp before it and so on.
        //The ideal instruction to use would be 'movl (%ebp) %ebp', but that can't be done
        //with this framework. Rather than changing the framework, the following hack is used:
        //
        //The constant 4 and the contents of ebp is added and placed in eax, then the
        //the value pointed to by eax with an offset of -4, that is -4(%eax), is placed in ebp
        //since eax is ebp + 4, -4(%eax) is really (%ebp)
        for(int c = 0; c < depth_difference; c++) {
            instruction_add(MOVE, STRDUP("$4"), eax, 0,0);
            instruction_add(ADD, ebp, eax, 0,0);
            instruction_add(MOVE, eax, ebp, -4,0);
        }

        //The offset of the vaiable (from its ebp)
        int32_t offset = root->entry->stack_offset;

        //The value of the variable is placed in eax, the right ebp is used, because of
        //the system above
        instruction_add(MOVE, ebp, eax, offset, 0);

        //The current ebp is restored
        instruction_add(POP, ebp, NULL, 0,0);

        //The value of the variable is placed on the stack (since it's a kind of expression)
        instruction_add(PUSH, eax, NULL, 0,0);

        break;

    case INTEGER:
        /*
         * Integers: constants which can just be put on stack
         */

        //We can't have a label followed by a declaration, so this is needed...
        elegant_solution = 0;

        //The value of the integer is fetched and converted to a string
        char temp1[10]; //ints are 4 bytes, so this is enough
        int32_t t = *((int32_t*)root->data);
        sprintf(temp1, "%d", t);
        char temp2[11] = "$";
        strcat(temp2, temp1);

        //The value is pushed on the stack
        instruction_add(PUSH, STRDUP(temp2), NULL, 0,0);
        break;

    case ASSIGNMENT_STATEMENT:
        /*
         * Assignments:
         * Right hand side is an expression, find left hand side on stack
         * (unwinding if necessary)
         */

        //Generating the code for the expression part of the assingment. The result is
        //placed on the top of the stack
        generate(stream, root->children[1]);

        //Using same scheme as above
        depth_difference = depth - root->children[0]->entry->depth;

        instruction_add(PUSH, ebp, NULL, 0,0);
        for(int c = 0; c < depth_difference; c++) {
            instruction_add(MOVE, STRDUP("$4"), eax, 0,0);
            instruction_add(ADD, ebp, eax, 0,0);
            instruction_add(MOVE, eax, ebp, -4,0);
        }

        int32_t offset_2 = root->children[0]->entry->stack_offset;

        //Putting the current ebp in ebx
        instruction_add(POP, ebx, NULL, 0,0);

        //Putting the result of the expression in eax
        instruction_add(POP, eax, NULL, 0,0);

        //Putting the result of the expression in the variable (ebp is the ebp of the variable)
        instruction_add(MOVE, eax, ebp, 0, offset_2);

        //Restoring the current ebp
        instruction_add(MOVE, ebx, ebp, 0, 0);
        break;

    case RETURN_STATEMENT:
        /*
         * Return statements:
         * Evaluate the expression and put it in EAX
         */
        RECUR();
        instruction_add(POP, eax, NULL, 0,0);

        for ( int u=0; u<depth-1; u++ ) {
            instruction_add ( LEAVE, NULL, NULL, 0, 0 );
        }
        instruction_add ( RET, eax, NULL, 0, 0 );

        break;

    case WHILE_STATEMENT:
        /* Start-label for the while statement. */
        current_label_index = label_index++;
        string_buffer = malloc(sizeof(*string_buffer) * 17);
        sprintf(string_buffer, "WHILE%d:", current_label_index);

        instruction_add(STRING, string_buffer, NULL, 0, 0);

        /* Evaulate the expression and compare it to 0. */
        generate(stream, root->children[0]);

        /* Jump out of the loop if the expression evaluated to 0. */
        instruction_add(POP, eax, NULL, 0, 0);
        instruction_add(CMPZERO, eax, NULL, 0, 0);

        string_buffer = malloc(sizeof(*string_buffer) * 19);
        sprintf(string_buffer, "WHLIEEND%d", current_label_index);

        instruction_add(JUMPZERO, string_buffer, NULL, 0, 0);

        /* Execute the loop body. */
        generate(stream, root->children[1]);

        /* Jump to the start of the loop. */
        string_buffer = malloc(sizeof(*string_buffer) * 16);
        sprintf(string_buffer, "WHILE%d", current_label_index);

        instruction_add(JUMP, string_buffer, NULL, 0, 0);

        /* Label for loop end. */
        string_buffer = malloc(sizeof(*string_buffer) * 20);
        sprintf(string_buffer, "WHLIEEND%d:", current_label_index);

        instruction_add(STRING, string_buffer, NULL, 0, 0);
        break;

    case FOR_STATEMENT:
        current_label_index = label_index++;
        /* Initialise the loop variable. */
        generate(stream, root->children[0]);

        /* Start-label for the for-loop. */
        string_buffer = malloc(sizeof(*string_buffer) * 20);
        sprintf(string_buffer, "FORSTART%d:", current_label_index);

        instruction_add(STRING, string_buffer, NULL, 0, 0);

        /*
         * Push both the variable and the end result on the stack for
         * comparison.
         */
        generate(stream, root->children[0]->children[0]);
        generate(stream, root->children[1]);

        instruction_add(POP, eax, NULL, 0, 0);
        instruction_add(POP, ebx, NULL, 0, 0);
        instruction_add(CMP, eax, ebx, 0, 0);

        /* Exit the loop if both are equal. */
        string_buffer = malloc(sizeof(*string_buffer) * 17);
        sprintf(string_buffer, "FOREND%d", current_label_index);
        instruction_add(JUMPEQ, string_buffer, NULL, 0, 0);

        /* Execute loop body. */
        generate(stream, root->children[2]);

        /*
         * Find the variable and increase it's value by one. Code copied
         * from the VARIABLE case. Comments and extra empty lines removed to
         * preserve space.
         */
        depth_difference = depth - root->children[0]->children[0]->entry->depth;
        instruction_add(PUSH, ebp, NULL, 0,0);
        for(int c = 0; c < depth_difference; c++) {
            instruction_add(MOVE, STRDUP("$4"), eax, 0,0);
            instruction_add(ADD, ebp, eax, 0,0);
            instruction_add(MOVE, eax, ebp, -4,0);
        }
        int32_t offset2 = root->children[0]->children[0]->entry->stack_offset;
        /* Add one to the memory location. */
        instruction_add(ADD, STRDUP("$1"), ebp, 0, offset2);
        instruction_add(POP, ebp, NULL, 0,0);
        /*
         * End of copied section.
         */

        /* Jump to the start of the loop. */
        string_buffer = malloc(sizeof(*string_buffer) * 19);
        sprintf(string_buffer, "FORSTART%d", current_label_index);

        instruction_add(JUMP, string_buffer, NULL, 0, 0);

        /* Loop end label. */
        string_buffer = malloc(sizeof(*string_buffer) * 18);
        sprintf(string_buffer, "FOREND%d:", current_label_index);

        instruction_add(STRING, string_buffer, NULL, 0, 0);

        break;

    case IF_STATEMENT:
        current_label_index = label_index++;

        /* Evaluate the if-expression, and compare it to 0. */
        generate(stream, root->children[0]);

        instruction_add(POP, eax, NULL, 0, 0);
        instruction_add(CMPZERO, eax, NULL, 0, 0);

        /*
         * Jump to the end of the if-block if the expression evaluated to
         * 0.
         */
        string_buffer = malloc(sizeof(*string_buffer) * 16);
        sprintf(string_buffer, "IFEND%d", current_label_index);

        instruction_add(JUMPZERO, string_buffer, NULL, 0, 0);

        /* The if body. */
        generate(stream, root->children[1]);

        /* IF-THEN-ELSE */
        if (root->n_children == 3) {
            /* Add a jump to after the else body. */
            string_buffer = malloc(sizeof(*string_buffer) * 18);
            sprintf(string_buffer, "ELSEEND%d", current_label_index);

            instruction_add(JUMP, string_buffer, NULL, 0, 0);

            /* The else body. */
            string_buffer = malloc(sizeof(*string_buffer) * 17);
            sprintf(string_buffer, "IFEND%d:", current_label_index);

            instruction_add(STRING, string_buffer, NULL, 0, 0);

            generate(stream, root->children[2]);

            string_buffer = malloc(sizeof(*string_buffer) * 19);
            sprintf(string_buffer, "ELSEEND%d:", current_label_index);

            instruction_add(STRING, string_buffer, NULL, 0, 0);
            /* IF-THEN */
        } else {
            /* Just print out the IFEND label. */
            string_buffer = malloc(sizeof(*string_buffer) * 17);
            sprintf(string_buffer, "IFEND%d:", current_label_index);

            instruction_add(STRING, string_buffer, NULL, 0, 0);
        }
        break;

    case NULL_STATEMENT:
        RECUR();
        break;

    default:
        /* Everything else can just continue through the tree */
        RECUR();
        break;
    }
}
示例#20
0
文件: generator.c 项目: sondrele/NTNU
void generate ( FILE *stream, node_t *root )
{
	int elegant_solution;
	if ( root == NULL )
		return;

	switch ( root->type.index )
	{
		case PROGRAM: {
			/* Output the data segment */
			strings_output ( stream );
			instruction_add ( STRING, STRDUP( ".text" ), NULL, 0, 0 );

			RECUR ();
			TEXT_HEAD ();
			/* TODO: Insert a call to the first defined function here */
			node_t *main_func = root->children[0]->children[0];
			instruction_add ( CALL, STRDUP( (char *) main_func->children[0]->data ),
					NULL, 0, 0);
			TEXT_TAIL ();

			instructions_print ( stream );
			instructions_finalize ();
			break;
		}
		case FUNCTION: {
			/*
			 * Function definitions:
			 * Set up/take down activation record for the function, return value
			 */
			depth += 1;
			instruction_add ( LABEL, STRDUP( root->children[0]->data ), NULL, 0, 0 );
			instruction_add ( PUSH, ebp, NULL, 0, 0 );
			instruction_add ( MOVE, esp, ebp, 0, 0 );
			// Generate for the children, except for the BLOCK-statement
			generate ( stream, root->children[2]->children[0] );
			generate ( stream, root->children[2]->children[1] );
			instruction_add ( LEAVE, NULL, NULL, 0, 0 );
			instruction_add ( RET, NULL, NULL, 0, 0 );
			depth -= 1;
			break;
		}
		case BLOCK: {
			/*
			 * Blocks:
			 * Set up/take down activation record, no return value
			 */
			depth += 1;
			instruction_add ( PUSH, ebp, NULL, 0, 0 );
			instruction_add ( MOVE, esp, ebp, 0, 0 );
			generate ( stream, root->children[0] );
			// This is done in order to avoid executing any statements in a STATEMENT_LIST,
			// that is occuring after a RETURN_STATEMENT 
			node_t *statement_list_n = root->children[1];
			for ( int i = 0; i < statement_list_n->n_children; i++ ) {
				generate ( stream, statement_list_n->children[i] );
				if ( statement_list_n->children[i]->type.index == RETURN_STATEMENT )
					break;
			}
			// Push a dummy value to the stack, so LEAVE works properly
			instruction_add ( PUSH, STRDUP( "$0" ), NULL, 0, 0 );
			instruction_add ( LEAVE, NULL, NULL, 0, 0 );
			depth -= 1;
			break;
		}
		case DECLARATION: {
			/*
			 * Declarations:
			 * Add space on local stack
			 */
			int offset = 0;
			for ( int i = 0; i < root->children[0]->n_children; i++ ) {
				offset -= 4;
				instruction_add ( PUSH, esp, NULL, offset, 0 );
			}
			break;
		}
		case PRINT_LIST: {
			/*
			 * Print lists:
			 * Emit the list of print items, followed by newline (0x0A)
			 */
			instruction_add ( PUSH, ecx, NULL, 0, 0 );
			RECUR ();
			instruction_add ( PUSH, STRDUP( "$10" ), NULL, 0, 0 );
			instruction_add ( SYSCALL, STRDUP( "putchar" ), NULL, 0, 0 );
			instruction_add ( ADD, STRDUP( "$4" ), esp, 0, 0 );
			instruction_add ( POP, ecx, NULL, 0, 0 );
			break;
		}
		case PRINT_ITEM: {
			/*
			 * Items in print lists:
			 * Determine what kind of value (string literal or expression)
			 * and set up a suitable call to printf
			 */
			if ( root->children[0]->type.index == TEXT ) {
				char str[30];
				sprintf ( str, "$.STRING%d", *(int *)root->children[0]->data );
				instruction_add ( PUSH, STRDUP( str ), NULL, 0, 0 );
				instruction_add ( SYSCALL, STRDUP( "printf" ), NULL, 0, 0 );
				instruction_add ( ADD, STRDUP( "$4" ), esp, 0, 0 );
			} else {
				// Add expression to top of stack, for use in printf
				generate ( stream, root->children[0] );
				instruction_add ( PUSH, STRDUP( "$.INTEGER" ), NULL, 0, 0 );
				instruction_add ( SYSCALL, STRDUP( "printf" ), NULL, 0, 0 );
				instruction_add ( ADD, STRDUP( "$8" ), esp, 0, 0 );
			}
			break;
		}
		case EXPRESSION: {
			/*
			 * Expressions:
			 * Handle any nested expressions first, then deal with the
			 * top of the stack according to the kind of expression
			 * (single variables/integers handled in separate switch/cases)
			 */
			// The expression is a function call
			if ( root->n_children == 2 && ( root->children[1] == NULL
					|| root->children[1]->type.index == EXPRESSION_LIST ) ) {
				// Push parameters on stack
				generate ( stream, root->children[1] );
				instruction_add ( CALL, STRDUP( (char *) root->children[0]->data ),
					NULL, 0, 0);
				// The evaluated expression to the stack
				instruction_add ( PUSH, eax, NULL, 0, 0 );
			} else if ( root->n_children == 2) {
				RECUR ();
				instruction_add ( POP, ebx, NULL, 0, 0 );
				instruction_add ( POP, eax, NULL, 0, 0 );
				char *data = (char *) root->data;
				switch ( data[0] ) {
					case '+':
						instruction_add ( ADD, ebx, eax, 0, 0 );
						break;
					case '-':
						instruction_add ( SUB, ebx, eax, 0, 0 );
						break;
					case '*':
						instruction_add ( MUL, ebx, NULL, 0, 0 );
						break;
					case '/':
						instruction_add ( CLTD, NULL, NULL, 0, 0 );
						instruction_add ( DIV, ebx, NULL, 0, 0 );
						break;
					// The following cases is a bit repetative, I know
					// Maybe gcc will optimize it a bit? ;-)
					case '=':
						instruction_add ( CMP, ebx, eax, 0, 0 );
						instruction_add ( SETE, al, NULL, 0, 0 );
						instruction_add ( CBW, NULL, NULL, 0, 0 );
						instruction_add ( CWDE, NULL, NULL, 0, 0 );
						break;
					case '!':
						instruction_add ( CMP, ebx, eax, 0, 0 );
						instruction_add ( SETNE, al, NULL, 0, 0 );
						instruction_add ( CBW, NULL, NULL, 0, 0 );
						instruction_add ( CWDE, NULL, NULL, 0, 0 );
						break;
					case '>':
						instruction_add ( CMP, ebx, eax, 0, 0 );
						if ( strlen( data ) == 2 )
							instruction_add ( SETGE, al, NULL, 0, 0 );
						else
							instruction_add ( SETG, al, NULL, 0, 0 );
						instruction_add ( CBW, NULL, NULL, 0, 0 );
						instruction_add ( CWDE, NULL, NULL, 0, 0 );
						break;
					case '<':
						instruction_add ( CMP, ebx, eax, 0, 0 );
						if ( strlen( data ) == 2 )
							instruction_add ( SETLE, al, NULL, 0, 0 );
						else
							instruction_add ( SETL, al, NULL, 0, 0 );
						instruction_add ( CBW, NULL, NULL, 0, 0 );
						instruction_add ( CWDE, NULL, NULL, 0, 0 );
						break;
				}
				instruction_add ( PUSH, eax, NULL, 0, 0 );
			} else if ( root->data != NULL && *(char *)root->data == '-' ) {
				// Unary minus
				RECUR ();
				instruction_add ( POP, eax, NULL, 0, 0 );
				instruction_add ( NEG, eax, NULL, 0, 0 );
				instruction_add ( PUSH, eax, NULL, 0, 0 );
			}
			break;
		}
		case VARIABLE: {
			/*
			 * Occurrences of variables: (declarations have their own case)
			 * - Find the variable's stack offset
			 * - If var is not local, unwind the stack to its correct base
			 */
			int stack_offset = root->entry->stack_offset;
			// If the variable is at right deapth, or it is a function argument, PUSH
			// the value of variable to the stack
			if ( depth == root->entry->depth  
					|| stack_offset > 0 && root->entry->depth == (depth-1) ) {
				instruction_add ( PUSH, ebp, NULL, stack_offset, 0 );
			} else {
				// Else unwind
				instruction_add ( MOVE, ebp, ebx, 0, 0 );
				// If the variable is an argument, the deapth, i.e. 'i', is decreased
				// by 1
				int i = stack_offset > 0 ? -1 : 0;
				for ( i += depth-1; i >= root->entry->depth; i-- ) {
					instruction_add ( MOVE, STRDUP("(%ebx)"), ebx, 0, 0 );
				}
				instruction_add ( PUSH, ebx, NULL, stack_offset, 0 );
			}
			break;
		}
		case ASSIGNMENT_STATEMENT: {
			/*
			 * Assignments:
			 * Right hand side is an expression, find left hand side on stack
			 * (unwinding if necessary)
			 */
			// This behaves almost the same as the VARIABLE case
			generate ( stream, root->children[1] );
			root->entry = root->children[0]->entry;
			int stack_offset = root->entry->stack_offset;
			if ( depth == root->entry->depth ) {
				instruction_add ( POP, ebp, NULL, stack_offset, 0 );
			} else {
				instruction_add ( MOVE, ebp, ebx, 0, 0 );
				for ( int i = depth-1; i >= root->entry->depth; i-- ) {
					instruction_add ( MOVE, STRDUP("(%ebx)"), ebx, 0, 0 );
				}
				instruction_add ( POP, ebx, NULL, stack_offset, 0 );
			}
			break;
		}
		case INTEGER: {
			/*
			 * Integers: constants which can just be put on stack
			 */
			char str[30];
			sprintf ( str, "$%d", *(int *)root->data );
			instruction_add ( PUSH, STRDUP( str ), NULL, 0, 0 );

			break;
		}
		case RETURN_STATEMENT: {
			/*
			 * Return statements:
			 * Evaluate the expression and put it in EAX
			 */
			RECUR ();
			instruction_add ( POP, eax, NULL, 0, 0 );
			break;
		}
		case WHILE_STATEMENT: {
            char whilestart[30];
            char _whilestart[30];
            char whileend[30];
            char _whileend[30];
            sprintf ( whilestart, "whilestart%d", while_label );
            sprintf ( _whilestart, "_whilestart%d", while_label );
            sprintf ( whileend, "whileend%d", while_label );
            sprintf ( _whileend, "_whileend%d", while_label++ );

            instruction_add ( LABEL, STRDUP( whilestart ), NULL, 0, 0 );
    		generate ( stream, root->children[0] );
            instruction_add ( CMPZERO, eax, NULL, 0, 0 );
            instruction_add ( JUMPZERO,  STRDUP( _whileend ), NULL, 0, 0 );
            generate ( stream, root->children[1] );
            instruction_add ( JUMP, STRDUP( _whilestart ), NULL, 0, 0 );
            instruction_add ( LABEL, STRDUP( whileend ), NULL, 0, 0 );
            break;
        }
        case FOR_STATEMENT: {
            char forstart[30];
            char _forstart[30];
            char forend[30];
            char _forend[30];
            sprintf ( forstart, "forstart%d", for_label );
            sprintf ( _forstart, "_forstart%d", for_label++ );

            // Initialize ecx, i.e. the loop counter
            generate ( stream, root->children[0] );
            instruction_add ( PUSH, eax, NULL, 0, 0 );
            instruction_add ( MOVE, eax, edi, 0, 0 );
            generate ( stream, root->children[1] );
            instruction_add ( POP, eax, NULL, 0,0 ); 
            instruction_add ( POP, ebx, NULL, 0,0 );
            instruction_add ( SUB, ebx, eax, 0,0 );
            instruction_add ( PUSH, eax, NULL, 0,0 );
            instruction_add ( POP, ecx, NULL, 0, 0 );
            
            // Start loop
            instruction_add ( LABEL, STRDUP( forstart ), NULL, 0, 0 );
            generate ( stream, root->children[2] );

            // Increment counter
            instruction_add ( ADD, STRDUP( "$1" ), edi, 0, 0 );
            instruction_add ( PUSH, edi, NULL, 0, 0 );
            depth_difference = depth - root->children[0]->children[0]->entry->depth;
            instruction_add(PUSH, ebp, NULL, 0,0);
            for(int c = 0; c < depth_difference; c++){
                instruction_add(MOVE, STRDUP("$4"), eax, 0,0);
                instruction_add(ADD, ebp, eax, 0,0);
                instruction_add(MOVE, eax, ebp, -4,0);
            }
            int32_t offset_2 = root->children[0]->children[0]->entry->stack_offset;
            //Putting the current ebp in ebx
            instruction_add(POP, ebx, NULL, 0,0);
            //Putting the result of the expression in eax
            instruction_add(POP, eax, NULL, 0,0);
            //Putting the result of the expression in the variable (ebp is the ebp of the variable)
            instruction_add(MOVE, eax, ebp, 0, offset_2);
            //Restoring the current ebp
            instruction_add(MOVE, ebx, ebp, 0, 0);

            // Loop
            instruction_add ( LOOP, STRDUP( _forstart ), NULL, 0, 0 );
            //instruction_add ( JUMPZERO, STRDUP( "TEST" ), NULL, 0, 0 );
            break;
        }
        case IF_STATEMENT: {
            char ifend[30];
            char _ifend[30];
            char ifelse[30];
            char _ifelse[30];
            sprintf ( ifend, "ifend%d", if_label );
            sprintf ( _ifend, "_ifend%d", if_label );
            sprintf ( ifelse, "ifelse%d", if_label );
            sprintf ( _ifelse, "_ifelse%d", if_label++ );
            // IF-THEN-FI
            if ( root->n_children == 2 ) {
                char str[30];
                node_t *expr = root->children[0];
                sprintf ( str, "expr: n:%d", expr->n_children );
                instruction_add ( JUMPZERO, STRDUP(str), NULL, 0, 0 );
                generate ( stream, root->children[0] );
                instruction_add ( CMPZERO, eax, NULL, 0, 0 );
                instruction_add ( JUMPZERO,  STRDUP( _ifend ), NULL, 0, 0 );
                generate ( stream, root->children[1] );
                instruction_add ( LABEL, STRDUP( ifend ), NULL, 0, 0 );
            } // IF-THEN-ELSE-FI
            else {
                generate ( stream, root->children[0] );
                instruction_add ( CMPZERO, eax, NULL, 0, 0 );
                instruction_add ( JUMPZERO,  STRDUP( _ifelse ), NULL, 0, 0 );
                generate ( stream, root->children[1] );
                instruction_add ( JUMP, STRDUP( _ifend ), NULL, 0, 0 );
                instruction_add ( LABEL, STRDUP( ifelse ), NULL, 0, 0 );
                generate ( stream, root->children[2] );
                instruction_add ( JUMP, STRDUP( _ifend ), NULL, 0, 0 );
                instruction_add ( LABEL, STRDUP( ifend ), NULL, 0, 0 );
            }
            break;
        }
		default:
			/* Everything else can just continue through the tree */
			RECUR();
			break;
	}
}
示例#21
0
void gen_PRINT_STATEMENT(node_t* root, int scopedepth)
{
    tracePrint("Starting PRINT_STATEMENT\n");

    for(int i = 0; i < root->children[0]->n_children; i++){

        root->children[0]->children[i]->generate(root->children[0]->children[i], scopedepth);

        //Pushing the .INTEGER constant, which will be the second argument to printf,
        //and cause the first argument, which is the result of the expression, and is
        //allready on the stack to be printed as an integer
        base_data_type_t t = root->children[0]->children[i]->data_type.base_type;
        switch(t)
        {
            case INT_TYPE:
                instruction_add(STRING, STRDUP("\tmovw	r0, #:lower16:.INTEGER"), NULL, 0,0);
                instruction_add(STRING, STRDUP("\tmovt	r0, #:upper16:.INTEGER"), NULL, 0,0);
                instruction_add(POP, r1, NULL, 0,0);
                break;

            case FLOAT_TYPE:
                instruction_add(LOADS, sp, s0, 0,0);
                instruction_add(CVTSD, s0, d0, 0,0);
                instruction_add(STRING, STRDUP("\tfmrrd	r2, r3, d0"), NULL, 0,0);
                instruction_add(STRING, STRDUP("\tmovw	r0, #:lower16:.FLOAT"), NULL, 0,0);
                instruction_add(STRING, STRDUP("\tmovt	r0, #:upper16:.FLOAT"), NULL, 0,0);

                // And now the tricky part... 8-byte stack alignment :(
                // We have at least 4-byte alignment always.
                // Check if its only 4-byte aligned right now by anding that bit in the stack-pointer.
                // Store the answer in r5, and set the zero flag.
                instruction_add(STRING, STRDUP("\tandS	r5, sp, #4"), NULL, 0,0);
                // Now use the zero flag as a condition to optionally change the stack-pointer
                instruction_add(STRING, STRDUP("\tpushNE	{r5}"), NULL, 0,0);
                break;

            case BOOL_TYPE:
                instruction_add(STRING, STRDUP("\tmovw	r0, #:lower16:.INTEGER"), NULL, 0,0);
                instruction_add(STRING, STRDUP("\tmovt	r0, #:upper16:.INTEGER"), NULL, 0,0);
                instruction_add(POP, r1, NULL, 0,0);
                break;

            case STRING_TYPE:
                instruction_add(POP, r0, NULL, 0,0);
                break;

            default:
                instruction_add(PUSH, STRDUP("$.INTEGER"), NULL, 0,0);
                fprintf(stderr, "WARNING: attempting to print something not int, float or bool\n");
                break;
        }

        instruction_add(SYSCALL, STRDUP("printf"), NULL,0,0);

        // Undo stack alignment.
        if(t == FLOAT_TYPE) {
            // Redo the zero flag test on r5, as it will give the same answer as the first test on sp.
            instruction_add(STRING, STRDUP("\tandS	r5, #4"), NULL, 0,0);
            // Conditionally remove the alignment. 
            instruction_add(STRING, STRDUP("\tpopNE	{r5}"), NULL, 0,0);
        }
    }

    instruction_add(MOVE32, STRDUP("#0x0A"), r0, 0,0);
    instruction_add(SYSCALL, STRDUP("putchar"), NULL, 0,0);

    tracePrint("Ending PRINT_STATEMENT\n");
}
示例#22
0
static BOOL script_initCodeFromUri(struct Shader_Script* me, const char* uri)
{
 size_t i;
 int rv;
 resource_item_t *res;
	ppCScripts p = (ppCScripts)gglobal()->CScripts.prv;

  rv = FALSE; /* initialize it */

 /* strip off whitespace at the beginning JAS */
 while ((*uri<= ' ') && (*uri>0)) uri++;

 /* Try javascript protocol */
 for(i=0; i!=ARR_SIZE(JS_PROTOCOLS); ++i)
 {
  const char* u=uri;
  const char* v=JS_PROTOCOLS[i];

  while(*u && *v && *u==*v)
  {
   ++u;
   ++v;
  }

  /* Is this a "data:text/plain," uri? JAS*/
  if((!*v && *u==',') || (!*v && *u==':')) {
   	if (me != NULL) {
		return script_initCode(me, u+1); /* a script */
	} else {
		p->buffer = STRDUP(u+1);
		return TRUE; /* a shader, program text will be in the "buffer" */
	}
   }
 }

 /* Not a valid script in this SFString. Lets see if this
    is this a possible file that we have to get? */

 DEBUG_CPARSER("script_initCodeFromUri, uri is %s\n", uri); 
 printf ("script_initCodeFromUri, uri is %s\n", uri); 

 res = resource_create_single(uri);
 resource_identify(gglobal()->resources.root_res, res);
 if (res->type != rest_invalid) {
	 if (resource_fetch(res)) {
		 if (resource_load(res)) {
			 s_list_t *l;
			 openned_file_t *of;

			 l = res->openned_files;
			 of = ml_elem(l);

			/* ok - Scripts get initialized; shaders get the buffer returned */
			if (me==NULL) { /* a Shader */
			 	p->buffer = STRDUP(of->fileData);
			 	/* JAS printf("**** Shader:\n%s\n", buffer); 
				printf ("*** Shader: doing the quick return here\n"); */
				return TRUE;
			} else {
				/* a Script */
			 	/* printf("**** Script:\n%s\n", buffer); */
			 	rv = script_initCode(me, of->fileData);
			}
		 }
	 }
 }
 
 
 if (res->status == ress_loaded && rv) {
	 /* ok - we are replacing EXTERNPROTO with PROTO */
	 res->status = ress_parsed;
	 res->complete = TRUE;
	 return TRUE;
 } else {
	 /* failure, FIXME: remove res from root_res... */
/* 		resource_destroy(res); */
 }

 return FALSE;
}
示例#23
0
static int
bladehpi_set_config(StonithPlugin *s, StonithNVpair *list)
{
	struct pluginDevice *	dev = NULL;
	StonithNamesToGet	namestocopy [] =
	{	{ST_ENTITYROOT,	NULL}
	,	{NULL,		NULL}
	};
	int			rc, i;
	SaErrorT		ohrc;
	
	if (Debug) {
		LOG(PIL_DEBUG, "%s: called", __FUNCTION__);
	}
	
	ERRIFWRONGDEV(s, S_OOPS);

	dev = (struct pluginDevice *)s;

	if (Debug) {
		LOG(PIL_DEBUG, "%s conditionally compiled with:"
#ifdef IBMBC_WAIT_FOR_OFF
		" IBMBC_WAIT_FOR_OFF"
#endif
		, dev->pluginid);
	}
	
	if ((rc = OurImports->CopyAllValues(namestocopy, list)) != S_OK) {
		return rc;
	}

	if (Debug) {
		LOG(PIL_DEBUG, "%s = %s", ST_ENTITYROOT
		,	namestocopy[0].s_value);	
	}

	if (get_num_tokens(namestocopy[0].s_value) == 1) {
		/* name=value pairs on command line, look for soft_reset */
		const char *softreset = 
			OurImports->GetValue(list, ST_SOFTRESET);
		if (softreset != NULL) {
			if (!strcasecmp(softreset, "true") ||
			    !strcmp(softreset, "1")) {
				dev->softreset = 1;
			} else if (!strcasecmp(softreset, "false") ||
				   !strcmp(softreset, "0")) {
				dev->softreset = 0;
			} else {
				LOG(PIL_CRIT, "Invalid %s %s, must be "
					"true, 1, false or 0"
				,	ST_SOFTRESET, softreset);
				FREE(namestocopy[0].s_value);
				return S_OOPS;
			}
		}
	} else {
		/* -p or -F option with args "entity_root [soft_reset]..." */
		char *pch = namestocopy[0].s_value;

		/* skip over entity_root and null-terminate */
		pch += strcspn(pch, WHITESPACE);
		*pch = EOS;

		/* skip over white-space up to next token */
		pch++;
		pch += strspn(pch, WHITESPACE);
		if (!strcasecmp(pch, "true") || !strcmp(pch, "1")) {
			dev->softreset = 1;
		} else if (!strcasecmp(pch, "false") || !strcmp(pch, "0")) {
			dev->softreset = 0;
		} else {
			LOG(PIL_CRIT, "Invalid %s %s, must be "
				"true, 1, false or 0"
			,	ST_SOFTRESET, pch);
			FREE(namestocopy[0].s_value);
			return S_OOPS;
		}
	}

	dev->device = STRDUP(namestocopy[0].s_value);
	FREE(namestocopy[0].s_value);
	if (dev->device == NULL) {
		LOG(PIL_CRIT, "Out of memory for strdup in %s", __FUNCTION__);
		return S_OOPS;
	}

	if (strcspn(dev->device, WHITESPACE) != strlen(dev->device) ||
	    sscanf(dev->device, SYSTEM_CHASSIS_FMT, &i) != 1 || i < 0) {
		LOG(PIL_CRIT, "Invalid %s %s, must be of format %s"
		,	ST_ENTITYROOT, dev->device, SYSTEM_CHASSIS_FMT);
		return S_BADCONFIG;
	}
	
	dev->ohver = saHpiVersionGet();
	if (dev->ohver > SAHPI_INTERFACE_VERSION) {
		LOG(PIL_CRIT, "Installed OpenHPI interface (%x) greater than "
			"one used by plugin (%x), incompatibilites may exist"
		,	dev->ohver, SAHPI_INTERFACE_VERSION);
		return S_BADCONFIG;
	}

	ohrc = saHpiSessionOpen(SAHPI_UNSPECIFIED_DOMAIN_ID
				    , &dev->ohsession, NULL);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to open HPI session (%d)", ohrc);
		return S_BADCONFIG;
	}

	ohrc = saHpiDiscover(dev->ohsession);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to discover resources (%d)", ohrc);
		return S_BADCONFIG;
	}

	if (get_bladehpi_hostlist(dev) != S_OK) {
		LOG(PIL_CRIT, "Unable to obtain list of hosts in %s"
		,	__FUNCTION__);
		return S_BADCONFIG;
	}

	return S_OK;
}
示例#24
0
/* kauth file scope listener 
 * this allows to detect files written to the filesystem
 * arg2 contains a flag KAUTH_FILEOP_CLOSE which is set if a modified file is being closed
 * this way we don't need to trace every close(), only the ones writing to the filesystem
 */
static int
fileop_scope_listener(kauth_cred_t    credential,
                      void *          idata,
                      kauth_action_t  action,
                      uintptr_t       arg0,     /* vnode reference */
                      uintptr_t       arg1,     /* full path to file being closed */
                      uintptr_t       arg2,     /* flags */
                      uintptr_t       arg3)
{
    /* ignore all actions except FILE_CLOSE */
    if (action != KAUTH_FILEOP_CLOSE)
    {
        return KAUTH_RESULT_DEFER;
    }
    
    /* ignore operations with bad data */
    if (credential == NULL || (vnode_t)arg0 == NULL || (char*)arg1 == NULL)
    {
        ERROR_MSG("Arguments contain null pointers!");
        return KAUTH_RESULT_DEFER;
    }
    
    /* ignore closes on folders, character and block devices */
    switch ( vnode_vtype((vnode_t)arg0) )
    {
        case VDIR:
        case VCHR:
        case VBLK:
            return KAUTH_RESULT_DEFER;
        default:
            break;
    }
    
    /* we are only interested when a modified file is being closed */
    if ((int)arg2 != KAUTH_FILEOP_CLOSE_MODIFIED)
    {
        return KAUTH_RESULT_DEFER;
    }
    
    char *file_path = (char*)arg1;
    /* get information from current proc trying to write to the vnode */
    proc_t proc = current_proc();
    pid_t mypid = proc_pid(proc);
    char myprocname[MAXCOMLEN+1] = {0};
    proc_name(mypid, myprocname, sizeof(myprocname));

    /* retrieve the vnode attributes, we can get a lot of vnode information from here */
    struct vnode_attr vap = {0};
    vfs_context_t context = vfs_context_create(NULL);
    /* initialize the structure fields we are interested in
     * reference vn_stat_noauth() xnu/bsd/vfs/vfs_vnops.c
     */
    VATTR_INIT(&vap);
    VATTR_WANTED(&vap, va_mode);
    VATTR_WANTED(&vap, va_type);
    VATTR_WANTED(&vap, va_uid);
    VATTR_WANTED(&vap, va_gid);
    VATTR_WANTED(&vap, va_data_size);
    VATTR_WANTED(&vap, va_flags);
    int attr_ok = 1;
    if ( vnode_getattr((vnode_t)arg0, &vap, context) != 0 )
    {
        /* in case of error permissions and filesize will be bogus */
        ERROR_MSG("failed to vnode_getattr");
        attr_ok = 0;
    }
    /* release the context we created, else kab00m! */
    vfs_context_rele(context);
    
    int error = 0;
    /* make sure we :
     * - were able to read the attributes
     * - file size is at least uint32_t 
     * - path starts with /Users
     */
    if ( attr_ok == 1 &&
         vap.va_data_size >= sizeof(uint32_t) &&
         strprefix(file_path, "/Users/") )
    {
        uint32_t magic = 0;
        /* read target vnode */
        uio_t uio = NULL;
        /* read from offset 0 */
        uio = uio_create(1, 0, UIO_SYSSPACE, UIO_READ);
        if (uio == NULL)
        {
            ERROR_MSG("uio_create returned null!");
            return KAUTH_RESULT_DEFER;
        }
        /* we just want to read 4 bytes to match the header */
        if ( (error = uio_addiov(uio, CAST_USER_ADDR_T(&magic), sizeof(uint32_t))) )
        {
            ERROR_MSG("uio_addiov returned error %d!", error);
            return KAUTH_RESULT_DEFER;
        }
        if ( (error = VNOP_READ((vnode_t)arg0, uio, 0, NULL)) )
        {
            ERROR_MSG("VNOP_READ failed %d!", error);
            return KAUTH_RESULT_DEFER;
        }
        else if (uio_resid(uio))
        {
            ERROR_MSG("uio_resid!");
            return KAUTH_RESULT_DEFER;
        }
        
        /* verify if it's a Mach-O file */
        if (magic == MH_MAGIC || magic == MH_MAGIC_64 || magic == FAT_CIGAM)
        {
            char *token = NULL;
            char *string = NULL;
            char *tofree = NULL;
            int library = 0;
            int preferences = 0;
            
            tofree = string = STRDUP(file_path, M_TEMP);
            while ((token = strsep(&string, "/")) != NULL)
            {
                if (strcmp(token, "Library") == 0)
                {
                    library = 1;
                }
                else if (library == 1 && strcmp(token, "Preferences") == 0)
                {
                    preferences = 1;
                }
            }
            _FREE(tofree, M_TEMP);
            /* we got a match into /Users/username/Library/Preferences, warn user about it */
            if (library == 1 && preferences == 1)
            {
                DEBUG_MSG("Found Mach-O written to %s by %s.", file_path, myprocname);
                char alert_msg[1025] = {0};
                snprintf(alert_msg, sizeof(alert_msg), "Process \"%s\" wrote Mach-O binary %s.\n This could be Hacking Team's malware!", myprocname, file_path);
                alert_msg[sizeof(alert_msg)-1] = '\0';
                
                /* log to syslog */
                printf("[WARNING] Process \"%s\" wrote Mach-O binary %s.\n This could be Hacking Team's malware!", myprocname, file_path);
                /* deprecated but still usable to display the alert */
                KUNCUserNotificationDisplayNotice(10,		// Timeout
                                                  0,		// Flags - default is Stop alert level
                                                  NULL,     // iconpath
                                                  NULL,     // soundpath
                                                  NULL,     // localization path
                                                  "Security Alert", // alert header
                                                  alert_msg, // alert message
                                                  "OK");	// button title
            }
        }
    }
    /* don't deny access, we are just here to observe */
    return KAUTH_RESULT_DEFER;
}
示例#25
0
// Input:
//   meta_parameters *meta_sar--  SAR geometry to subset the DEM
//   const char *demImg       --  DEM data filename
//   const char *demMeta      --  DEM metadata filename
//   int pad                  --  number of lines to add at the top/bottom/left/right
//   double tolerance         --  how accurate the approximation mapping needs to be,
//                                in units of pixels
//   const char *output_name  --  output filename (basename)
//   int test_mode            --  adds checks for the accuracy of the mapping, and
//                                does some unit testing
// Output:
//   no output parameters, the output is the output_name files (.img and .meta)
// Return Value:
//   return TRUE on success, FALSE on fail
//
int make_gr_dem_ext(meta_parameters *meta_sar, const char *demImg, const char *demMeta,
                    int pad, double tolerance, const char *output_name, int test_mode)
{
  if (test_mode)
    test_interp();
  
  asfPrintStatus("Reading DEM...\n");
  meta_parameters *meta_dem = meta_read(demMeta);
  float *demData = read_dem(meta_dem, demImg);
  int dnl = meta_dem->general->line_count;
  int dns = meta_dem->general->sample_count;

  char *outImg = appendExt(output_name, ".img");
  char *output_name_tmp, *outImgTmp;

  // do not do DEM smoothing if the DEM pixel size is better or close to the
  // SAR image's pixel size.
  int do_averaging = TRUE;
  if (meta_dem->general->y_pixel_size - 10 < meta_sar->general->y_pixel_size)
    do_averaging = FALSE;
  asfPrintStatus("Averaging: %s (DEM %f, SAR: %f)\n", do_averaging ? "YES" : "NO",
                 meta_dem->general->y_pixel_size,
                 meta_sar->general->y_pixel_size);
  if (do_averaging) {
    output_name_tmp = appendStr(output_name, "_unsmoothed");
    outImgTmp = appendExt(output_name_tmp, ".img");
  }
  else {
    output_name_tmp = STRDUP(output_name);
    outImgTmp = STRDUP(outImg);
  }

  // add the padding if requested
  meta_parameters *meta_out = meta_copy(meta_sar);
  meta_out->general->line_count += pad*2;
  meta_out->general->sample_count += pad*2;
  meta_out->general->start_line -= pad;
  meta_out->general->start_sample -= pad;

  // fixing up the output metadata.  Note that we must keep the SAR section
  // intact since that specifies our geometry which is the whole point of
  // this exercise.
  strcpy(meta_out->general->basename, meta_dem->general->basename);
  strcpy(meta_out->general->sensor, MAGIC_UNSET_STRING);
  strcpy(meta_out->general->processor, MAGIC_UNSET_STRING);
  strcpy(meta_out->general->mode, MAGIC_UNSET_STRING);
  strcpy(meta_out->general->sensor_name, MAGIC_UNSET_STRING);
  meta_out->general->image_data_type = DEM;
  meta_out->general->radiometry = MAGIC_UNSET_INT;
  strcpy(meta_out->general->acquisition_date, meta_dem->general->acquisition_date);
  meta_out->general->orbit = MAGIC_UNSET_INT;
  meta_out->general->orbit_direction = MAGIC_UNSET_CHAR;
  meta_out->general->frame = MAGIC_UNSET_INT;
  meta_out->general->band_count = 1;
  strcpy(meta_out->general->bands, "DEM");

  int nl = meta_out->general->line_count;
  int ns = meta_out->general->sample_count;

  // finding the right grid size
  int size = find_grid_size(meta_sar, meta_dem, 512, .1*tolerance);

  asfPrintStatus("Creating ground range image...\n");

  float *buf = MALLOC(sizeof(float)*ns*size);
  FILE *fpOut = FOPEN(outImgTmp, "wb");

  // these are for tracking the quality of the bilinear interp
  // not used if test_mode is false
  int num_out_of_tol = 0;
  int num_checked = 0;
  int num_bad = 0;
  double max_err = 0;
  double avg_err = 0;

  int ii, jj;
  for (ii=0; ii<nl; ii += size) {
    int line_lo = ii;
    int line_hi = ii + size;

    for (jj=0; jj<ns; jj += size) {
      double lines[4], samps[4];
      
      int samp_lo = jj;
      int samp_hi = jj + size;

      get_interp_params(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi,
                        lines, samps);

      int iii, jjj;
      for (iii=0; iii<size; ++iii) {
        for (jjj=0; jjj<size && jj+jjj<ns; ++jjj) {
          int index = iii*ns + jj + jjj;
          assert(index < ns*size);

          double line_out, samp_out;
          xy_interp(ii+iii, jj+jjj, line_lo, line_hi, samp_lo, samp_hi, lines, samps,
                    &line_out, &samp_out);

          // random checking of the quality of our interpolations
          if (test_mode && iii%11==0 && jjj%13==0) {
            double real_line, real_samp; 
            sar_to_dem(meta_sar, meta_dem, ii+iii, jj+jjj, &real_line, &real_samp);

            double err = hypot(real_line - line_out, real_samp - samp_out);

            avg_err += err;
            if (err > max_err)
              max_err = err;

            if (err > tolerance) {
              asfPrintStatus("Out of tolerance at %d,%d: (%f,%f) vs (%f,%f) -> %f\n",
                             ii+iii, jj+jjj, line_out, samp_out, real_line, real_samp,
                             err);
              ++num_out_of_tol;
            }
            if (err > .5) {
              asfPrintStatus("Error is larger than 1 pixel!\n");
              ++num_bad;
            }
            ++num_checked;
          }
          buf[index] = interp_demData(demData, dnl, dns, line_out, samp_out);
        }
      }
    }

    put_float_lines(fpOut, meta_out, ii, size, buf);
    asfPrintStatus("Completed %.1f%%  \r", 100.*ii/(double)nl);
  }
  asfPrintStatus("Completed 100%%   \n");

  if (test_mode) {
    asfPrintStatus("Tolerance was %f\n", tolerance);
    asfPrintStatus("%d/%d checked pixels had error exceeding tolerance. (%.1f%%)\n",
                   num_out_of_tol, num_checked, 100.*num_out_of_tol/(double)num_checked);
    asfPrintStatus("%d/%d checked pixels had error larger than half a pixel. (%.1f%%)\n",
                   num_bad, num_checked, 100.*num_bad/(double)num_checked);
    asfPrintStatus("Maximum error: %f pixels\n", max_err);
    avg_err /= (double)num_checked;
    asfPrintStatus("Average error: %f pixels\n", avg_err);
  }

  FCLOSE(fpOut);
  meta_write(meta_out, outImgTmp);

  meta_free(meta_out);
  meta_free(meta_dem);

  FREE(buf);
  FREE(demData);

  // now apply 3x3 filter
  if (do_averaging) {
    asfPrintStatus("Smoothing with 3x3 kernel ...\n");
    smooth(outImgTmp, outImg, 3, EDGE_TRUNCATE);
  }

  FREE(outImg);
  FREE(outImgTmp);
  FREE(output_name_tmp);

  return FALSE;
}
示例#26
0
文件: bios.cpp 项目: Conti/FakeSMC
static char *bios_version_to_str(int version)
{
	char res[12];
	snprintf(res,12, "%02x.%02x.%02x.%02x%c", (version>>24) & 0xff, (version>>16) & 0xff, (version>>8) & 0xff, version&0xff, '\0');
	return (char*)STRDUP(res,12);
}
示例#27
0
文件: dload.c 项目: moben/pacman
/** Fetch a remote pkg. */
char SYMEXPORT *alpm_fetch_pkgurl(alpm_handle_t *handle, const char *url)
{
	char *filepath;
	const char *cachedir;
	char *final_file = NULL;
	struct dload_payload payload;
	int ret;

	CHECK_HANDLE(handle, return NULL);
	ASSERT(url, RET_ERR(handle, ALPM_ERR_WRONG_ARGS, NULL));

	/* find a valid cache dir to download to */
	cachedir = _alpm_filecache_setup(handle);

	memset(&payload, 0, sizeof(struct dload_payload));
	payload.handle = handle;
	STRDUP(payload.fileurl, url, RET_ERR(handle, ALPM_ERR_MEMORY, NULL));
	payload.allow_resume = 1;

	/* download the file */
	ret = _alpm_download(&payload, cachedir, &final_file);
	_alpm_dload_payload_reset(&payload);
	if(ret == -1) {
		_alpm_log(handle, ALPM_LOG_WARNING, _("failed to download %s\n"), url);
		free(final_file);
		return NULL;
	}
	_alpm_log(handle, ALPM_LOG_DEBUG, "successfully downloaded %s\n", url);

	/* attempt to download the signature */
	if(ret == 0 && (handle->siglevel & ALPM_SIG_PACKAGE)) {
		char *sig_final_file = NULL;
		size_t len;

		len = strlen(url) + 5;
		MALLOC(payload.fileurl, len, RET_ERR(handle, ALPM_ERR_MEMORY, NULL));
		snprintf(payload.fileurl, len, "%s.sig", url);
		payload.handle = handle;
		payload.force = 1;
		payload.errors_ok = (handle->siglevel & ALPM_SIG_PACKAGE_OPTIONAL);

		ret = _alpm_download(&payload, cachedir, &sig_final_file);
		if(ret == -1 && !payload.errors_ok) {
			_alpm_log(handle, ALPM_LOG_WARNING,
					_("failed to download %s\n"), payload.fileurl);
			/* Warn now, but don't return NULL. We will fail later during package
			 * load time. */
		} else if(ret == 0) {
			_alpm_log(handle, ALPM_LOG_DEBUG,
					"successfully downloaded %s\n", payload.fileurl);
		}
		FREE(sig_final_file);
		_alpm_dload_payload_reset(&payload);
	}

	/* we should be able to find the file the second time around */
	filepath = _alpm_filecache_find(handle, final_file);
	free(final_file);

	return filepath;
}
示例#28
0
static void rgps_grid2cell(char *line, rgps_grid_t *grid, int nGrids, 
  rgps_cell_t *cell, int nCells, dbf_header_t *dbf, FILE *fpOut)
{
  char **col;
  int ii, nCols, nCoords=0, cell_id=0, obs_year;
  double obs_time, x_disp, y_disp;

  // Extract information from line
  split_into_array(line, ',', &nCols, &col);
  for (ii=0; ii<nCols; ii++) {
    if (dbf[ii].format == CSV_STRING)
      dbf[ii].sValue = STRDUP(col[ii]);
    else if (dbf[ii].format == CSV_DOUBLE)
      dbf[ii].fValue = atof(col[ii]);
    else if (dbf[ii].format == CSV_INTEGER)
      dbf[ii].nValue = atoi(col[ii]);
    if (strcmp_case(dbf[ii].shape, "CELL_ID") == 0)
      cell_id = dbf[ii].nValue;
    else if (strcmp_case(dbf[ii].shape, "OBS_YEAR") == 0)
      obs_year = dbf[ii].nValue;
    else if (strcmp_case(dbf[ii].shape, "OBS_TIME") == 0) {
      obs_time = dbf[ii].fValue;
      if (obs_year > grid[0].obs_year)
        obs_time += date_getDaysInYear(grid[0].obs_year);
    }
    else if (strcmp_case(dbf[ii].shape, "X_DISP") == 0)
      x_disp = dbf[ii].fValue;
    else if (strcmp_case(dbf[ii].shape, "Y_DISP") == 0)
      y_disp = dbf[ii].fValue;
  }
  free_char_array(&col, nCols);

  // Extract information from connectivity table
  int *grid_id = (int *) MALLOC(sizeof(int)*50);
  double *grid_order = (double *) MALLOC(sizeof(double)*50);
  size_t *p = (size_t *) MALLOC(sizeof(size_t)*50);
  for (ii=0; ii<nCells; ii++) {
    if (cell_id == cell[ii].cell_id) {
      grid_id[nCoords] = cell[ii].grid_id;
      grid_order[nCoords] = cell[ii].cell_id + (double) cell[ii].order / 100;
      nCoords++;
    }
  }
  gsl_sort_index(p, grid_order, 1, nCoords);
  double disp_mag = sqrt(x_disp*x_disp + y_disp*y_disp);

  // Extract grid information from motion product
  int kk, index;
  double diff, grid_time, birth_time, death_time;
  char image_id[30];
  char *tmp = (char *) MALLOC(sizeof(char)*25);
  char *coordStr = (char *) MALLOC(sizeof(char)*50*nCoords);
  strcpy(coordStr, "");
  for (kk=0; kk<nCoords; kk++) {
    index = -1;
    for (ii=0; ii<nGrids; ii++) {
      grid_time = grid[ii].obs_time;
      if (grid[ii].obs_year > grid[0].obs_year)
        grid_time += date_getDaysInYear(grid[0].obs_year);
      diff = fabs(grid_time - obs_time);
      if ((grid_id[p[kk]] == grid[ii].gpid) && (diff < 0.01)) {
        birth_time = grid[ii].birth_time;
        if (grid[ii].birth_year > grid[0].obs_year)
          birth_time += date_getDaysInYear(grid[0].obs_year);
        index = ii;
      }
    }
    if (index > 0 && birth_time <= grid_time) {
      sprintf(tmp, ",%.4f,%.4f", grid[index].x, grid[index].y);
      strcat(coordStr, tmp);
      strcpy(image_id, grid[index].image_id);
    }
  }

  // Check cell death time    
  int n, cell_death_year;
  double cell_death_time;
  split_into_array(line, ',', &n, &col);
  for (ii=0; ii<nCells; ii++) {
    if (cell[ii].cell_id == atoi(col[0])) {
      cell_death_time = death_time = cell[ii].death_time;
      cell_death_year = cell[ii].death_year;
      if (cell[ii].death_year > cell[0].birth_year)
        death_time += date_getDaysInYear(cell[0].birth_year);
      if (cell[ii].death_year == -1)
        death_time = -1;
    }
  }
  if (death_time < 0 || obs_time < (death_time + 0.01)) {
    fprintf(fpOut, "%.6f,%s,%s,%s", obs_time, col[0], col[1], col[2]);
    fprintf(fpOut, ",%s,%d,%.6f", col[3], cell_death_year, cell_death_time);
    for (kk=4; kk<n; kk++)
      fprintf(fpOut, ",%s", col[kk]);
    fprintf(fpOut, ",%s,%.6f%s\n", image_id, disp_mag, coordStr);
  }
  free_char_array(&col, n);

  // Clean up
  FREE(grid_id);
  FREE(grid_order);
  FREE(p);
  FREE(tmp);
  FREE(coordStr);

  return;
}
示例#29
0
文件: IconObj.C 项目: juddy/edcde
void IconObj::StateIconFile(char *stateIconName)
{
   delete _stateIconName;
   _stateIconName = STRDUP(stateIconName);
   SetStateIconFile(IconView());
}
示例#30
0
void gen_EXPRESSION ( node_t *root, int scopedepth )
{
	/*
	 * Expressions:
	 * Handle any nested expressions first, then deal with the
	 * top of the stack according to the kind of expression
	 * (single variables/integers handled in separate switch/cases)
	 */
	tracePrint ( "Starting EXPRESSION of type %s\n", (char*) root->expression_type.text);

	int size;
	char size_string[100];
	switch(root->expression_type.index){

		case FUNC_CALL_E:
			ge(root,scopedepth);
			break;

			/* Add cases for other expressions here */
		case UMINUS_E:
			// Generate the child
			root->children[0]->generate(root->children[0], scopedepth);
			// Fetching the operand from stack
			instruction_add(POP, r0, NULL, 0, 0);
			instruction_add(MOVE, r1, "#-1", 0, 0);
			instruction_add3(MUL, r0, r0, r1);
			instruction_add(PUSH, r0, NULL, 0, 0);
			break;

		case METH_CALL_E:
			// Caller saves registers on stack.
			// Assuming that there might be something in registers r1-r3
			// Assuming that r0 are used to handle different inputs and outputs, including function result.
			instruction_add(PUSH, r3, NULL, 0,0);
			instruction_add(PUSH, r2, NULL, 0,0);
			instruction_add(PUSH, r1, NULL, 0,0);
		
			// Caller pushes parameters on stack.
			// Must find number of parameters, and push each value to stack
			// When parameters, second child-node is a variable-list instead of NULL. Children of that node contain the parameters values
			int i;
			if (root->children[2]!=NULL){
			
				for (i=0; i<root->children[2]->n_children; i++){
					// Load parameter number i into register r0 by using the generate-method for that node (usually variable or constant)
					// r0 will automatically be pushed by either gen_CONSTANT or gen_VARIABLE
					root->children[2]->children[i]->generate(root->children[2]->children[i], scopedepth);
				
				}
			}
			
			// IMPORTANT: Difference from func_call is also that the object (value is address on heap) is pushed as final argument
			// Loading object as variable into r0 and pushing r0 in stack, by generate
			root->children[0]->generate(root->children[0], scopedepth);
			
			//Performing method call from correct class:
			//function_symbol_t* entry = root->children[1]->function_entry;
			symbol_t* p1 = root->children[0]->entry;
			data_type_t p2 = p1->type;
			int len2 = strlen(p2.class_name);
			
			char *temp2 = (char*) malloc(sizeof(char) * (len2 + 3));
			temp2[0] = 0;
			//temp3 = test.type->class_name;
			//temp3= root->children[0]->entry.type->class_name;
			strcat(temp2, p2.class_name);
			strcat(temp2, "_");
			strcat(temp2, root->children[1]->label);

			instruction_add(CALL, STRDUP(temp2), NULL, 0, 0 );
			free(temp2);
			
			// Poping THIS as argument from the stack
			instruction_add(POP, "r8", NULL, 0,0); 
			// Callee jumps back to caller, and pops return address. Caller removes parameters, restores registers, uses result.
			// Using r0 for result storing from the function
			if (root->children[2]!=NULL){
				for (i=0; i<root->children[2]->n_children; i++){
					// Poping parameters from stack, by loading into r8, that is otherwise never used. This includes the objects heap parameter
					instruction_add(POP, "r8", NULL, 0,0);
				}
			}
			
			// Restoring original registers
			instruction_add(POP, r1, NULL, 0,0);
			instruction_add(POP, r2, NULL, 0,0);
			instruction_add(POP, r3, NULL, 0,0);
		
			// NOTE: Have to hack in order to make sure printing works when including functions straight in print statement
			// by setting data_type
			root->data_type = root->function_entry->return_type;
			if (root->data_type.base_type!=VOID_TYPE){
				// Adding result in r0 to stack as return result
				instruction_add(PUSH, r0, NULL, 0,0);
			}
			
			
			break;

			// Binary expressions:
		case ADD_E: case SUB_E: case MUL_E: case DIV_E: case AND_E: case OR_E:
		case EQUAL_E: case NEQUAL_E: case LEQUAL_E: case GEQUAL_E: case LESS_E: case GREATER_E:

			// The two operands are in the two child-nodes. They must be generated.
			root->children[0]->generate(root->children[0], scopedepth);
			root->children[1]->generate(root->children[1], scopedepth);
			// Fetching the operands from stack
			instruction_add(POP, r2, NULL, 0,0);
			instruction_add(POP, r1, NULL, 0,0);
			// Calculating, and pushing to stack

      // Now the current operation itself:
			switch(root->expression_type.index){

				// Arithmetic and logical expressions:
				case ADD_E: case OR_E:
					instruction_add3(ADD, r0, r1, r2);
					break;

				case SUB_E:
					instruction_add3(SUB, r0, r1, r2);
					break;

				case MUL_E: case AND_E:
					instruction_add3(MUL, r0, r1, r2);
					break;

				case DIV_E:
					instruction_add3(DIV, r0, r1, r2); 
					break;

					// Comparison expressions:

				case GREATER_E:
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVGT, r0, "#1", 0,0);
					break;

				case LESS_E: 
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVLT, r0, "#1", 0,0);
					break;

				case EQUAL_E:
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVEQ, r0, "#1", 0,0);
					break;

				case NEQUAL_E:
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVNE, r0, "#1", 0,0);
					break;

				case GEQUAL_E:
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVGE, r0, "#1", 0,0); 
					break;

				case LEQUAL_E:
					instruction_add(MOVE, r0, "#0", 0,0);
					instruction_add(CMP, r1, r2, 0,0);
					instruction_add(MOVLE, r0, "#1", 0,0);
					break;

			}

			// Pushing to stack:
			instruction_add(PUSH, r0, NULL, 0, 0);

			break;

		case CLASS_FIELD_E:
			// Fetching address value from child 1, pushing to top of stack:
			root->children[0]->generate(root->children[0], scopedepth);
			// Now poping from stack into r0:
			instruction_add(POP, r1, NULL, 0,0);
			// Now loading from heap, based on address from child 1 and offset from child 2:
			instruction_add(LOAD, r0, r1, 0, root->children[1]->entry->stack_offset);
			// Pushing class field access result to stac:
			instruction_add(PUSH, r0, NULL, 0,0);


			break;

		case THIS_E: //TODO: Double check that this works, double check that the value at class position in stack indeed is the address, or if it needs to be fetched using node field
			instruction_add(LOAD, r0, fp, 0, 8);
			instruction_add(PUSH, r0, NULL, 0, 0);
			break;

		case NEW_E:
			size = root->children[0]->class_entry->size;
			snprintf(size_string, 100, "#%d", size); //Max 99 digits

			instruction_add(MOVE, r0, STRDUP(size_string), 0, 0);
			instruction_add(PUSH, r0, NULL, 0, 0); //Pushing constant to stack, in case of print statement

			instruction_add(CALL, STRDUP("malloc"), NULL, 0, 0);
			instruction_add(POP, r1, NULL, 0, 0);
			//instruction_add(STORE, r0, sp, 0, 8);
			instruction_add(PUSH, r0, NULL, 0, 0);
			break;
	}

	tracePrint ( "Ending EXPRESSION of type %s\n", (char*) root->expression_type.text);
}