Exemplo n.º 1
0
static void DoExportCB(Widget w, XtPointer client_data, XtPointer call_data)
{
    SelectPlotCB(w, client_data, call_data);

    PlotWindowInfo *plot = (PlotWindowInfo *)client_data;
    string target = get_file(w, client_data, call_data);
    if (target.empty())
	return;

    const StringArray& titles  = plot->plotter->data_titles();
    const StringArray& sources = plot->plotter->data_files();

    string source = "";
    string title  = "";
    for (int i = 0; source.empty() && i < sources.size(); i++)
    {
	if (!sources[i].empty())
	{
	    source = sources[i];
	    title  = titles[i];
	}
    }
    
    if (source.empty())
	return;			// This should not happen

    if (access(target.chars(), W_OK) == 0 && is_regular_file(target))
    {
	// File exists - request confirmation
	static Widget confirm_overwrite_dialog = 0;
	if (confirm_overwrite_dialog != 0)
	    DestroyWhenIdle(confirm_overwrite_dialog);

	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNdialogStyle, 
		 XmDIALOG_FULL_APPLICATION_MODAL); arg++;
	confirm_overwrite_dialog = 
	    verify(XmCreateQuestionDialog(plot->shell,
					  XMST("confirm_overwrite_dialog"), 
					  args, arg));
	Delay::register_shell(confirm_overwrite_dialog);

	bool yes = false;
	bool no  = false;
	   
	XtAddCallback(confirm_overwrite_dialog,
		      XmNokCallback, SetCB, XtPointer(&yes));
	XtAddCallback(confirm_overwrite_dialog,
		      XmNcancelCallback, SetCB, XtPointer(&no));
	XtAddCallback(confirm_overwrite_dialog, 
		      XmNhelpCallback, ImmediateHelpCB, 0);

	MString question = rm("Overwrite existing file " 
			      + quote(target) + "?");
	XtVaSetValues (confirm_overwrite_dialog, XmNmessageString, 
		       question.xmstring(), XtPointer(0));
	manage_and_raise(confirm_overwrite_dialog);

	XtAppContext app_context = XtWidgetToApplicationContext(plot->shell);
	while (!yes && !no)
	    XtAppProcessEvent(app_context, XtIMAll);

	if (no)
	    return;
    }

    StatusDelay delay("Saving " + title + " data to " + quote(target));

    // Copy SOURCE to TARGET
    std::ifstream is(source.chars());
    std::ofstream os(target.chars());

    if (os.bad())
    {
	FILE *fp = fopen(target.chars(), "w");
	post_error(string("Cannot open ") 
		   + quote(target) + ": " + strerror(errno), 
		   "export_failed_error", plot->shell);
	if (fp)
	    fclose(fp);
	delay.outcome = strerror(errno);
	return;
    }

    int c;
    while ((c = is.get()) != EOF)
	os.put((unsigned char) c);

    XtUnmanageChild(plot->export_dialog);
}
Exemplo n.º 2
0
globle void ReturnDefrule(
  void *vWaste)
  {
#if (MAC_MPW || MAC_MCW) && (RUN_TIME || BLOAD_ONLY)
#pragma unused(vWaste)
#endif

#if (! RUN_TIME) && (! BLOAD_ONLY)
   struct defrule *waste = (struct defrule *) vWaste;
   int first = TRUE;
   struct defrule *nextPtr;

   if (waste == NULL) return;

   /*======================================*/
   /* If a rule is redefined, then we want */
   /* to save its breakpoint status.       */
   /*======================================*/

#if DEBUGGING_FUNCTIONS
   DeletedRuleDebugFlags = 0;
   if (waste->afterBreakpoint) BitwiseSet(DeletedRuleDebugFlags,0);
   if (waste->watchActivation) BitwiseSet(DeletedRuleDebugFlags,1);
   if (waste->watchFiring) BitwiseSet(DeletedRuleDebugFlags,2);
#endif

   /*================================*/
   /* Clear the agenda of all the    */
   /* activations added by the rule. */
   /*================================*/

   ClearRuleFromAgenda(waste);

   /*======================*/
   /* Get rid of the rule. */
   /*======================*/

   while (waste != NULL)
     {
      /*================================================*/
      /* Remove the rule's joins from the join network. */
      /*================================================*/

      DetachJoins(waste);

      /*=============================================*/
      /* If this is the first disjunct, get rid of   */
      /* the dynamic salience and pretty print form. */
      /*=============================================*/

      if (first)
        {
#if DYNAMIC_SALIENCE
         if (waste->dynamicSalience != NULL)
          {
           ExpressionDeinstall(waste->dynamicSalience);
           ReturnPackedExpression(waste->dynamicSalience);
           waste->dynamicSalience = NULL;
          }
#endif
#if CERTAINTY_FACTORS     /* changed 03-12-96 */
         if (waste->dynamicCF != NULL)
          {
           ExpressionDeinstall(waste->dynamicCF);
           ReturnPackedExpression(waste->dynamicCF);
           waste->dynamicCF = NULL;
          }
#endif
         if (waste->header.ppForm != NULL)
           {
            rm(waste->header.ppForm,(int) strlen(waste->header.ppForm) + 1);
            waste->header.ppForm = NULL;
           }

         first = FALSE;
        }

      /*===========================*/
      /* Get rid of any user data. */
      /*===========================*/
      
      if (waste->header.usrData != NULL)
        { ClearUserDataList(waste->header.usrData); }
        
      /*===========================================*/
      /* Decrement the count for the defrule name. */
      /*===========================================*/

      DecrementSymbolCount(waste->header.name);

      /*========================================*/
      /* Get rid of the the rule's RHS actions. */
      /*========================================*/

      if (waste->actions != NULL)
        {
         ExpressionDeinstall(waste->actions);
         ReturnPackedExpression(waste->actions);
        }

      /*===============================*/
      /* Move on to the next disjunct. */
      /*===============================*/

      nextPtr = waste->disjunct;
#if FUZZY_DEFTEMPLATES 
      if (waste != ExecutingRule)
        {
         if (waste->numberOfFuzzySlots > 0)
         rm(waste->pattern_fv_arrayPtr, sizeof(struct fzSlotLocator) * waste->numberOfFuzzySlots);
        }
#endif
      rtn_struct(defrule,waste);
      waste = nextPtr;
     }

   /*==========================*/
   /* Free up partial matches. */
   /*==========================*/

   if (ExecutingRule == NULL) FlushGarbagePartialMatches();
#endif
  }
jvmtiError VM_RedefineClasses::load_new_class_versions(TRAPS) {
  // For consistency allocate memory using os::malloc wrapper.
  _k_h_new = (instanceKlassHandle *) os::malloc(sizeof(instanceKlassHandle) * _class_count);

  ResourceMark rm(THREAD);

  JvmtiThreadState *state = JavaThread::current()->jvmti_thread_state();
  assert(state != NULL, "JvmtiThreadState not initialized"); 
  for (int i = 0; i < _class_count; i++) {
    oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
    klassOop k_oop = java_lang_Class::as_klassOop(mirror);
    instanceKlassHandle k_h = instanceKlassHandle(THREAD, k_oop);
    symbolHandle k_name = symbolHandle(THREAD, k_h->name());

    ClassFileStream st((u1*) _class_defs[i].class_bytes,
      _class_defs[i].class_byte_count, (char *)"__VM_RedefineClasses__");

    // Parse the stream.
    Handle k_loader_h(THREAD, k_h->class_loader());
    Handle protection_domain;
    // Set redefined class handle in JvmtiThreadState class.
    // This redefined class is sent to agent event handler for class file
    // load hook event.
    state->set_class_being_redefined(&k_h);

    klassOop k = SystemDictionary::parse_stream(k_name, 
                                                k_loader_h, 
                                                protection_domain,
                                                &st,
                                                THREAD);
    // Clear class_being_redefined just to be sure.
    state->set_class_being_redefined(NULL);
                                     
    instanceKlassHandle k_h_new (THREAD, k);

    if (HAS_PENDING_EXCEPTION) {
      symbolOop ex_name = PENDING_EXCEPTION->klass()->klass_part()->name();
      CLEAR_PENDING_EXCEPTION;

      if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {
        return JVMTI_ERROR_UNSUPPORTED_VERSION;
      } else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {
        return JVMTI_ERROR_INVALID_CLASS_FORMAT;
      } else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {
        return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
      } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
        // The message will be "XXX (wrong name: YYY)"
        return JVMTI_ERROR_NAMES_DONT_MATCH;
      } else {  // Just in case more exceptions can be thrown..
        return JVMTI_ERROR_FAILS_VERIFICATION;
      }
    }

    // All its super classes should be linked to 
    // initialize the vtable.
    instanceKlassHandle super(THREAD, k_h_new->super());
    if (super.not_null() && !super->is_linked()) {
      super->link_class(THREAD);
      if (HAS_PENDING_EXCEPTION) {
        CLEAR_PENDING_EXCEPTION;
        return JVMTI_ERROR_INTERNAL;
      }
    }
    
    // See instanceKlass::link_klass_impl()
    { ObjectLocker ol(k_h_new, THREAD);
      Verifier::verify_byte_codes(k_h_new, THREAD);

      if (HAS_PENDING_EXCEPTION) {
        CLEAR_PENDING_EXCEPTION;
        return JVMTI_ERROR_FAILS_VERIFICATION;
      }
      Rewriter::rewrite(k_h_new, THREAD);
      if (HAS_PENDING_EXCEPTION) {
        CLEAR_PENDING_EXCEPTION;
        return JVMTI_ERROR_INTERNAL;
      }
    }

    jvmtiError res = compare_class_versions(k_h, k_h_new);
    if (res != JVMTI_ERROR_NONE) return res;
  
    _k_h_new[i] = k_h_new;
  }
  
  return JVMTI_ERROR_NONE;
}
Exemplo n.º 4
0
int isCommand( struct directory* cluster, unsigned char* buffer, 
		unsigned int FDS, unsigned int SPC, unsigned int RSC,
		unsigned int BPS, char* input, char* args )
{

	/* Make a copy of args; iterate through it with strtok; count arguments */
	int argumentCount = 0;
	char * tempArgs = malloc( 1 + strlen ( args ));
    strcpy( tempArgs, args );
    for( tempArgs = strtok( tempArgs, " " ); tempArgs;
        tempArgs = strtok( NULL, " " )) {
			argumentCount++;   
    }
//			printf( "Number of args: %d\n", argumentCount );	

	int dir_result = isDir( cluster, args );
	int file_result = isFile( cluster, args );
	int r,w;

	/* OPEN */
	if( strcmp( input, "open" ) == 0 ){

		// check number of args:
		if( checkArgumentCount( argumentCount, OPEN_ARG_NUM ))
			return 1;

		char * mode = calloc( sizeof( char ), 2 );
		char * ptr  = calloc( sizeof( char ), 64 );	
		ptr = strtok( args, " " );
		mode = strtok( NULL, " " );

		open( args, mode );
	
		return 1;

	}

	/* CLOSE */
	else if(strcmp(input,"close") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, CLOSE_ARG_NUM ))
			return 1;

		close(args);
		return 1;
	}
	/* CREATE */
	else if(strcmp(input,"create") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, CREATE_ARG_NUM ))
			return 1;
		
		if(fileExists(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS) == 1){
			printf("error: File already exists\n");
			return 1;
		}	
		r = checkIfClusterIsFull(buffer,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
		if(r == 1){
			//cluster is full, allocate new space
			//get space for new link in cluster chain	
			r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			//extend the cluster chain using the new link
			extendClusterChain(buffer,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);		
			//get space for the new file being created	
			r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			//create new file
			r = create(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);		
			if(r > 0){
				FILE *fileptr;
				fileptr = fopen("fat32.img", "wb");
				fwrite(buffer,1,67108864,fileptr); 
				fclose(fileptr);
			}else if(r == 0){
				printf("error: File already exists\n");
			}else if(r < 0){
				printf("error: out of useable space!\n");
			}
		}else{
			//cluster has room, put new file in that space
			r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			r = create(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
			if(r > 0){
				FILE *fileptr;
				fileptr = fopen("fat32.img", "wb");
				fwrite(buffer,1,67108864,fileptr); 
				fclose(fileptr);
			}else if(r == 0){
				printf("error: File already exists\n");
			}else if(r < 0){
				printf("error: out of useable space!\n");
			}
		}
		return 1;

	}
	/* RMDIR */
	else if(strcmp(input,"rmdir") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, RMDIR_ARG_NUM ))
			return 1;
	
		r = rmdir(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
		if(r == 1){
			FILE *fileptr;
			fileptr = fopen("fat32.img", "wb");
			fwrite(buffer,1,67108864,fileptr); 
			fclose(fileptr);
		}else if(r == 0){
			printf("error: does not exist\n");
		}else if(r == -1){
			printf("error: not a directory\n"); 
		}else{
			printf("error: directory not empty\n");
		}

		return 1;
	}
	/* RM */
	else if(strcmp(input,"rm") == 0){
		// check number of args:
		if( checkArgumentCount( argumentCount, RM_ARG_NUM ))
			return 1;

		r = rm(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
		if(r == 1){
			close_without_check(args);
			FILE *fileptr;
			fileptr = fopen("fat32.img", "wb");
			fwrite(buffer,1,67108864,fileptr); 
			fclose(fileptr);
		}else if(r == 0){
			printf("error: does not exist\n");
		}else{
			printf("error: not a file\n"); 
		}
		return 1;
	}
	/* SIZE */
	else if(strcmp(input,"size") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, SIZE_ARG_NUM ))
			return 1;
		

			size(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);


		return 1;
	}
	/* CD */
	else if(strcmp(input,"cd") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, CD_ARG_NUM ))
			return 1;

		if(dir_result == -1){ //current dir
			//dont change currentClusterNumber	
		}else if(dir_result == -2){
			currentClusterNumber(SET,
				cd_back(buffer,
					currentClusterNumber(GET,0),
					FDS,SPC,RSC,BPS)	
			);
			return 3;		
		}else{
			r = cd(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
			if(r > 0){
				currentClusterNumber(SET,r);
				return 2;
			}else{
				printf("%s: Invalid directory\n",args);
			}
		}
		return 1;
	}
	/* LS */
	else if(strcmp(input,"ls") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, LS_ARG_NUM ))
			return 1;


		if(dir_result > 0){
			ls(buffer,args,dir_result,FDS,SPC, RSC, BPS);
		}
		else if(dir_result < 0){
			ls(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
		}
		else 
			printf("%s: Invalid directory\n",args);
		return 1;
	}
	/* MKDIR */
	else if(strcmp(input,"mkdir") == 0){
			int datacnum, dotcnum;
		// check number of args:
		if( checkArgumentCount( argumentCount, MKDIR_ARG_NUM ))
			return 1;
		
		if(fileExists(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS) == 1){
			printf("error: directory already exists\n");
			return 1;
		}	
		r = checkIfClusterIsFull(buffer,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
		if(r == 1){
			//cluster is full, allocate new space
			//get space for new link in cluster chain	
			dotcnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			//extend the cluster chain using the new link
			extendClusterChain(buffer,dotcnum,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);		
			//get space for the new dir being created	
			datacnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			//create new directory
			r = mkdir(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);	
			if(r > 0){
				makeDotDirectories(buffer,(datacnum-2)*SPC+FDS,dotcnum,currentClusterNumber(GET,0));
				FILE *fileptr;
				fileptr = fopen("fat32.img", "wb");
				fwrite(buffer,1,67108864,fileptr); 
				fclose(fileptr);
			}else if(r == 0){
				printf("error: directory already exists\n");
			}else if(r < 0){
				printf("error: out of useable space!\n");
			}
		}else{
			//cluster has room, put new file in that space
			datacnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS);
			r = mkdir(buffer,args,datacnum,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);		
			if(r > 0){
				makeDotDirectories(buffer,(datacnum-2)*SPC+FDS,datacnum,currentClusterNumber(GET,0));
				FILE *fileptr;
				fileptr = fopen("fat32.img", "wb");
				fwrite(buffer,1,67108864,fileptr); 
				fclose(fileptr);
			}else if(r == 0){
				printf("error: directory already exists\n");
			}else if(r < 0){
				printf("error: out of useable space!\n");
			}
		}
	
		return 1;
	}
	/* READ */
	else if(strcmp(input,"read") == 0){

		// check number of args:
		if( checkArgumentCount( argumentCount, READ_ARG_NUM ))
			return 1;

		char* file = calloc(sizeof(char),64);
		long int start, num_bytes;
		char *pEnd;
		char *temp1 = calloc(sizeof(char),8);
		char *temp2 = calloc(sizeof(char),8);
		file = strtok(args," ");
		r = fileModeIsReadable(file);
		if(r == 1){
			temp1 = strtok(NULL," ");
			start = strtol(temp1,&pEnd,10);
			temp2 = strtok(NULL," ");
			num_bytes = strtol(temp2,&pEnd,10);
			if(start >= SIZE_OF_SECTOR){
				printf( "Error: attempt to read beyond EoF\n" );	
			}else{
				read( buffer, file, start, num_bytes, currentClusterNumber( GET, 0 ), FDS, SPC, RSC, BPS );
			}
		}else{
			printf( "Error: file is not open for writing!\n" );
		}
		return 1;
	}
	/* WRITE */
	else if( strcmp( input, "write" ) == 0 ){

		// check number of args:
		if( checkArgumentCount( argumentCount, WRITE_ARG_NUM ))
			return 1;
			
		char* file = calloc(sizeof(char),64);
		long int start, num_bytes;
		char *pEnd;
		char *temp1 = calloc(sizeof(char),8);
		char *temp2 = calloc(sizeof(char),8);
		char *temp3 = calloc(sizeof(char),8);
		file = strtok(args," ");
		w = fileModeIsWriteable(file);
		if(w == 1){
			temp1 = strtok(NULL," ");
			start = strtol(temp1,&pEnd,10);
			temp2 = strtok(NULL," ");
			num_bytes = strtol(temp2,&pEnd,10);
			temp3 = strtok(NULL,"\n");
			if(strlen(temp3) != num_bytes){
				printf("Error: Bytes requested does not match string size!\n");
				return 1;
			}
			if(start >= SIZE_OF_SECTOR){
				printf("Error: attempt to read beyond EoF\n");	
			}else{
				FILE *fileptr;
				long filelen;
				write(buffer,file,start,num_bytes,temp3,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS);
				//find the file length
				fileptr = fopen("fat32.img", "rb");
				fseek(fileptr, 0, SEEK_END);
				filelen = ftell(fileptr);
				fclose(fileptr);
				//write to file
				fileptr = fopen("fat32.img", "wb");
				fwrite(buffer,1,filelen,fileptr); 
				fclose(fileptr);
			}
		}else{
			printf("Error: file is not open for writing!\n");
		}

		return 1;
	}
	/* EXIT */
	else if( strcmp( input,"exit" ) == 0 ){
		printf( "Goodbye!\n" );
		exit( 1 );
	}else return 0;
}
Exemplo n.º 5
0
jvmtiError
JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
                              jint start_depth, jint max_count,
                              jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
#ifdef ASSERT
  uint32_t debug_bits = 0;
#endif
  assert((SafepointSynchronize::is_at_safepoint() ||
          is_thread_fully_suspended(java_thread, false, &debug_bits)),
         "at safepoint or target thread is suspended");
  int count = 0;
  if (java_thread->has_last_Java_frame()) {
    RegisterMap reg_map(java_thread);
    Thread* current_thread = Thread::current();
    ResourceMark rm(current_thread);
    javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
    HandleMark hm(current_thread);
    if (start_depth != 0) {
      if (start_depth > 0) {
        for (int j = 0; j < start_depth && jvf != NULL; j++) {
          jvf = jvf->java_sender();
        }
        if (jvf == NULL) {
          // start_depth is deeper than the stack depth
          return JVMTI_ERROR_ILLEGAL_ARGUMENT;
        }
      } else { // start_depth < 0
        // we are referencing the starting depth based on the oldest
        // part of the stack.
        // optimize to limit the number of times that java_sender() is called
        javaVFrame *jvf_cursor = jvf;
        javaVFrame *jvf_prev = NULL;
        javaVFrame *jvf_prev_prev;
        int j = 0;
        while (jvf_cursor != NULL) {
          jvf_prev_prev = jvf_prev;
          jvf_prev = jvf_cursor;
          for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
            jvf_cursor = jvf_cursor->java_sender();
          }
        }
        if (j == start_depth) {
          // previous pointer is exactly where we want to start
          jvf = jvf_prev;
        } else {
          // we need to back up further to get to the right place
          if (jvf_prev_prev == NULL) {
            // the -start_depth is greater than the stack depth
            return JVMTI_ERROR_ILLEGAL_ARGUMENT;
          }
          // j now is the number of frames on the stack starting with
          // jvf_prev, we start from jvf_prev_prev and move older on
          // the stack that many, the result is -start_depth frames
          // remaining.
          jvf = jvf_prev_prev;
          for (; j < 0; j++) {
            jvf = jvf->java_sender();
          }
        }
      }
    }
    for (; count < max_count && jvf != NULL; count++) {
      frame_buffer[count].method = jvf->method()->jmethod_id();
      frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
      jvf = jvf->java_sender();
    }
  } else {
    if (start_depth != 0) {
      // no frames and there is a starting depth
      return JVMTI_ERROR_ILLEGAL_ARGUMENT;
    }
  }
  *count_ptr = count;
  return JVMTI_ERROR_NONE;
}
Exemplo n.º 6
0
globle void *ImplodeMultifield(
  void *theEnv,
  DATA_OBJECT *value)
  {
   size_t strsize = 0;
   long i, j;
   const char *tmp_str;
   char *ret_str;
   void *rv;
   struct multifield *theMultifield;
   DATA_OBJECT tempDO;

   /*===================================================*/
   /* Determine the size of the string to be allocated. */
   /*===================================================*/

   theMultifield = (struct multifield *) GetpValue(value);
   for (i = GetpDOBegin(value) ; i <= GetpDOEnd(value) ; i++)
     {
      if (GetMFType(theMultifield,i) == FLOAT)
        {
         tmp_str = FloatToString(theEnv,ValueToDouble(GetMFValue(theMultifield,i)));
         strsize += strlen(tmp_str) + 1;
        }
      else if (GetMFType(theMultifield,i) == INTEGER)
        {
         tmp_str = LongIntegerToString(theEnv,ValueToLong(GetMFValue(theMultifield,i)));
         strsize += strlen(tmp_str) + 1;
        }
      else if (GetMFType(theMultifield,i) == STRING)
        {
         strsize += strlen(ValueToString(GetMFValue(theMultifield,i))) + 3;
         tmp_str = ValueToString(GetMFValue(theMultifield,i));
         while(*tmp_str)
           {
            if (*tmp_str == '"')
              { strsize++; }
            else if (*tmp_str == '\\') /* GDR 111599 #835 */
              { strsize++; }           /* GDR 111599 #835 */
            tmp_str++;
           }
        }
#if OBJECT_SYSTEM
      else if (GetMFType(theMultifield,i) == INSTANCE_NAME)
        { strsize += strlen(ValueToString(GetMFValue(theMultifield,i))) + 3; }
      else if (GetMFType(theMultifield,i) == INSTANCE_ADDRESS)
        { strsize += strlen(ValueToString(((INSTANCE_TYPE *)
                            GetMFValue(theMultifield,i))->name)) + 3; }
#endif

      else
        { 
         SetType(tempDO,GetMFType(theMultifield,i));
         SetValue(tempDO,GetMFValue(theMultifield,i));
         strsize += strlen(DataObjectToString(theEnv,&tempDO)) + 1; 
        }
     }

   /*=============================================*/
   /* Allocate the string and copy all components */
   /* of the MULTIFIELD variable to it.           */
   /*=============================================*/

   if (strsize == 0) return(EnvAddSymbol(theEnv,""));
   ret_str = (char *) gm2(theEnv,strsize);
   for(j=0, i=GetpDOBegin(value); i <= GetpDOEnd(value) ; i++)
     {
      /*============================*/
      /* Convert numbers to strings */
      /*============================*/

      if (GetMFType(theMultifield,i) == FLOAT)
        {
         tmp_str = FloatToString(theEnv,ValueToDouble(GetMFValue(theMultifield,i)));
         while(*tmp_str)
           {
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
        }
      else if (GetMFType(theMultifield,i) == INTEGER)
        {
         tmp_str = LongIntegerToString(theEnv,ValueToLong(GetMFValue(theMultifield,i)));
         while(*tmp_str)
           {
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
        }

      /*=======================================*/
      /* Enclose strings in quotes and preceed */
      /* imbedded quotes with a backslash      */
      /*=======================================*/

      else if (GetMFType(theMultifield,i) == STRING)
        {
         tmp_str = ValueToString(GetMFValue(theMultifield,i));
         *(ret_str+j) = '"';
         j++;
         while(*tmp_str)
           {
            if (*tmp_str == '"')
              {
               *(ret_str+j) = '\\';
               j++;
              }
            else if (*tmp_str == '\\') /* GDR 111599 #835 */
              {                        /* GDR 111599 #835 */
               *(ret_str+j) = '\\';    /* GDR 111599 #835 */
               j++;                    /* GDR 111599 #835 */
              }                        /* GDR 111599 #835 */
              
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
         *(ret_str+j) = '"';
         j++;
        }
#if OBJECT_SYSTEM
      else if (GetMFType(theMultifield,i) == INSTANCE_NAME)
        {
         tmp_str = ValueToString(GetMFValue(theMultifield,i));
         *(ret_str + j++) = '[';
         while(*tmp_str)
           {
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
         *(ret_str + j++) = ']';
        }
      else if (GetMFType(theMultifield,i) == INSTANCE_ADDRESS)
        {
         tmp_str = ValueToString(((INSTANCE_TYPE *) GetMFValue(theMultifield,i))->name);
         *(ret_str + j++) = '[';
         while(*tmp_str)
           {
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
         *(ret_str + j++) = ']';
        }
#endif
      else
        {
         SetType(tempDO,GetMFType(theMultifield,i));
         SetValue(tempDO,GetMFValue(theMultifield,i));
         tmp_str = DataObjectToString(theEnv,&tempDO);
         while(*tmp_str)
           {
            *(ret_str+j) = *tmp_str;
            j++, tmp_str++;
           }
         }
      *(ret_str+j) = ' ';
      j++;
     }
   *(ret_str+j-1) = '\0';

   /*====================*/
   /* Return the string. */
   /*====================*/

   rv = EnvAddSymbol(theEnv,ret_str);
   rm(theEnv,ret_str,strsize);
   return(rv);
  }
Exemplo n.º 7
0
static void DeallocateDefmoduleData(
  void *theEnv)
  {
   struct moduleStackItem *tmpMSPtr, *nextMSPtr;
   struct moduleItem *tmpMIPtr, *nextMIPtr;
#if (! RUN_TIME) && (! BLOAD_ONLY)
   struct defmodule *tmpDMPtr, *nextDMPtr;
   struct portConstructItem *tmpPCPtr, *nextPCPtr;
#endif
#if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME)
   int i;
   size_t space;
#endif

#if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME)
   for (i = 0; i < DefmoduleData(theEnv)->BNumberOfDefmodules; i++)
     {
      if (DefmoduleData(theEnv)->DefmoduleArray[i].itemsArray != NULL)
        { 
         rm(theEnv,DefmoduleData(theEnv)->DefmoduleArray[i].itemsArray,
            sizeof(void *) * GetNumberOfModuleItems(theEnv));
        }
     }

   space = DefmoduleData(theEnv)->BNumberOfDefmodules * sizeof(struct defmodule);
   if (space != 0) 
     {
      genfree(theEnv,(void *) DefmoduleData(theEnv)->DefmoduleArray,space);
      DefmoduleData(theEnv)->ListOfDefmodules = NULL;
     }

   space = DefmoduleData(theEnv)->NumberOfPortItems * sizeof(struct portItem);
   if (space != 0) genfree(theEnv,(void *) DefmoduleData(theEnv)->PortItemArray,space);
#endif

#if (! RUN_TIME) && (! BLOAD_ONLY)
   tmpDMPtr = DefmoduleData(theEnv)->ListOfDefmodules;
   while (tmpDMPtr != NULL)
     {
      nextDMPtr = tmpDMPtr->next;
      ReturnDefmodule(theEnv,tmpDMPtr,TRUE);
      tmpDMPtr = nextDMPtr;
     }

   tmpPCPtr = DefmoduleData(theEnv)->ListOfPortConstructItems;
   while (tmpPCPtr != NULL)
     {
      nextPCPtr = tmpPCPtr->next;
      rtn_struct(theEnv,portConstructItem,tmpPCPtr);
      tmpPCPtr = nextPCPtr;
     }
#endif

   tmpMSPtr = DefmoduleData(theEnv)->ModuleStack;
   while (tmpMSPtr != NULL)
     {
      nextMSPtr = tmpMSPtr->next;
      rtn_struct(theEnv,moduleStackItem,tmpMSPtr);
      tmpMSPtr = nextMSPtr;
     }

   tmpMIPtr = DefmoduleData(theEnv)->ListOfModuleItems;
   while (tmpMIPtr != NULL)
     {
      nextMIPtr = tmpMIPtr->next;
      rtn_struct(theEnv,moduleItem,tmpMIPtr);
      tmpMIPtr = nextMIPtr;
     }
     
#if (! RUN_TIME) && (! BLOAD_ONLY)
   DeallocateCallList(theEnv,DefmoduleData(theEnv)->AfterModuleDefinedFunctions);
#endif
   DeallocateCallList(theEnv,DefmoduleData(theEnv)->AfterModuleChangeFunctions);
  }
Exemplo n.º 8
0
void do_modrm(char t)
{
  int m = mod(modrm());
  int r = rm(modrm());
  int extend = (addrsize == 32) ? 4 : 2;
  if (m == 3)
  {
    reg_name(r, t);
    return;
  }
  switch(bytes(t))
  {
  case 1 : ua_str("byte ptr "); break;
  case 2 : ua_str("word ptr "); break;
  case 4 : ua_str("dword ptr "); break;
  default : ua_str("?word ptr "); break;
  }
  if ((m == 0) && (r == 5) && (addrsize == 32))
  {
    ua_str("%p:[");
    ohex('d', extend, 0, addrsize);
    uprintf("%c",']');
    return;
  }
  if ((m == 0) && (r == 6) && (addrsize == 16))
  {
    ua_str("%p:[");
    ohex('w', extend, 0, addrsize);
    uprintf("%c",']');
    return;
  }
  if ((addrsize != 32) || (r != 4))
    ua_str("%p:[");
  if (addrsize == 16)
  {
    switch (r)
    {
      case 0: uprintf("bx+si"); break;
      case 1: uprintf("bx+di"); break;
      case 2: uprintf("bp+si"); break;
      case 3: uprintf("bp+di"); break;
      case 4: uprintf("si"); break;
      case 5: uprintf("di"); break;
      case 6: uprintf("bp"); break;
      case 7: uprintf("bx"); break;
    }
  }
  else
  {
    switch (r)
    {
      case 0: uprintf("eax"); break;
      case 1: uprintf("ecx"); break;
      case 2: uprintf("edx"); break;
      case 3: uprintf("ebx"); break;
      case 4: do_sib(m); break;
      case 5: uprintf("ebp"); break;
      case 6: uprintf("esi"); break;
      case 7: uprintf("edi"); break;
    }
  }
  switch (m)
  {
    case 1:
      ohex('b', extend, 1, addrsize);
      break;
    case 2:
      uprintf("+");
      ohex('v', extend, 1, addrsize);
      break;
  }
  uprintf("%c",']');
}
Exemplo n.º 9
0
static void percent(char c, char t)
{
  word32 vofs;
  long l;
  int extend = (addrsize == 32) ? 4 : 2;
  switch (c)
  {
    case 'A':
      ohex(t, extend, 0, addrsize);
      break;
    case 'C':
      uprintf("C%d", reg(modrm()));
      break;
    case 'D':
      uprintf("D%d", reg(modrm()));
      break;
    case 'E':
      do_modrm(t);
      break;
    case 'G':
      if (t == 'F')
        reg_name(rm(modrm()), t);
      else
        reg_name(reg(modrm()), t);
      break;
    case 'I':
      ohex(t, 0, 0, opsize);
      break;
    case 'J':
      switch (bytes(t))
      {
        case 1:
          vofs = (int8)getbyte();
          break;
        case 2:
          vofs = getbyte();
          vofs += getbyte()<<8;
          vofs = (int16)vofs;
          break;
        case 4:
          vofs = (word32)getbyte();
          vofs |= (word32)getbyte() << 8;
          vofs |= (word32)getbyte() << 16;
          vofs |= (word32)getbyte() << 24;
          break;
      }
      l=vofs+codeoff;
      if(l<0x10000L)
        uprintf("%s%04lx%s %c", hex1, l, hex2,
                (vofs & 0x80000000L) ? 0x18 : 0x19);
      else
        uprintf("%s%08lX%s %c", hex1, l, hex2,
                (vofs & 0x80000000L) ? 0x18 : 0x19);
      break;
    case 'M':
      do_modrm(t);
      break;
    case 'O':
      ua_str("%p:[");
      ohex(t, extend, 0, addrsize);
      uprintf("%c",']');
      break;
    case 'R':
      reg_name(reg(modrm()), t);
      //do_modrm(t);
      break;
    case 'S':
      uprintf("%c","ecsdfg"[reg(modrm())]);
      uprintf("%c",'s');
      break;
    case 'T':
      uprintf("tr%d", reg(modrm()));
      break;
    case 'X':
      uprintf("ds:[");
      if (addrsize == 32)
        uprintf("%c",'e');
      uprintf("si]");
      break;
    case 'Y':
      uprintf("es:[");
      if (addrsize == 32)
        uprintf("%c",'e');
      uprintf("di]");
      break;
    case '2':
      ua_str(second[getbyte()]);
      break;
    case 'e':
      if (opsize == 32)
      {
        if (t == 'w')
          uprintf("%c",'d');
        else
        {
          uprintf("%c",'e');
          uprintf("%c",t);
        }
      }
      else
        uprintf("%c",t);
      break;
    case 'f':
      floating_point(t-'0');
      break;
    case 'g':
      ua_str(groups[t-'0'][reg(modrm())]);
      break;
    case 'p':
      switch (t)
      {
        case 'c':
        case 'd':
        case 'e':
        case 'f':
        case 'g':
        case 's':
          prefix = t;
          ua_str(opmap1[getbyte()]);
          break;
        case ':':
          if (prefix)
            uprintf("%cs:", prefix);
          break;
        case ' ':
          ua_str(opmap1[getbyte()]);
          break;
      }
      break;
    case 's':
      switch (t)
      {
        case 'a':
          addrsize = 48 - addrsize;
          ua_str(opmap1[getbyte()]);
          break;
        case 'o':
          opsize = 48 - opsize;
          ua_str(opmap1[getbyte()]);
          break;
      }
      break;
  }
}
Exemplo n.º 10
0
Arquivo: lex.c Projeto: coyizumi/cs111
/*
 * Set up editing on the given file name.
 * If the first character of name is %, we are considered to be
 * editing the file, otherwise we are reading our mail which has
 * signficance for mbox and so forth.
 *
 * If the -e option is being passed to mail, this function has a
 * tri-state return code: -1 on error, 0 on no mail, 1 if there is
 * mail.
 */
int
setfile(char *name)
{
	FILE *ibuf;
	int checkmode, i, fd;
	struct stat stb;
	char isedit = *name != '%' || getuserid(myname) != getuid();
	char *who = name[1] ? name + 1 : myname;
	char tempname[PATHSIZE];
	static int shudclob;

	checkmode = value("checkmode") != NULL;
	if ((name = expand(name)) == NULL)
		return (-1);

	if ((ibuf = Fopen(name, "r")) == NULL) {
		if (!isedit && errno == ENOENT)
			goto nomail;
		warn("%s", name);
		return (-1);
	}

	if (fstat(fileno(ibuf), &stb) < 0) {
		warn("fstat");
		(void)Fclose(ibuf);
		return (-1);
	}

	if (S_ISDIR(stb.st_mode) || !S_ISREG(stb.st_mode)) {
		(void)Fclose(ibuf);
		errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
		warn("%s", name);
		return (-1);
	}

	/*
	 * Looks like all will be well.  We must now relinquish our
	 * hold on the current set of stuff.  Must hold signals
	 * while we are reading the new file, else we will ruin
	 * the message[] data structure.
	 */

	holdsigs();
	if (shudclob)
		quit();

	/*
	 * Copy the messages into /tmp
	 * and set pointers.
	 */

	readonly = 0;
	if ((i = open(name, 1)) < 0)
		readonly++;
	else
		(void)close(i);
	if (shudclob) {
		(void)fclose(itf);
		(void)fclose(otf);
	}
	shudclob = 1;
	edit = isedit;
	strlcpy(prevfile, mailname, sizeof(prevfile));
	if (name != mailname)
		strlcpy(mailname, name, sizeof(mailname));
	mailsize = fsize(ibuf);
	(void)snprintf(tempname, sizeof(tempname),
	    "%s/mail.RxXXXXXXXXXX", tmpdir);
	if ((fd = mkstemp(tempname)) == -1 || (otf = fdopen(fd, "w")) == NULL)
		err(1, "%s", tempname);
	(void)fcntl(fileno(otf), F_SETFD, 1);
	if ((itf = fopen(tempname, "r")) == NULL)
		err(1, "%s", tempname);
	(void)fcntl(fileno(itf), F_SETFD, 1);
	(void)rm(tempname);
	setptr(ibuf, 0);
	setmsize(msgCount);
	/*
	 * New mail may have arrived while we were reading
	 * the mail file, so reset mailsize to be where
	 * we really are in the file...
	 */
	mailsize = ftello(ibuf);
	(void)Fclose(ibuf);
	relsesigs();
	sawcom = 0;

	if ((checkmode || !edit) && msgCount == 0) {
nomail:
		if (!checkmode) {
			fprintf(stderr, "No mail for %s\n", who);
			return (-1);
		} else
			return (0);
	}
	return (checkmode ? 1 : 0);
}
Exemplo n.º 11
0
int main() {
  Filesystem filesystem;
  char line[LINE_MAX]= "", command[WORD_MAX]= "", temp[WORD_MAX],
       arg1[WORD_MAX]= "", arg2[WORD_MAX]= "", prompt[WORD_MAX]= "%";
  int verbose= 0, length= 0, num_matched= 0, argument_error, done= 0;

  setup_memory_checking();

  printf("%s ", prompt);
  /* continue reading lines until the end of the input */
  while (!done && fgets(line, sizeof(line) - sizeof(*line), stdin) != NULL) {

    temp[0]= '\0';
    sscanf(line, "%[ \t\n]%n", temp, &length);

    if (strcmp(temp, "") != 0 && length == strlen(temp))
      printf("%s ", prompt);  /* ignore empty input lines */

      else {

        /* num_matched is the number of format specifiers that were matched */
        num_matched= sscanf(line, "%s %s %s %s", command, arg1, arg2, temp);
        if (verbose == 1)
          printf("%s", line);

        /* argument_error will be 1 if the wrong number of arguments are
           given for any command */
        argument_error= 0;

        switch(command_idx(command)) {

          case LOGOUT:
          case EXIT:
            if (num_matched == 1)
              done= 1;  /* also quit if the command entered is logout or
                           exit */
            else argument_error= 1;
            break;

          /* call mkfs() if the line began with "mkfs" with no following
             arguments */
          case MKFS:
            if (num_matched == 1)
              mkfs(&filesystem);
            else argument_error= 1;
            break;

          /* call touch() if the line began with "touch" and had one
             following argument; if touch() returns -1 print an appropriate
             error message */
          case TOUCH:
            if (num_matched != 2)
              argument_error= 1;
            else
              if (touch(&filesystem, arg1) == -1)
                printf("Missing or invalid operand.\n");
            break;

          /* call mkdir() if the line began with "mkdir" and had one
             following argument; if mkdir() returns -1 or -2 print an
             appropriate error message */
          case MKDIR:
            if (num_matched != 2)
              argument_error= 1;
            else
              switch (mkdir(&filesystem, arg1)) {
                case -1: printf("Missing or invalid operand.\n");
                         break;
                case -2: printf("Cannot create directory %s: File exists.\n",
                                arg1);
                         break;
                default: break;  /* no-op; 0 return is expected */
              }
            break;

          /* call cd() if the line began with "cd" and had one following
             argument; if cd() returns -1 or -2 print an appropriate error
             message */
          case CD:
            if (num_matched != 1 && num_matched != 2)
              argument_error= 1;
            else
              switch (cd(&filesystem, arg1)) {
                case -1: printf("%s: No such file or directory.\n", arg1);
                         break;
                case -2: printf("%s: Not a directory.\n", arg1);
                         break;
                default: break;  /* no-op; 0 return is expected */
              }
            break;

          /* call ls() if the line began with "ls" and had one following
             argument; if ls() returns -1 print an appropriate error
             message */
          case LS:
            if (num_matched != 1 && num_matched != 2)
              argument_error= 1;
            else
              if (ls(filesystem, arg1) == -1)
                printf("%s: No such file or directory.\n", arg1);
            break;

          /* call pwd() if the line began with "pwd" with no following
             arguments */
          case PWD:
            if (num_matched == 1)
              pwd(filesystem);
            else argument_error= 1;
            break;

          /* call rm() if the line began with "rm" and had one following
             argument; if rm() returns -1, -2, or -3 print an appropriate
             error message */
          case RM:
            if (num_matched != 2)
              argument_error= 1;
            else
              switch (rm(&filesystem, arg1)) {
                case -1: printf("%s: No such file or directory.\n", arg1);
                         break;
                case -2: printf("Cannot remove directory '%s'.\n", arg1);
                         break;
                case -3: printf("Missing or invalid operand.\n");
                         break;
                default: break;  /* no-op; 0 return is expected */
              }
            break;

           /* call re_name() if the line began with "rename" with two
              following arguments; if it returns an error code (-1 through
              -4) print an appopriate error message */
          case RENAME:
            if (num_matched != 3)
              argument_error= 1;
            else
              switch (re_name(&filesystem, arg1, arg2)) {
                case -1: printf("%s: No such file or directory.\n", arg1);
                         break;
                case -2: printf("Missing or invalid operand.\n");
                         break;
                case -3: printf("File or directory %s already exists.\n",
                                arg1);
                         break;
                case -4: printf("%s and %s are the same file.\n", arg1, arg2);
                         break;
                default: break;  /* no-op; 0 return is expected */
              }
            break;

           /* call rmfs() if the line began with "rmfs" with no following
              arguments */
          case RMFS:
            if (num_matched == 1)
              rmfs(&filesystem);
            else argument_error= 1;
            break;

          /* the variable verbose is set to 1 if the "set verbose" command
             is entered. */
          case SET:
            if (num_matched == 2 && strcmp(arg1, "verbose") == 0)
              verbose= 1;
            else argument_error= 1;
            break;

            /* the variable verbose is set to 0 if "unset verbose" is
               entered. */
          case UNSET:
            if (num_matched == 2 && strcmp(arg1, "verbose") == 0)
              verbose= 0;
            else argument_error= 1;
            break;

          /* error message for a command not matching one of the function
             names */
          default: printf("%s: Command not found.\n", command);
            break;
        }

        /* error message for a command with the wrong number of arguments */
        if (argument_error)
          printf("Invalid arguments.\n");

        if (verbose == 1)
          printf("\n");
        printf("%s ", prompt);

        /* sscanf() will fail if the line read is empty, in which case the
           prior command will be executed again unless it's first cleared
           out */
        arg1[0]= arg2[0]= command[0]= '\0';
      }
  }

  check_memory_leak();

  return 0;
}
Exemplo n.º 12
0
void TmpList::rmP(void *p)
{
  rm(((Vertex *)p)->ordinal);
}
Exemplo n.º 13
0
/**
 * If a deoptimization happens, this function returns the point of next bytecode to continue execution.
 */
address AbstractInterpreter::deopt_continue_after_entry(Method* method, address bcp, int callee_parameters, bool is_top_frame) {
  assert(method->contains(bcp), "just checkin'");

  // Get the original and rewritten bytecode.
  Bytecodes::Code code = Bytecodes::java_code_at(method, bcp);
  assert(!Interpreter::bytecode_should_reexecute(code), "should not reexecute");

  const int bci = method->bci_from(bcp);

  // compute continuation length
  const int length = Bytecodes::length_at(method, bcp);

  // compute result type
  BasicType type = T_ILLEGAL;

  switch (code) {
    case Bytecodes::_invokevirtual  :
    case Bytecodes::_invokespecial  :
    case Bytecodes::_invokestatic   :
    case Bytecodes::_invokeinterface: {
      Thread *thread = Thread::current();
      ResourceMark rm(thread);
      methodHandle mh(thread, method);
      type = Bytecode_invoke(mh, bci).result_type();
      // since the cache entry might not be initialized:
      // (NOT needed for the old calling convension)
      if (!is_top_frame) {
        int index = Bytes::get_native_u2(bcp+1);
        method->constants()->cache()->entry_at(index)->set_parameter_size(callee_parameters);
      }
      break;
    }

   case Bytecodes::_invokedynamic: {
      Thread *thread = Thread::current();
      ResourceMark rm(thread);
      methodHandle mh(thread, method);
      type = Bytecode_invoke(mh, bci).result_type();
      // since the cache entry might not be initialized:
      // (NOT needed for the old calling convension)
      if (!is_top_frame) {
        int index = Bytes::get_native_u4(bcp+1);
        method->constants()->invokedynamic_cp_cache_entry_at(index)->set_parameter_size(callee_parameters);
      }
      break;
    }

    case Bytecodes::_ldc   :
    case Bytecodes::_ldc_w : // fall through
    case Bytecodes::_ldc2_w:
      {
        Thread *thread = Thread::current();
        ResourceMark rm(thread);
        methodHandle mh(thread, method);
        type = Bytecode_loadconstant(mh, bci).result_type();
        break;
      }

    default:
      type = Bytecodes::result_type(code);
      break;
  }

  // return entry point for computed continuation state & bytecode length
  return
    is_top_frame
    ? Interpreter::deopt_entry (as_TosState(type), length)
    : Interpreter::return_entry(as_TosState(type), length, code);
}
Exemplo n.º 14
0
// Create a new plot window
PlotAgent *new_plotter(const string& name, DispValue *source)
{
    static int tics = 1;

    string cmd = app_data.plot_command;
    cmd.gsub("@FONT@", make_font(app_data, FixedWidthDDDFont));

    string window_name = ddd_NAME "plot" + itostring(tics++);
    if (cmd.contains("@NAME@"))
	cmd.gsub("@NAME@", window_name);
    else
	cmd += " -name " + window_name;

    // Create shell
    PlotWindowInfo *plot = new_decoration(name);
    if (plot == 0)
	return 0;

    plot->source      = source;
    plot->window_name = window_name;
    XtVaSetValues(plot->shell, XmNuserData, XtPointer(True), XtPointer(0));

    // Pop up a working dialog
    static Widget dialog = 0;
    if (dialog == 0)
    {
	Arg args[10];
	Cardinal arg = 0;
	dialog = verify(XmCreateWorkingDialog(find_shell(),
					      XMST("launch_plot_dialog"), 
					      args, arg));
	XtUnmanageChild(XmMessageBoxGetChild(dialog,
					     XmDIALOG_OK_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(dialog,
					     XmDIALOG_HELP_BUTTON));
    }

    XtRemoveAllCallbacks(dialog, XmNcancelCallback);
    XtAddCallback(dialog, XmNcancelCallback, CancelPlotCB, XtPointer(plot));
    plot->working_dialog = dialog;

    string base = cmd;
    if (base.contains(' '))
	base = cmd.before(' ');
    MString msg = rm("Starting ") + tt(base) + rm("...");
    XtVaSetValues(dialog, XmNmessageString, msg.xmstring(), XtPointer(0));
    manage_and_raise(dialog);
    wait_until_mapped(dialog);

    // Invoke plot process
    PlotAgent *plotter = 
	new PlotAgent(XtWidgetToApplicationContext(plot->shell), cmd);

    XtAddCallback(plot->shell, XtNpopdownCallback,
		  CancelPlotCB, XtPointer(plot));

    if (plot->area != 0)
    {
	XtAddCallback(plot->area->widget(), XmNexposeCallback,
		      ExposePlotAreaCB, XtPointer(plot));
	XtAddCallback(plot->area->widget(), XmNresizeCallback,
		      ResizePlotAreaCB, XtPointer(plot));
    }

    string init = app_data.plot_init_commands;
    init.prepend("set term " + string(app_data.plot_term_type) + "\n");
    if (!init.empty() && !init.contains('\n', -1))
	init += '\n';

    // Add trace handlers
    plotter->addHandler(Input,  TraceInputHP);     // Gnuplot => DDD
    plotter->addHandler(Output, TraceOutputHP);    // DDD => Gnuplot
    plotter->addHandler(Error,  TraceErrorHP);     // Gnuplot Errors => DDD

    // Show Gnuplot Errors in status line
    plotter->addHandler(Error,  SetStatusHP,       (void *)plot);

    // Handle death
    plotter->addHandler(Died, PlotterNotFoundHP, (void *)plot);
    plotter->addHandler(Died, DeletePlotterHP,   (void *)plot);

    if (plot->area != 0)
	plotter->addHandler(Plot, GetPlotHP, (void *)plot);

    plotter->start_with(init);
    plot->plotter = plotter;

    return plotter;
}
int main()
{
	int ch;
	struct student *head=NULL;
	
	printf("\n\n\n\n\n\n\n\n\n\t\t\t学生信息管理系统\t\t\n\n\n\t\t\t15080120 郭都豪\t\t\n\n\t\t\t2015.12.24\t\t\n\t\t\tVersion 1.0\t\t\n\n\n\n\n");
	system("pause");
		
	while (1)
	{		
		system("cls");
		printf("链表头的地址:%p\n\n\n\n\t\t\t(1)Create a student list; \n\t\t\t(2)Sort according to the StudentID;\n\t\t\t(3)Insert a student;\n\t\t\t(4)Delete a student;\n\t\t\t(5)Update a student Info;\n\t\t\t(6)Search a student ;\n\t\t\t(7)Display all students;\n\t\t\t(8)Save to the file;\n\t\t\t(9)Open the file;\n\t\t\t(10)exit\n",head);
		scanf("%d",&ch);
		
		switch(ch)
		{
			case 1:
				system("cls");
				head = create(head);//创建一个学生列表 
				break;
			case 2:
				system("cls");
				if (nullchk(head))
					break;
				head = sort(head);//排序
				printf("排序完成\n");
				system("pause");
				break;
			case 3:
				system("cls");
				if (nullchk(head))
					break;
				head = insert(head);//插入
				break;
			case 4:
				system("cls");
				if (nullchk(head))
					break;
				head = rm(head);//移除
				break;
			case 5:
				system("cls");
				if (nullchk(head))
					break;
				update(head);//更新。
				break;		
			case 6:
				system("cls");
				if (nullchk(head))
					break;
				search(head);
				break;
			case 7:
				system("cls");
				if (nullchk(head))
					break;
				display(head);
				system("pause");
				break;
			case 8:
				system("cls");
				if (nullchk(head))
					break;
				out(head);
				break;
			case 9:
				system("cls");
				head = in(head);
				break;
			case 10:
				release(head);//释放整个链表
				return 0;
		}	
	}
}
void instanceKlassKlass::oop_verify_on(oop obj, outputStream* st) {
  klassKlass::oop_verify_on(obj, st);
  if (!obj->partially_loaded()) {
    Thread *thread = Thread::current();
    instanceKlass* ik = instanceKlass::cast(klassOop(obj));   

    // Avoid redundant verifies
    if (ik->_verify_count == Universe::verify_count()) return;
    ik->_verify_count = Universe::verify_count();

    // Verify that klass is present in SystemDictionary
    if (ik->is_loaded()) {
      symbolHandle h_name (thread, ik->name());
      Handle h_loader (thread, ik->class_loader());
      SystemDictionary::verify_obj_klass_present(obj, h_name, h_loader);
    }
    
    // Verify static fields
    VerifyFieldClosure blk;
    ik->iterate_static_fields(&blk);

    // Verify vtables
    if (ik->is_linked()) {
      ResourceMark rm(thread);  
      // $$$ This used to be done only for m/s collections.  Doing it
      // always seemed a valid generalization.  (DLD -- 6/00)
      ik->vtable()->verify(st);
    }
  
    // Verify oop map cache
    if (ik->oop_map_cache() != NULL) {
      ik->oop_map_cache()->verify();
    }

    // Verify first subklass
    if (ik->subklass_oop() != NULL) { 
      guarantee(ik->subklass_oop()->is_perm(),  "should be in permspace");
      guarantee(ik->subklass_oop()->is_klass(), "should be klass");
    }

    // Verify siblings
    klassOop super = ik->super();
    Klass* sib = ik->next_sibling();
    int sib_count = 0;
    while (sib != NULL) {
      if (sib == ik) {
        fatal1("subclass cycle of length %d", sib_count);
      }
      if (sib_count >= 100000) {
        fatal1("suspiciously long subclass list %d", sib_count);
      }
      guarantee(sib->as_klassOop()->is_klass(), "should be klass");
      guarantee(sib->as_klassOop()->is_perm(),  "should be in permspace");
      guarantee(sib->super() == super, "siblings should have same superklass");
      sib = sib->next_sibling();
    }

    // Verify implementor field
    if (ik->implementor() != NULL) {
      guarantee(ik->is_interface(), "only interfaces should have implementor set");
      guarantee(ik->nof_implementors() == 1, "should only have one implementor");
      klassOop im = ik->implementor();
      guarantee(im->is_perm(),  "should be in permspace");
      guarantee(im->is_klass(), "should be klass");
      guarantee(!Klass::cast(klassOop(im))->is_interface(), "implementors cannot be interfaces");
    }
    
    // Verify local interfaces
    objArrayOop local_interfaces = ik->local_interfaces();
    guarantee(local_interfaces->is_perm(),          "should be in permspace");
    guarantee(local_interfaces->is_objArray(),      "should be obj array");
    int j;
    for (j = 0; j < local_interfaces->length(); j++) {
      oop e = local_interfaces->obj_at(j);
      guarantee(e->is_klass() && Klass::cast(klassOop(e))->is_interface(), "invalid local interface");
    }

    // Verify transitive interfaces
    objArrayOop transitive_interfaces = ik->transitive_interfaces();
    guarantee(transitive_interfaces->is_perm(),          "should be in permspace");
    guarantee(transitive_interfaces->is_objArray(),      "should be obj array");
    for (j = 0; j < transitive_interfaces->length(); j++) {
      oop e = transitive_interfaces->obj_at(j);
      guarantee(e->is_klass() && Klass::cast(klassOop(e))->is_interface(), "invalid transitive interface");
    }

    // Verify methods
    objArrayOop methods = ik->methods();
    guarantee(methods->is_perm(),              "should be in permspace");
    guarantee(methods->is_objArray(),          "should be obj array");
    for (j = 0; j < methods->length(); j++) {
      guarantee(methods->obj_at(j)->is_method(), "non-method in methods array");
    }
    for (j = 0; j < methods->length() - 1; j++) {
      methodOop m1 = methodOop(methods->obj_at(j));
      methodOop m2 = methodOop(methods->obj_at(j + 1));
      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
    }
    
    // Verify method ordering
    typeArrayOop method_ordering = ik->method_ordering();
    guarantee(method_ordering->is_perm(),              "should be in permspace");
    guarantee(method_ordering->is_typeArray(),         "should be type array");
    int length = method_ordering->length();
    if (jvmdi::enabled()) {
      guarantee(length == methods->length(),           "invalid method ordering length");
      jlong sum = 0;
      for (j = 0; j < length; j++) {
        int original_index = method_ordering->int_at(j);
        guarantee(original_index >= 0 && original_index < length, "invalid method ordering index");
        sum += original_index;
      }
      // Verify sum of indices 0,1,...,length-1
      guarantee(sum == ((jlong)length*(length-1))/2,   "invalid method ordering sum");
    } else {
      guarantee(length == 0,                           "invalid method ordering length");
    }

    // Verify JNI static field/method identifiers
    if (ik->jni_ids() != NULL) {
      ik->jni_ids()->verify(ik->as_klassOop());
    }

    // Verify other fields
    if (ik->array_klasses() != NULL) {
      guarantee(ik->array_klasses()->is_perm(),      "should be in permspace");
      guarantee(ik->array_klasses()->is_klass(),     "should be klass");
    }
    guarantee(ik->fields()->is_perm(),               "should be in permspace");
    guarantee(ik->fields()->is_typeArray(),          "should be type array");
    guarantee(ik->constants()->is_perm(),            "should be in permspace");
    guarantee(ik->constants()->is_constantPool(),    "should be constant pool");
    guarantee(ik->inner_classes()->is_perm(),        "should be in permspace");
    guarantee(ik->inner_classes()->is_typeArray(),   "should be type array");
    if (ik->source_file_name() != NULL) {
      guarantee(ik->source_file_name()->is_perm(),   "should be in permspace");
      guarantee(ik->source_file_name()->is_symbol(), "should be symbol");
    }
    if (ik->source_debug_extension() != NULL) {
      guarantee(ik->source_debug_extension()->is_perm(),   "should be in permspace");
      guarantee(ik->source_debug_extension()->is_symbol(), "should be symbol");
    }
    if (ik->protection_domain() != NULL) {
      guarantee(ik->protection_domain()->is_oop(),  "should be oop");
    }
    if (ik->signers() != NULL) {
      guarantee(ik->signers()->is_objArray(),       "should be obj array");
    }
  }
}
Exemplo n.º 17
0
Arquivo: main.c Projeto: mengpq/os
void process_command(char* cmd){
	char* CMD[10];
	memset(CMD,0,10);
	int i,pid,total,status;
	total=0;
	split_by_space(CMD,cmd,&total);
	if (total==0) return;
	if (strcmp(CMD[0],"clear")==0){
		clear_screen();
	} else if (strcmp(CMD[0],"run")==0){
		if (total<2 || (pid=run(CMD[1]))==-1){
			display_string("this program is not exists or already running!\n");
		} else{
			display_string("run successful ");
			display_string("pid = "); display_int(pid); 
			display_string(" name = "); display_string(CMD[1]);
			display_string("\n");
		}
	} else if (strcmp(CMD[0],"sleep")==0){
		if (total<2 || sleep(CMD[1])==-1){
		} else{
			display_string("Process "); 
			display_string(CMD[1]);
			display_string(" is sleeping now!\n");
		}
	} else if (strcmp(CMD[0],"kill")==0){
		if (total<2 || !is_number(CMD[1])){
			display_string("Usage: kill <pid>\n");
		} else 
		if (kill(CMD[1])==-1){
			display_string("No such process\n");
		} else{
			display_string("The process with pid=");
			display_string(CMD[1]);
			display_string(" was stopped\n");
		}
	} else if (strcmp(CMD[0],"killall")==0){
		if (total<2){
			display_string("Usage: killall <name>");
		} else{
			if (killall(CMD[1])==-1){
				display_string("No such process\n");
			} else{
				display_string("the process with name=");
				display_string(CMD[1]);
				display_string(" was stopped\n");
			}
		}
	} else if (strcmp(CMD[0],"setp")==0){
		if (total<3 || !is_number(CMD[2])){
			display_string("Usage: setp <name> <num>\n");
		} else if (setp(CMD[1],atoi(CMD[2]))==-1){
			display_string("i can't set the priority of ");
			display_string(CMD[1]);
			display_string("\n");
		} else {
			display_string("set priority successful\n");
		}
	} else if (strcmp(CMD[0],"ps")==0){
		if (show_tasks(CMD[1])==-1){
			display_string("I can't recognize the parameter\n");
		}
	} else if (strcmp(CMD[0],"ls")==0){
		ls();
	} else if (strcmp(CMD[0],"rm")==0){
		if (total<2){
			display_string("Usage: rm <filename>\n");
		} else{
			if (rm(CMD[1])==-1){
				display_string(CMD[1]); 
				display_string(" no exist!\n");
			}
		}
	} else if (strcmp(CMD[0],"help")==0){
		show_help();
	} else if (strcmp(CMD[0],"edit")==0){
		if (total==1){
			display_string("Usage: edit <filename>\n");
		} else start_editor(CMD[1]);
	} else if (strcmp(CMD[0],"dump")==0){
		if (dump_mem(CMD[1],CMD[2])==-1){
			display_string("I can't recognize the parameter\n");
		}
	} else{
		display_string(cmd); display_string(": ");
		display_string("no such command\n");
	}
}
Exemplo n.º 18
0
/*******************************************************************************
  NAME         : CreateGetAndPutHandlers
  DESCRIPTION  : Creates two message-handlers with
                  the following syntax for the slot:

                 (defmessage-handler <class> get-<slot-name> primary ()
                    ?self:<slot-name>)

                 For single-field slots:

                 (defmessage-handler <class> put-<slot-name> primary (?value)
                    (bind ?self:<slot-name> ?value))

                 For multifield slots:

                 (defmessage-handler <class> put-<slot-name> primary ($?value)
                    (bind ?self:<slot-name> ?value))

  INPUTS       : The class slot descriptor
  RETURNS      : Nothing useful
  SIDE EFFECTS : Message-handlers created
  NOTES        : A put handler is not created for read-only slots
 *******************************************************************************/
globle void CreateGetAndPutHandlers(
  void *theEnv,
  SLOT_DESC *sd)
  {
   char *className,*slotName;
   unsigned bufsz;
   char *buf,*handlerRouter = "*** Default Public Handlers ***";
   int oldPWL,oldCM;
   char *oldRouter;
   char *oldString;
   long oldIndex;

   if ((sd->createReadAccessor == 0) && (sd->createWriteAccessor == 0))
     return;
   className = ValueToString(sd->cls->header.name);
   slotName = ValueToString(sd->slotName->name);

   bufsz = (sizeof(char) * (strlen(className) + (strlen(slotName) * 2) + 80));
   buf = (char *) gm2(theEnv,bufsz);

   oldPWL = GetPrintWhileLoading(theEnv);
   SetPrintWhileLoading(theEnv,FALSE);
   oldCM = EnvSetConserveMemory(theEnv,TRUE);

   if (sd->createReadAccessor)
     {
      sprintf(buf,"%s get-%s () ?self:%s)",className,slotName,slotName);
      
      oldRouter = RouterData(theEnv)->FastCharGetRouter;
      oldString = RouterData(theEnv)->FastCharGetString;
      oldIndex = RouterData(theEnv)->FastCharGetIndex;
   
      RouterData(theEnv)->FastCharGetRouter = handlerRouter;
      RouterData(theEnv)->FastCharGetIndex = 0;
      RouterData(theEnv)->FastCharGetString = buf;
      
      ParseDefmessageHandler(theEnv,handlerRouter);
      DestroyPPBuffer(theEnv);
      /*
      if (OpenStringSource(theEnv,handlerRouter,buf,0))
        {
         ParseDefmessageHandler(handlerRouter);
         DestroyPPBuffer();
         CloseStringSource(theEnv,handlerRouter);
        }
      */
      RouterData(theEnv)->FastCharGetRouter = oldRouter;
      RouterData(theEnv)->FastCharGetIndex = oldIndex;
      RouterData(theEnv)->FastCharGetString = oldString;
     }

   if (sd->createWriteAccessor)
     {
      sprintf(buf,"%s put-%s ($?value) (bind ?self:%s ?value))",
                  className,slotName,slotName);
                  
      oldRouter = RouterData(theEnv)->FastCharGetRouter;
      oldString = RouterData(theEnv)->FastCharGetString;
      oldIndex = RouterData(theEnv)->FastCharGetIndex;
   
      RouterData(theEnv)->FastCharGetRouter = handlerRouter;
      RouterData(theEnv)->FastCharGetIndex = 0;
      RouterData(theEnv)->FastCharGetString = buf;
      
      ParseDefmessageHandler(theEnv,handlerRouter);
      DestroyPPBuffer(theEnv);

/*     
      if (OpenStringSource(theEnv,handlerRouter,buf,0))
        {
         ParseDefmessageHandler(handlerRouter);
         DestroyPPBuffer();
         CloseStringSource(theEnv,handlerRouter);
        }
*/        
      RouterData(theEnv)->FastCharGetRouter = oldRouter;
      RouterData(theEnv)->FastCharGetIndex = oldIndex;
      RouterData(theEnv)->FastCharGetString = oldString;
     }

   SetPrintWhileLoading(theEnv,oldPWL);
   EnvSetConserveMemory(theEnv,oldCM);

   rm(theEnv,(void *) buf,bufsz);
  }
Exemplo n.º 19
0
static void ReturnDefmodule(
  void *theEnv,
  struct defmodule *theDefmodule,
  intBool environmentClear)
  {
   int i;
   struct moduleItem *theItem;
   struct portItem *theSpec, *nextSpec;

   /*=====================================================*/
   /* Set the current module to the module being deleted. */
   /*=====================================================*/

   if (theDefmodule == NULL) return;
   
   if (! environmentClear)
     { EnvSetCurrentModule(theEnv,(void *) theDefmodule); }

   /*============================================*/
   /* Call the free functions for the constructs */
   /* belonging to this module.                  */
   /*============================================*/

   if (theDefmodule->itemsArray != NULL)
     {
      if (! environmentClear)
        {
         for (i = 0, theItem = DefmoduleData(theEnv)->ListOfModuleItems;
              (i < DefmoduleData(theEnv)->NumberOfModuleItems) && (theItem != NULL);
              i++, theItem = theItem->next)
           {
            if (theItem->freeFunction != NULL)
              { (*theItem->freeFunction)(theEnv,theDefmodule->itemsArray[i]); }
           }
        }

      rm(theEnv,theDefmodule->itemsArray,sizeof(void *) * DefmoduleData(theEnv)->NumberOfModuleItems);
    }

   /*======================================================*/
   /* Decrement the symbol count for the defmodule's name. */
   /*======================================================*/

   if (! environmentClear)
     { DecrementSymbolCount(theEnv,theDefmodule->name); }

   /*====================================*/
   /* Free the items in the import list. */
   /*====================================*/

   theSpec = theDefmodule->importList;
   while (theSpec != NULL)
     {
      nextSpec = theSpec->next;
      if (! environmentClear)
        {
         if (theSpec->moduleName != NULL) DecrementSymbolCount(theEnv,theSpec->moduleName);
         if (theSpec->constructType != NULL) DecrementSymbolCount(theEnv,theSpec->constructType);
         if (theSpec->constructName != NULL) DecrementSymbolCount(theEnv,theSpec->constructName);
        }
      rtn_struct(theEnv,portItem,theSpec);
      theSpec = nextSpec;
     }

   /*====================================*/
   /* Free the items in the export list. */
   /*====================================*/

   theSpec = theDefmodule->exportList;
   while (theSpec != NULL)
     {
      nextSpec = theSpec->next;
      if (! environmentClear)
        {
         if (theSpec->moduleName != NULL) DecrementSymbolCount(theEnv,theSpec->moduleName);
         if (theSpec->constructType != NULL) DecrementSymbolCount(theEnv,theSpec->constructType);
         if (theSpec->constructName != NULL) DecrementSymbolCount(theEnv,theSpec->constructName);
        }
      rtn_struct(theEnv,portItem,theSpec);
      theSpec = nextSpec;
     }

   /*=========================================*/
   /* Free the defmodule pretty print string. */
   /*=========================================*/

   if (theDefmodule->ppForm != NULL)
     {
      rm(theEnv,theDefmodule->ppForm,
         (int) sizeof(char) * (strlen(theDefmodule->ppForm) + 1));
     }
     
   /*=======================*/
   /* Return the user data. */
   /*=======================*/

   ClearUserDataList(theEnv,theDefmodule->usrData);
   
   /*======================================*/
   /* Return the defmodule data structure. */
   /*======================================*/

   rtn_struct(theEnv,defmodule,theDefmodule);
  }
Exemplo n.º 20
0
/***********************************************************************
  NAME         : ParseDefmessageHandler
  DESCRIPTION  : Parses a message-handler for a class of objects
  INPUTS       : The logical name of the input source
  RETURNS      : FALSE if successful parse, TRUE otherwise
  SIDE EFFECTS : Handler allocated and inserted into class
  NOTES        : H/L Syntax:

                 (defmessage-handler <class> <name> [<type>] [<comment>]
                    (<params>)
                    <action>*)

                 <params> ::= <var>* | <var>* $?<name>
 ***********************************************************************/
globle int ParseDefmessageHandler(
  void *theEnv,
  char *readSource)
  {
   DEFCLASS *cls;
   SYMBOL_HN *cname,*mname,*wildcard;
   unsigned mtype = MPRIMARY;
   int min,max,error,lvars;
   EXPRESSION *hndParams,*actions;
   HANDLER *hnd;

   SetPPBufferStatus(theEnv,ON);
   FlushPPBuffer(theEnv);
   SetIndentDepth(theEnv,3);
   SavePPBuffer(theEnv,"(defmessage-handler ");

#if BLOAD || BLOAD_AND_BSAVE
   if ((Bloaded(theEnv)) && (! ConstructData(theEnv)->CheckSyntaxMode))
     {
      CannotLoadWithBloadMessage(theEnv,"defmessage-handler");
      return(TRUE);
     }
#endif
   cname = GetConstructNameAndComment(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken,"defmessage-handler",
                                      NULL,NULL,"~",TRUE,FALSE,DEFMODULE_CONSTRUCT);
   if (cname == NULL)
     return(TRUE);
   cls = LookupDefclassByMdlOrScope(theEnv,ValueToString(cname));
   if (cls == NULL)
     {
      PrintErrorID(theEnv,"MSGPSR",1,FALSE);
      EnvPrintRouter(theEnv,WERROR,"A class must be defined before its message-handlers.\n");
      return(TRUE);
     }
   if ((cls == DefclassData(theEnv)->PrimitiveClassMap[INSTANCE_NAME]) ||
       (cls == DefclassData(theEnv)->PrimitiveClassMap[INSTANCE_ADDRESS]) ||
       (cls == DefclassData(theEnv)->PrimitiveClassMap[INSTANCE_NAME]->directSuperclasses.classArray[0]))
     {
      PrintErrorID(theEnv,"MSGPSR",8,FALSE);
      EnvPrintRouter(theEnv,WERROR,"Message-handlers cannot be attached to the class ");
      EnvPrintRouter(theEnv,WERROR,EnvGetDefclassName(theEnv,(void *) cls));
      EnvPrintRouter(theEnv,WERROR,".\n");
      return(TRUE);
     }
   if (HandlersExecuting(cls))
     {
      PrintErrorID(theEnv,"MSGPSR",2,FALSE);
      EnvPrintRouter(theEnv,WERROR,"Cannot (re)define message-handlers during execution of \n");
      EnvPrintRouter(theEnv,WERROR,"  other message-handlers for the same class.\n");
      return(TRUE);
     }
   if (GetType(DefclassData(theEnv)->ObjectParseToken) != SYMBOL)
     {
      SyntaxErrorMessage(theEnv,"defmessage-handler");
      return(TRUE);
     }
   PPBackup(theEnv);
   PPBackup(theEnv);
   SavePPBuffer(theEnv," ");
   SavePPBuffer(theEnv,DefclassData(theEnv)->ObjectParseToken.printForm);
   SavePPBuffer(theEnv," ");
   mname = (SYMBOL_HN *) GetValue(DefclassData(theEnv)->ObjectParseToken);
   GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
   if (GetType(DefclassData(theEnv)->ObjectParseToken) != LPAREN)
     {
      SavePPBuffer(theEnv," ");
      if (GetType(DefclassData(theEnv)->ObjectParseToken) != STRING)
        {
         if (GetType(DefclassData(theEnv)->ObjectParseToken) != SYMBOL)
           {
            SyntaxErrorMessage(theEnv,"defmessage-handler");
            return(TRUE);
           }
         mtype = HandlerType(theEnv,"defmessage-handler",DOToString(DefclassData(theEnv)->ObjectParseToken));
         if (mtype == MERROR)
           return(TRUE);
#if ! IMPERATIVE_MESSAGE_HANDLERS
         if (mtype == MAROUND)
           return(TRUE);
#endif
         GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
         if (GetType(DefclassData(theEnv)->ObjectParseToken) == STRING)
           {
            SavePPBuffer(theEnv," ");
            GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
           }
        }
      else
        {
         SavePPBuffer(theEnv," ");
         GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
        }
     }
   PPBackup(theEnv);
   PPBackup(theEnv);
   PPCRAndIndent(theEnv);
   SavePPBuffer(theEnv,DefclassData(theEnv)->ObjectParseToken.printForm);

   hnd = FindHandlerByAddress(cls,mname,mtype);
   if (GetPrintWhileLoading(theEnv) && GetCompilationsWatch(theEnv))
     {
      EnvPrintRouter(theEnv,WDIALOG,"   Handler ");
      EnvPrintRouter(theEnv,WDIALOG,ValueToString(mname));
      EnvPrintRouter(theEnv,WDIALOG," ");
      EnvPrintRouter(theEnv,WDIALOG,MessageHandlerData(theEnv)->hndquals[mtype]);
      EnvPrintRouter(theEnv,WDIALOG,(char *) ((hnd == NULL) ? " defined.\n" : " redefined.\n"));
     }

   if ((hnd != NULL) ? hnd->system : FALSE)
     {
      PrintErrorID(theEnv,"MSGPSR",3,FALSE);
      EnvPrintRouter(theEnv,WERROR,"System message-handlers may not be modified.\n");
      return(TRUE);
     }

   hndParams = GenConstant(theEnv,SYMBOL,(void *) MessageHandlerData(theEnv)->SELF_SYMBOL);
   hndParams = ParseProcParameters(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken,hndParams,
                                    &wildcard,&min,&max,&error,IsParameterSlotReference);
   if (error)
     return(TRUE);
   PPCRAndIndent(theEnv);
   ExpressionData(theEnv)->ReturnContext = TRUE;
   actions = ParseProcActions(theEnv,"message-handler",readSource,
                              &DefclassData(theEnv)->ObjectParseToken,hndParams,wildcard,
                              SlotReferenceVar,BindSlotReference,&lvars,
                              (void *) cls);
   if (actions == NULL)
     {
      ReturnExpression(theEnv,hndParams);
      return(TRUE);
     }
   if (GetType(DefclassData(theEnv)->ObjectParseToken) != RPAREN)
     {
      SyntaxErrorMessage(theEnv,"defmessage-handler");
      ReturnExpression(theEnv,hndParams);
      ReturnPackedExpression(theEnv,actions);
      return(TRUE);
     }
   PPBackup(theEnv);
   PPBackup(theEnv);
   SavePPBuffer(theEnv,DefclassData(theEnv)->ObjectParseToken.printForm);
   SavePPBuffer(theEnv,"\n");

   /* ===================================================
      If we're only checking syntax, don't add the
      successfully parsed defmessage-handler to the KB.
      =================================================== */

   if (ConstructData(theEnv)->CheckSyntaxMode)
     {
      ReturnExpression(theEnv,hndParams);
      ReturnPackedExpression(theEnv,actions);
      return(FALSE);
     }

   if (hnd != NULL)
     {
      ExpressionDeinstall(theEnv,hnd->actions);
      ReturnPackedExpression(theEnv,hnd->actions);
      if (hnd->ppForm != NULL)
        rm(theEnv,(void *) hnd->ppForm,
           (sizeof(char) * (strlen(hnd->ppForm)+1)));
     }
   else
     {
      hnd = InsertHandlerHeader(theEnv,cls,mname,(int) mtype);
      IncrementSymbolCount(hnd->name);
     }
   ReturnExpression(theEnv,hndParams);

   hnd->minParams = min;
   hnd->maxParams = max;
   hnd->localVarCount = lvars;
   hnd->actions = actions;
   ExpressionInstall(theEnv,hnd->actions);
#if DEBUGGING_FUNCTIONS

   /* ===================================================
      Old handler trace status is automatically preserved
      =================================================== */
   if (EnvGetConserveMemory(theEnv) == FALSE)
     hnd->ppForm = CopyPPBuffer(theEnv);
   else
#endif
     hnd->ppForm = NULL;
   return(FALSE);
  }
/*!
 * \brief Move joints synchronous
 *
 * Adjusting velocity of all joints to reach the final angules at the same time
 */
bool PowerCubeCtrl::MoveJointSpaceSync(const std::vector<double>& target)
{
	PCTRL_CHECK_INITIALIZED();
	unsigned int DOF = m_params->GetDOF();

	std::vector<std::string> errorMessages;
	PC_CTRL_STATUS status;
	getStatus(status, errorMessages);
	if ((status != PC_CTRL_OK))
	{
		m_ErrorMessage.assign("");
		for (unsigned int i = 0; i < DOF; i++)
		{
			m_ErrorMessage.append(errorMessages[i]);
		}
		return false;
	}

	std::vector<double> vel(DOF);
	std::vector<double> acc(DOF);

	double TG = 0;

	try
	{
		/// calculate which joint takes the longest time to reach goal
		std::vector<double> times(DOF);
		for (unsigned int i = 0; i < DOF; i++)
		{
			RampCommand rm(m_positions[i], m_velocities[i], target[i], m_params->GetMaxAcc()[i],
						   m_params->GetMaxVel()[i]);
			times[i] = rm.getTotalTime();
		}

		/// determine the joint index that has the greatest value for time
		int furthest = 0;
		double max = times[0];
		for (unsigned int i = 1; i < DOF; i++)
		{
			if (times[i] > max)
			{
				max = times[i];
				furthest = i;
			}
		}

		RampCommand rm_furthest(m_positions[furthest], m_velocities[furthest], target[furthest],
                                m_params->GetMaxAcc()[furthest], m_params->GetMaxVel()[furthest]);

		double T1 = rm_furthest.T1();
		double T2 = rm_furthest.T2();
		double T3 = rm_furthest.T3();

		/// total time:
		TG = T1 + T2 + T3;

		/// calculate velocity and acceleration for all joints:
		acc[furthest] = m_params->GetMaxAcc()[furthest];
		vel[furthest] = m_params->GetMaxVel()[furthest];
		for (unsigned int i = 0; i < DOF; i++)
		{
			if (int(i) != furthest)
			{
				double a;
				double v;
				RampCommand::calculateAV(m_positions[i], m_velocities[i], target[i], TG, T3, m_params->GetMaxAcc()[i],
										 m_params->GetMaxVel()[i], a, v);

				acc[i] = a;
				vel[i] = v;
			}
		}
	}
	catch (...)
	{
		return false;
	}

	/// Send motion commands to hardware
	for (unsigned int i = 0; i < DOF; i++)
	{
		pthread_mutex_lock(&m_mutex);
		PCube_moveRamp(m_DeviceHandle, m_params->GetModuleIDs()[i], target[i], fabs(vel[i]), fabs(acc[i]));
		pthread_mutex_unlock(&m_mutex);
	}

	pthread_mutex_lock(&m_mutex);
	PCube_startMotionAll(m_DeviceHandle);
	pthread_mutex_unlock(&m_mutex);

	return true;
}
Exemplo n.º 22
0
void ServerNetworkHandler::inMessage(std::string pMessage, int pSocket){
	pMessage = Tokenizer::cleanEntry(pMessage);
	std::string command = Tokenizer::getCommandSpace(pMessage, 1);
	if (_sessionID == -1 && command != "connect" && command != "adduser"){
		outMessage("?Error: No se ha inciado sesión\n", pSocket);
	} else {

		std::string param = Tokenizer::getParameters(pMessage);
		std::cout<<param<<std::endl;
		if (command == "get"){
			get(param, pSocket);

		} else if (command == "cd"){
			cd(param, pSocket);
		
		} else if (command == "rm"){
			rm(param, pSocket);

		} else if (command == "touch"){
			touch(param, pSocket);

		} else if (command == "connect"){
			connect(param, pSocket);

		} else if (command == "mkdir"){
			mkdir(param, pSocket);

		} else if (command == "adduser"){
			adduser(param, pSocket);

		} else if (command == "openfile"){
			openfile(param, pSocket);

		} else if (command == "appendReg"){
			appendReg(param, pSocket);

		} else if (command == "delReg"){

			if (param == ""){
				delActualReg(pSocket);
			} else {
				delReg(param, pSocket);
			}
		
		} else if (command == "write"){
			write(param, pSocket);
		
		} else if (command == "seek"){
			seek(param, pSocket);
		
		} else if (command == "addReg"){
			addReg(param, pSocket);
		
		} else if (command == "read"){

			if (param == ""){
				readActual(pSocket);
			} else {
				readRegister(param, pSocket);
			}

		} else if (command == "close"){
			close(pSocket);
		} else if (command == "consoleMode"){
			consoleMode(param, pSocket);
		} else {
			outMessage("?Error: No se ha encontrado la instrucción " + command + '\n', pSocket);
		}
		consoleUI(pSocket);
	}
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
	int i;
	char mode[1];
	char name[13];
	char operation[6];
	working_directory=(char*)malloc(200*sizeof(char));
	parent_directory=(char*)malloc(200*sizeof(char));
	
	number_opened_file=0;
	number_read_file= 0;
	number_write_file= 0;
	for (i=0; i<100; i++){
		opened_file[i]=0;
		opened_read_file[i] = 0;
		opened_write_file[i] = 0;
	}
	
	if (argc == 2)
	{
		if (f = fopen(argv[1], "rb+"))
		{
			fread(&BS_BPB, sizeof(struct BS_BPB), 1, f);
			image_name=argv[1];
			
			working_directory[0]='/';
			working_directory[1]='\0';
			current_cluster=BS_BPB.RootClus;
			
			parent_directory[0]='\0';
			parent_cluster=-1;
			
			while(1)
			{
				printf("%s:%s>", image_name, working_directory);
				scanf("%s",operation);
				if (strcmp(operation, "info")==0)
					info();
				else if (strcmp(operation, "ls")==0)
					ls();
				else if (strcmp(operation, "cd")==0)
				{
					scanf("%s", name);
					getchar();
					cd(name);
				}
				else if (strcmp(operation, "touch")==0)
				{
					scanf("%s", name);
					getchar();
					touch(name);
				}
				/*else if (strcmp(operation, "size")==0)
					size();*/
				else if (strcmp(operation, "fopen")==0)
				{
					scanf("%s", name);
					scanf("%s", mode);
					getchar();
					openfile(name, mode);
				}
				else if (strcmp(operation, "fclose")==0)
				{
					scanf("%s", name);
					getchar();
					closefile(name);
				}
				/*else if (strcmp(operation, "fread")==0)
					readfile();
				else if (strcmp(operation, "fwrite")==0)
					writefile();*/
				else if (strcmp(operation, "rm")==0)
				{
					scanf("%s", name);
					getchar();
					rm(name);
				}
				else if (strcmp(operation, "mkdir")==0)
				{
					scanf("%s", name);
					getchar();
					mkdir(name);
				}
				else if (strcmp(operation, "rmdir")==0)
				{
					scanf("%s", name);
					getchar();
					rmdir(name);
				}
				else if (strcmp(operation, "exit")==0)
				{
					fclose(f);
					break;
				}
				else
					printf("Argument not correct\n");
				
			}
			return 0;
		}
		else
		{
			printf("Image not found!\n");
			return -1;
		}
	}
	else
	{
		printf("Arguments not correct!\n");
		return -1;
	}
}
Exemplo n.º 24
0
bool test_cont_values_of_edge_fns(Mesh *mesh, Facet::Key fid, int pos0, int pos1, Shapeset *shapeset) {
    _F_
    Facet *facet = mesh->facets[fid];
    Quad3D *quad = get_quadrature(MODE);

    Element *h[2] = {
        mesh->elements[facet->left],
        mesh->elements[facet->right]
    };

    // local number of edges on the face
    const int *face_edges[] = {
        h[0]->get_face_edges(facet->left_face_num),
        h[1]->get_face_edges(facet->right_face_num)
    };

    // orientations of edges on the face
    int edge_ori[2][4];
    for (int i = 0; i < 4; i++) {
        edge_ori[0][i] = h[0]->get_edge_orientation(face_edges[0][i]);
        edge_ori[1][i] = h[1]->get_edge_orientation(face_edges[1][i]);
    }

    RefMap rm(mesh);
    Pts epts[2];

    // get coordinates of the point in the middle of an edge on the face
    // it is used to find matching edges
    int enp = Quad::NUM_EDGES;
    for (int i = 0; i < 2; i++) {
        QuadPt3D *pt = new QuadPt3D[Quad::NUM_EDGES];
        for (int j = 0; j < enp; j++) {
            const int *edge_vtx = RefHex::get_edge_vertices(face_edges[i][j]);
            QuadPt3D *rd_vtx_pt = quad->get_vertex_points();
            pt[j].x = (rd_vtx_pt[edge_vtx[0]].x + rd_vtx_pt[edge_vtx[1]].x) / 2.0;
            pt[j].y = (rd_vtx_pt[edge_vtx[0]].y + rd_vtx_pt[edge_vtx[1]].y) / 2.0;
            pt[j].z = (rd_vtx_pt[edge_vtx[0]].z + rd_vtx_pt[edge_vtx[1]].z) / 2.0;
        }

        rm.set_active_element(h[i]);

        epts[i].ref_pt = pt;
        epts[i].phys_x = rm.get_phys_x(enp, pt);
        epts[i].phys_y = rm.get_phys_y(enp, pt);
        epts[i].phys_z = rm.get_phys_z(enp, pt);

        // sort points by physical coordinates
        epts[i].sort = new int [enp];
        for (int j = 0; j < enp; j++)
            epts[i].sort[j] = j;
        sort_pts = epts + i;
        qsort(epts[i].sort, enp, sizeof(int), compare);
    }

    // we know which edge correspond to each other, since we sorted them by their phys. coordinates
    // we use it for comparing matching edge functions

    // obtain coordinates where edge functions are going to be evaluated
    Pts fpts[2];
    Ord2 face_ord = quad->get_face_max_order(facet->left_face_num);
    int np = quad->get_face_num_points(facet->left_face_num, face_ord);

    QuadPt3D *pt[2] = {
        quad->get_face_points(facet->left_face_num, face_ord),
        quad->get_face_points(facet->right_face_num, face_ord)
    };

    // transform the coorinates so we can compare them
    for (int i = 0; i < 2; i++) {
        rm.set_active_element(h[i]);

        fpts[i].ref_pt = pt[i];
        fpts[i].phys_x = rm.get_phys_x(np, pt[i]);
        fpts[i].phys_y = rm.get_phys_y(np, pt[i]);
        fpts[i].phys_z = rm.get_phys_z(np, pt[i]);

        // sort points by physical coordinates
        fpts[i].sort = new int [np];
        for (int j = 0; j < np; j++)
            fpts[i].sort[j] = j;
        sort_pts = fpts + i;
        qsort(fpts[i].sort, np, sizeof(int), compare);
    }

    // loop through edges
    for (int k = 0; k < Quad::NUM_EDGES; k++) {
        int i1 = epts[0].sort[k];
        int i2 = epts[1].sort[k];

        // loop through edge functions
        // get all face functions on the face
        Ord1 order(H3D_MAX_ELEMENT_ORDER);
        int *edge_fn[] = {
            shapeset->get_edge_indices(face_edges[0][i1], edge_ori[0][i1], order),
            shapeset->get_edge_indices(face_edges[1][i2], edge_ori[1][i2], order)
        };

        // loop through face functions
        int n_edge_fns = shapeset->get_num_edge_fns(order);
        for (int ifn = 0; ifn < n_edge_fns; ifn++) {
            // get values of edge functions
            double *uval0 = new double[np];
            double *uval1 = new double[np];
            double *uval2 = new double[np];
            shapeset->get_fn_values(edge_fn[0][ifn], np, pt[0], 0, uval0);
            shapeset->get_fn_values(edge_fn[0][ifn], np, pt[0], 1, uval1);
            shapeset->get_fn_values(edge_fn[0][ifn], np, pt[0], 2, uval2);

            double *vval0 = new double[np];
            double *vval1 = new double[np];
            double *vval2 = new double[np];
            shapeset->get_fn_values(edge_fn[1][ifn], np, pt[1], 0, vval0);
            shapeset->get_fn_values(edge_fn[1][ifn], np, pt[1], 1, vval1);
            shapeset->get_fn_values(edge_fn[1][ifn], np, pt[1], 2, vval2);

            // compare their values
            for (int i = 0; i < np; i++) {
                int j1 = fpts[0].sort[i];
                int j2 = fpts[1].sort[i];

                if ((fabs(uval0[j1] - vval0[j2]) > EPS) && (fabs(uval1[j1] - vval1[j2]) > EPS) && (fabs(uval2[j1] - vval2[j2]) > EPS)) {
                    printf("failed\n");
                    warning("Edge fn not continuous @(% lf, % lf, % lf), diff = (% e, % e, % e)",
                            fpts[0].ref_pt[j1].x, fpts[0].ref_pt[j1].y, fpts[0].ref_pt[j1].z,
                            fabs(uval0[j1] - vval0[j2]), fabs(uval1[j1] - vval1[j2]), fabs(uval2[j1] - vval2[j2]));
                    return false;
                }
            }
        }
    }

    // free memory
    for (int i = 0; i < 2; i++) {
        delete [] epts[i].ref_pt;
        delete [] epts[i].phys_x;
        delete [] epts[i].phys_y;
        delete [] epts[i].phys_z;
        delete [] epts[i].sort;

        delete [] fpts[i].phys_x;
        delete [] fpts[i].phys_y;
        delete [] fpts[i].phys_z;
        delete [] fpts[i].sort;
    }

    return true;
}
Exemplo n.º 25
0
/***************************************************
  NAME         : DeallocateMarkedHandlers
  DESCRIPTION  : Removes any handlers from a class
                   that have been previously marked
                   for deletion.
  INPUTS       : The class
  RETURNS      : Nothing useful
  SIDE EFFECTS : Marked handlers are deleted
  NOTES        : Assumes none of the handlers are
                   currently executing or have a
                   busy count != 0 for any reason
 ***************************************************/
globle void DeallocateMarkedHandlers(
  void *theEnv,
  EXEC_STATUS,
  DEFCLASS *cls)
  {
   short count;
   HANDLER *hnd,*nhnd;
   unsigned *arr,*narr;
   long i,j;

   for (i = 0 , count = 0 ; i < cls->handlerCount ; i++)
     {
      hnd = &cls->handlers[i];
      if (hnd->mark == 1)
        {
         count++;
         DecrementSymbolCount(theEnv,execStatus,hnd->name);
         ExpressionDeinstall(theEnv,execStatus,hnd->actions);
         ReturnPackedExpression(theEnv,execStatus,hnd->actions);
         ClearUserDataList(theEnv,execStatus,hnd->usrData);
         if (hnd->ppForm != NULL)
           rm(theEnv,execStatus,(void *) hnd->ppForm,
              (sizeof(char) * (strlen(hnd->ppForm)+1)));
        }
      else
         /* ============================================
            Use the busy field to count how many
            message-handlers are removed before this one
            ============================================ */
        hnd->busy = count;
     }
   if (count == 0)
     return;
   if (count == cls->handlerCount)
     {
      rm(theEnv,execStatus,(void *) cls->handlers,(sizeof(HANDLER) * cls->handlerCount));
      rm(theEnv,execStatus,(void *) cls->handlerOrderMap,(sizeof(unsigned) * cls->handlerCount));
      cls->handlers = NULL;
      cls->handlerOrderMap = NULL;
      cls->handlerCount = 0;
     }
   else
     {
      count = (short) (cls->handlerCount - count);
      hnd = cls->handlers;
      arr = cls->handlerOrderMap;
      nhnd = (HANDLER *) gm2(theEnv,execStatus,(sizeof(HANDLER) * count));
      narr = (unsigned *) gm2(theEnv,execStatus,(sizeof(unsigned) * count));
      for (i = 0 , j = 0 ; j < count ; i++)
        {
         if (hnd[arr[i]].mark == 0)
           {
            /* ==============================================================
               The offsets in the map need to be decremented by the number of
               preceding nodes which were deleted.  Use the value of the busy
               field set in the first loop.
               ============================================================== */
            narr[j] = arr[i] - hnd[arr[i]].busy;
            j++;
           }
        }
      for (i = 0 , j = 0 ; j < count ; i++)
        {
         if (hnd[i].mark == 0)
           {
            hnd[i].busy = 0;
            GenCopyMemory(HANDLER,1,&nhnd[j],&hnd[i]);
            j++;
           }
        }
      rm(theEnv,execStatus,(void *) hnd,(sizeof(HANDLER) * cls->handlerCount));
      rm(theEnv,execStatus,(void *) arr,(sizeof(unsigned) * cls->handlerCount));
      cls->handlers = nhnd;
      cls->handlerOrderMap = narr;
      cls->handlerCount = count;
     }
  }
Exemplo n.º 26
0
bool test_cont_values_of_face_fns(Mesh *mesh, Facet::Key fid, int pos0, int pos1, Shapeset *shapeset) {
    _F_
    Quad3D *quad = get_quadrature(MODE);
    Facet *facet = mesh->facets[fid];

    Element *h[2] = {
        mesh->elements[facet->left],
        mesh->elements[facet->right]
    };

    int face_ori[2] = {
        h[0]->get_face_orientation(facet->left_face_num),
        h[1]->get_face_orientation(facet->right_face_num)
    };

    RefMap rm(mesh);

    // get points where the functions are going to be evaluated
    Pts fpts[2];
    Ord2 face_ord = quad->get_face_max_order(facet->left_face_num);
    int np = quad->get_face_num_points(facet->left_face_num, face_ord);

    QuadPt3D *pt[2] = {
        quad->get_face_points(facet->left_face_num, face_ord),
        quad->get_face_points(facet->right_face_num, face_ord)
    };

    // transform points and sort them
    for (int i = 0; i < 2; i++) {
        rm.set_active_element(h[i]);

        fpts[i].ref_pt = pt[i];
        fpts[i].phys_x = rm.get_phys_x(np, pt[i]);
        fpts[i].phys_y = rm.get_phys_y(np, pt[i]);
        fpts[i].phys_z = rm.get_phys_z(np, pt[i]);

        // sort points by physical coordinates
        fpts[i].sort = new int [np];
        for (int j = 0; j < np; j++)
            fpts[i].sort[j] = j;
        sort_pts = fpts + i;
        qsort(fpts[i].sort, np, sizeof(int), compare);
    }

    // get all face functions on the face
    Ord2 order(H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER);
    int *face_fn[] = {
        shapeset->get_face_indices(facet->left_face_num, face_ori[0], order),
        shapeset->get_face_indices(facet->right_face_num, face_ori[1], order)
    };

    // loop through face functions
    int n_face_fns = shapeset->get_num_face_fns(order);
    for (int ifn = 0; ifn < n_face_fns; ifn++) {
        // evaluate functions
        double *uval0 = new double[np];
        double *uval1 = new double[np];
        double *uval2 = new double[np];
        shapeset->get_fn_values(face_fn[0][ifn], np, pt[0], 0, uval0);
        shapeset->get_fn_values(face_fn[0][ifn], np, pt[0], 1, uval1);
        shapeset->get_fn_values(face_fn[0][ifn], np, pt[0], 2, uval2);
        double *vval0 = new double[np];
        double *vval1 = new double[np];
        double *vval2 = new double[np];
        shapeset->get_fn_values(face_fn[1][ifn], np, pt[1], 0, vval0);
        shapeset->get_fn_values(face_fn[1][ifn], np, pt[1], 1, vval1);
        shapeset->get_fn_values(face_fn[1][ifn], np, pt[1], 2, vval2);

        // compare
        for (int i = 0; i < np; i++) {
            int j1 = fpts[0].sort[i];
            int j2 = fpts[1].sort[i];

            if ((fabs(uval0[j1] - vval0[j2]) > EPS) && (fabs(uval1[j1] - vval1[j2]) > EPS) && (fabs(uval2[j1] - vval2[j2]) > EPS)) {
                printf("failed\n");
                warning("Face fn not continuous @(% lf, % lf, % lf), diff = (% e, % e, % e)",
                        fpts[0].ref_pt[j1].x, fpts[0].ref_pt[j1].y, fpts[0].ref_pt[j1].z,
                        fabs(uval0[j1] - vval0[j2]), fabs(uval1[j1] - vval1[j2]), fabs(uval2[j1] - vval2[j2]));
                return false;
            }
        }
    }

    for (int i = 0; i < 2; i++) {
        delete [] fpts[i].phys_x;
        delete [] fpts[i].phys_y;
        delete [] fpts[i].phys_z;
        delete [] fpts[i].sort;
    }

    return true;
}
Exemplo n.º 27
0
/*
 * Set up the input pointers while copying the mail file into /tmp.
 */
void
setptr(FILE *ibuf, off_t offset)
{
	int c, count;
	char *cp, *cp2;
	struct message this;
	FILE *mestmp;
	int maybe, inhead;
	char linebuf[LINESIZE], pathbuf[PATHSIZE];
	int omsgCount;

	/* Get temporary file. */
	(void)snprintf(pathbuf, sizeof(pathbuf), "%s/mail.XXXXXXXXXX", tmpdir);
	if ((c = mkstemp(pathbuf)) == -1 || (mestmp = Fdopen(c, "r+")) == NULL)
		err(1, "can't open %s", pathbuf);
	(void)rm(pathbuf);

	if (offset == 0) {
		 msgCount = 0;
	} else {
		/* Seek into the file to get to the new messages */
		(void)fseeko(ibuf, offset, SEEK_SET);
		/*
		 * We need to make "offset" a pointer to the end of
		 * the temp file that has the copy of the mail file.
		 * If any messages have been edited, this will be
		 * different from the offset into the mail file.
		 */
		(void)fseeko(otf, (off_t)0, SEEK_END);
		offset = ftello(otf);
	}
	omsgCount = msgCount;
	maybe = 1;
	inhead = 0;
	this.m_flag = MUSED|MNEW;
	this.m_size = 0;
	this.m_lines = 0;
	this.m_block = 0;
	this.m_offset = 0;
	for (;;) {
		if (fgets(linebuf, sizeof(linebuf), ibuf) == NULL) {
			if (append(&this, mestmp))
				errx(1, "temporary file");
			makemessage(mestmp, omsgCount);
			return;
		}
		count = strlen(linebuf);
		/*
		 * Transforms lines ending in <CR><LF> to just <LF>.
		 * This allows mail to be able to read Eudora mailboxes.
		 */
		if (count >= 2 && linebuf[count - 1] == '\n' &&
		    linebuf[count - 2] == '\r') {
			count--;
			linebuf[count - 1] = '\n';
		}

		(void)fwrite(linebuf, sizeof(*linebuf), count, otf);
		if (ferror(otf))
			errx(1, "/tmp");
		if (count)
			linebuf[count - 1] = '\0';
		if (maybe && linebuf[0] == 'F' && ishead(linebuf)) {
			msgCount++;
			if (append(&this, mestmp))
				errx(1, "temporary file");
			this.m_flag = MUSED|MNEW;
			this.m_size = 0;
			this.m_lines = 0;
			this.m_block = blockof(offset);
			this.m_offset = boffsetof(offset);
			inhead = 1;
		} else if (linebuf[0] == 0) {
			inhead = 0;
		} else if (inhead) {
			for (cp = linebuf, cp2 = "status";; cp++) {
				if ((c = *cp2++) == '\0') {
					while (isspace((unsigned char)*cp++))
						;
					if (cp[-1] != ':')
						break;
					while ((c = *cp++) != '\0')
						if (c == 'R')
							this.m_flag |= MREAD;
						else if (c == 'O')
							this.m_flag &= ~MNEW;
					inhead = 0;
					break;
				}
				if (*cp != c && *cp != toupper((unsigned char)c))
					break;
			}
		}
		offset += count;
		this.m_size += count;
		this.m_lines++;
		maybe = linebuf[0] == 0;
	}
}
Exemplo n.º 28
0
globle SYMBOL_HN *ExtractConstructName(
  void *theEnv,
  EXEC_STATUS,
  unsigned thePosition,
  char *theString)
  {
   size_t theLength;
   char *newString;
   SYMBOL_HN *returnValue;

   /*======================================*/
   /* Just return the string if it doesn't */
   /* contain the :: symbol.               */
   /*======================================*/

   if (thePosition == 0) return((SYMBOL_HN *) EnvAddSymbol(theEnv,execStatus,theString));

   /*=====================================*/
   /* Determine the length of the string. */
   /*=====================================*/

   theLength = strlen(theString);

   /*=================================================*/
   /* Return NULL if the :: is at the very end of the */
   /* string (and thus there is no construct name).   */
   /*=================================================*/

   if (theLength <= (thePosition + 1)) return(NULL);

   /*====================================*/
   /* Allocate a temporary string large  */
   /* enough to hold the construct name. */
   /*====================================*/

   newString = (char *) gm2(theEnv,execStatus,theLength - thePosition);

   /*================================================*/
   /* Copy the construct name portion of the         */
   /* module/construct name to the temporary string. */
   /*================================================*/

   genstrncpy(newString,&theString[thePosition+1],
           (STD_SIZE) theLength - thePosition);

   /*=============================================*/
   /* Add the construct name to the symbol table. */
   /*=============================================*/

   returnValue = (SYMBOL_HN *) EnvAddSymbol(theEnv,execStatus,newString);

   /*=============================================*/
   /* Return the storage of the temporary string. */
   /*=============================================*/

   rm(theEnv,execStatus,newString,theLength - thePosition);

   /*================================================*/
   /* Return a pointer to the construct name symbol. */
   /*================================================*/

   return(returnValue);
  }
// Install the redefinition of a class --
// The original instanceKlass object (k_h) always represents the latest 
// version of the respective class. However, during class redefinition we swap
// or replace much of its content with that of the instanceKlass object created
// from the bytes of the redefine (k_h_new). Specifically, k_h points to the new
// constantpool and methods objects, which we take from k_h_new. k_h_new, in turn,
// assumes the role of the previous class version, with the old constantpool and
// methods (taken from k_h) attached to it. k_h links to k_h_new to create a 
// linked list of class versions. 
void VM_RedefineClasses::redefine_single_class(jclass j_clazz, instanceKlassHandle k_h_new, TRAPS) {

  oop mirror = JNIHandles::resolve_non_null(j_clazz);
  klassOop k_oop = java_lang_Class::as_klassOop(mirror);
  instanceKlassHandle k_h = instanceKlassHandle(THREAD, k_oop);

  // Remove all breakpoints in methods of this class
  JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
  jvmti_breakpoints.clearall_in_class_at_safepoint(k_oop); 

  // Deoptimize all compiled code that depends on this class
  NOT_CORE(Universe::flush_evol_dependents_on(k_h));

  _old_methods = k_h->methods();
  _new_methods = k_h_new->methods();
  _evolving_koop = k_oop;
  _old_constants = k_h->constants();

  // flush the cached jmethodID fields for _old_methods
  flush_method_jmethod_id_cache();

  // Patch the indexes into the constantpool from the array of fields of the evolving
  // class. This is required, because the layout of the new constantpool can be different,
  // so old indexes corresponding to field names and signatures can become invalid.
  patch_indexes_for_fields(k_h, k_h_new);

  // Make new constantpool object (and methodOops via it) point to the original class object
  k_h_new->constants()->set_pool_holder(k_h());

  // Replace methods and constantpool
  k_h->set_methods(_new_methods);
  k_h_new->set_methods(_old_methods);     // To prevent potential GCing of the old methods, 
                                          // and to be able to undo operation easily.

  constantPoolOop old_constants = k_h->constants();
  k_h->set_constants(k_h_new->constants());
  k_h_new->set_constants(old_constants);  // See the previous comment.

  check_methods_and_mark_as_old();
  transfer_old_native_function_registrations();

  // Replace inner_classes
  typeArrayOop old_inner_classes = k_h->inner_classes();
  k_h->set_inner_classes(k_h_new->inner_classes());
  k_h_new->set_inner_classes(old_inner_classes);

  // Initialize the vtable and interface table after
  // methods have been rewritten
  { ResourceMark rm(THREAD);
  k_h->vtable()->initialize_vtable(THREAD); // No exception can happen here
  k_h->itable()->initialize_itable();
  }

  // Copy the "source file name" attribute from new class version
  k_h->set_source_file_name(k_h_new->source_file_name());

  // Copy the "source debug extension" attribute from new class version
  k_h->set_source_debug_extension(k_h_new->source_debug_extension());

  // Use of javac -g could be different in the old and the new
  if (k_h_new->access_flags().has_localvariable_table() !=
      k_h->access_flags().has_localvariable_table()) {

    AccessFlags flags = k_h->access_flags();
    if (k_h_new->access_flags().has_localvariable_table()) {
      flags.set_has_localvariable_table();
    } else {
      flags.clear_has_localvariable_table();
    }
    k_h->set_access_flags(flags);
  }

  // Replace class annotation fields values
  typeArrayOop old_class_annotations = k_h->class_annotations();
  k_h->set_class_annotations(k_h_new->class_annotations());
  k_h_new->set_class_annotations(old_class_annotations);

  // Replace fields annotation fields values
  objArrayOop old_fields_annotations = k_h->fields_annotations();
  k_h->set_fields_annotations(k_h_new->fields_annotations());
  k_h_new->set_fields_annotations(old_fields_annotations);

  // Replace methods annotation fields values
  objArrayOop old_methods_annotations = k_h->methods_annotations();
  k_h->set_methods_annotations(k_h_new->methods_annotations());
  k_h_new->set_methods_annotations(old_methods_annotations);

  // Replace methods parameter annotation fields values
  objArrayOop old_methods_parameter_annotations = k_h->methods_parameter_annotations();
  k_h->set_methods_parameter_annotations(k_h_new->methods_parameter_annotations());
  k_h_new->set_methods_parameter_annotations(old_methods_parameter_annotations);

  // Replace methods default annotation fields values
  objArrayOop old_methods_default_annotations = k_h->methods_default_annotations();
  k_h->set_methods_default_annotations(k_h_new->methods_default_annotations());
  k_h_new->set_methods_default_annotations(old_methods_default_annotations);

  // Replace major version number of class file
  u2 old_major_version = k_h->major_version();
  k_h->set_major_version(k_h_new->major_version());
  k_h_new->set_major_version(old_major_version);

  // Replace CP indexes for class and name+type of enclosing method
  u2 old_class_idx  = k_h->enclosing_method_class_index();
  u2 old_method_idx = k_h->enclosing_method_method_index();
  k_h->set_enclosing_method_indices(k_h_new->enclosing_method_class_index(),
                                    k_h_new->enclosing_method_method_index());
  k_h_new->set_enclosing_method_indices(old_class_idx, old_method_idx);

  // Maintain a linked list of versions of this class. 
  // List is in ascending age order. Current version (k_h) is the head.
  if (k_h->has_previous_version()) {
    k_h_new->set_previous_version(k_h->previous_version());
  }
  k_h->set_previous_version(k_h_new);

  // Adjust constantpool caches and vtables for all classes
  // that reference methods of the evolved class.
  SystemDictionary::classes_do(adjust_cpool_cache_and_vtable);
  k_h->set_rewritten_by_redefine(true);
}
Exemplo n.º 30
0
int main(int argc, char *argv[]) {
	int i, j, nf;

	progname = argv[0];

	UpdatePaths( progname );

	ac = argc + 50;
	av = alloc(ac*sizeof(char *));
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, interrupt);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, interrupt);
#ifdef SIGHUP
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, interrupt);
#endif
	if (getenv("TMP"))
		tempdir = getenv("TMP");
	else if (getenv("TEMP"))
		tempdir = getenv("TEMP");
	else if (getenv("TMPDIR"))
		tempdir = getenv("TMPDIR");
	assert(tempdir);
	i = strlen(tempdir);
	for (; (i > 0 && tempdir[i-1] == '/') || tempdir[i-1] == '\\'; i--)
		tempdir[i-1] = '\0';
	if (argc <= 1) {
		help();
		exit(0);
	}
	plist = append("-D__LCC__", 0);
	initinputs();
	if (getenv("LCCDIR"))
		option(stringf("-lccdir=%s", getenv("LCCDIR")));
	for (nf = 0, i = j = 1; i < argc; i++) {
		if (strcmp(argv[i], "-o") == 0) {
			if (++i < argc) {
				if (suffix(argv[i], suffixes, 2) >= 0) {
					error("-o would overwrite %s", argv[i]);
					exit(8);
				}
				outfile = argv[i];
				continue;
			} else {
				error("unrecognized option `%s'", argv[i-1]);
				exit(8);
			}
		} else if (strcmp(argv[i], "-target") == 0) {
			if (argv[i+1] && *argv[i+1] != '-')
				i++;
			continue;
		} else if (*argv[i] == '-' && argv[i][1] != 'l') {
			opt(argv[i]);
			continue;
		} else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0)
			nf++;
		argv[j++] = argv[i];
	}
	if ((cflag || Sflag) && outfile && nf != 1) {
		fprintf(stderr, "%s: -o %s ignored\n", progname, outfile);
		outfile = 0;
	}
	argv[j] = 0;
	for (i = 0; include[i]; i++)
		plist = append(include[i], plist);
	if (ilist) {
		List b = ilist;
		do {
			b = b->link;
			plist = append(b->str, plist);
		} while (b != ilist);
	}
	ilist = 0;
	for (i = 1; argv[i]; i++)
		if (*argv[i] == '-')
			opt(argv[i]);
		else {
			char *name = exists(argv[i]);
			if (name) {
				if (strcmp(name, argv[i]) != 0
				|| (nf > 1 && suffix(name, suffixes, 3) >= 0))
					fprintf(stderr, "%s:\n", name);
				filename(name, 0);
			} else
				error("can't find `%s'", argv[i]);
		}
	if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) {
		compose(ld, llist[0], llist[1],
			append(outfile ? outfile : concat("a", first(suffixes[4])), 0));
		if (callsys(av))
			errcnt++;
	}
	rm(rmlist);	
	return errcnt ? EXIT_FAILURE : EXIT_SUCCESS;
}