Ejemplo n.º 1
0
Settings::Settings()
	:
	fMessage(kMsgDiskProbeSettings),
	fUpdated(false)
{
	float fontSize = be_plain_font->Size();
	int32 windowWidth = DataView::WidthForFontSize(fontSize) + 20;
		// TODO: make scrollbar width variable

	BScreen screen;
	fMessage.AddRect("window_frame", BLayoutUtils::AlignInFrame(screen.Frame(),
		BSize(windowWidth, windowWidth),
		BAlignment(B_ALIGN_HORIZONTAL_CENTER, B_ALIGN_VERTICAL_CENTER)));
	fMessage.AddInt32("base_type", kHexBase);
	fMessage.AddFloat("font_size", fontSize);
	fMessage.AddBool("case_sensitive", true);
	fMessage.AddInt8("find_mode", kAsciiMode);

	BFile file;
	if (Open(&file, B_READ_ONLY) != B_OK)
		return;

	// TODO: load/save settings as flattened BMessage - but not yet,
	//		since that will break compatibility with R5's DiskProbe

	disk_probe_settings settings;
	if (file.Read(&settings, sizeof(settings)) == sizeof(settings)) {
#if B_HOST_IS_BENDIAN
		// settings are saved in little endian
		settings.window_frame.left = B_LENDIAN_TO_HOST_FLOAT(
			settings.window_frame.left);
		settings.window_frame.top = B_LENDIAN_TO_HOST_FLOAT(
			settings.window_frame.top);
		settings.window_frame.right = B_LENDIAN_TO_HOST_FLOAT(
			settings.window_frame.right);
		settings.window_frame.bottom = B_LENDIAN_TO_HOST_FLOAT(
			settings.window_frame.bottom);
#endif
		// check if the window frame is on screen at all
		BScreen screen;
		if (screen.Frame().Contains(settings.window_frame.LeftTop())
			&& settings.window_frame.Width() < screen.Frame().Width()
			&& settings.window_frame.Height() < screen.Frame().Height())
			fMessage.ReplaceRect("window_frame", settings.window_frame);

		if (settings.base_type == kHexBase
			|| settings.base_type == kDecimalBase)
			fMessage.ReplaceInt32("base_type",
				B_LENDIAN_TO_HOST_INT32(settings.base_type));
		if (settings.font_size >= 0 && settings.font_size <= 72)
			fMessage.ReplaceFloat("font_size",
				float(B_LENDIAN_TO_HOST_INT32(settings.font_size)));

		fMessage.ReplaceBool("case_sensitive",
			settings.flags & kCaseSensitive);
		fMessage.ReplaceInt8("find_mode",
			settings.flags & kHexFindMode ? kHexMode : kAsciiMode);
	}
}
Ejemplo n.º 2
0
void MesaDriver::ClearBack(GLcontext *ctx,
                        GLboolean all, GLint x, GLint y,
                        GLint width, GLint height)
{
   MesaDriver *md = (MesaDriver *) ctx->DriverCtx;
   BGLView *bglview = md->m_bglview;
   assert(bglview);
   BBitmap *bitmap = md->m_bitmap;
   assert(bitmap);
   GLuint *start = (GLuint *) bitmap->Bits();
   const GLuint *clearPixelPtr = (const GLuint *) md->m_clear_color;
   const GLuint clearPixel = B_LENDIAN_TO_HOST_INT32(*clearPixelPtr);

   if (all) {
      const int numPixels = md->m_width * md->m_height;
      if (clearPixel == 0) {
         memset(start, 0, numPixels * 4);
      }
      else {
         for (int i = 0; i < numPixels; i++) {
             start[i] = clearPixel;
         }
      }
   }
   else {
      // XXX untested
      start += y * md->m_width + x;
      for (int i = 0; i < height; i++) {
         for (int j = 0; j < width; j++) {
            start[j] = clearPixel;
         }
         start += md->m_width;
      }
   }
}
Ejemplo n.º 3
0
void WAVEAtom::OnProcessMetaData()
{
	// This should be in LITTLE ENDIAN DATA
	theStream->Read(&theWaveFormat.format_tag,sizeof(uint16));
	theStream->Read(&theWaveFormat.channels,sizeof(uint16));
	theStream->Read(&theWaveFormat.frames_per_sec,sizeof(uint32));
	theStream->Read(&theWaveFormat.avg_bytes_per_sec,sizeof(uint32));
	theStream->Read(&theWaveFormat.block_align,sizeof(uint16));
	theStream->Read(&theWaveFormat.bits_per_sample,sizeof(uint16));
	theStream->Read(&theWaveFormat.extra_size,sizeof(uint16));

	theWaveFormat.format_tag = B_LENDIAN_TO_HOST_INT16(theWaveFormat.format_tag);
	theWaveFormat.channels = B_LENDIAN_TO_HOST_INT16(theWaveFormat.channels);
	theWaveFormat.frames_per_sec = B_LENDIAN_TO_HOST_INT32(theWaveFormat.frames_per_sec);
	theWaveFormat.avg_bytes_per_sec = B_LENDIAN_TO_HOST_INT32(theWaveFormat.avg_bytes_per_sec);
	theWaveFormat.block_align = B_LENDIAN_TO_HOST_INT16(theWaveFormat.block_align);
	theWaveFormat.bits_per_sample = B_LENDIAN_TO_HOST_INT16(theWaveFormat.bits_per_sample);
	theWaveFormat.extra_size = B_LENDIAN_TO_HOST_INT16(theWaveFormat.extra_size);
}
Ejemplo n.º 4
0
const char *
Header::_PrintGUID(const guid_t &id)
{
	static char guid[48];
	snprintf(guid, sizeof(guid),
		"%08" B_PRIx32 "-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
		B_LENDIAN_TO_HOST_INT32(id.data1), B_LENDIAN_TO_HOST_INT16(id.data2),
		B_LENDIAN_TO_HOST_INT16(id.data3), id.data4[0], id.data4[1],
		id.data4[2], id.data4[3], id.data4[4], id.data4[5], id.data4[6],
		id.data4[7]);
	return guid;
}
Ejemplo n.º 5
0
static void
decode_vendor(edid1_vendor *vendor, const edid1_vendor_raw *raw)
{
	vendor->manufacturer[0] = raw->c1 + '@';
	vendor->manufacturer[1] = ((raw->c2_high << 3) | raw->c2_low) + '@';
	vendor->manufacturer[2] = raw->c3 + '@';
	vendor->manufacturer[3] = 0;
	vendor->prod_id = B_LENDIAN_TO_HOST_INT16(raw->prod_id);
	vendor->serial = B_LENDIAN_TO_HOST_INT32(raw->serial);
	vendor->week = raw->week;
	vendor->year = raw->year + 1990;
}
Ejemplo n.º 6
0
static void
prep_infoblock(ide_device_info *device)
{
	ide_device_infoblock *infoblock = &device->infoblock;

	B_BENDIAN_TO_HOST_MULTI((uint16 *)infoblock->serial_number, 
		sizeof(infoblock->serial_number) / 2);

	B_BENDIAN_TO_HOST_MULTI( (uint16 *)infoblock->firmware_version, 
		sizeof(infoblock->firmware_version) / 2);

	B_BENDIAN_TO_HOST_MULTI( (uint16 *)infoblock->model_number, 
		sizeof(infoblock->model_number) / 2);

	infoblock->LBA_total_sectors = B_LENDIAN_TO_HOST_INT32(infoblock->LBA_total_sectors);
	infoblock->LBA48_total_sectors = B_LENDIAN_TO_HOST_INT64(infoblock->LBA48_total_sectors);
}
Ejemplo n.º 7
0
int32 PacketizedProxyDataIO :: Read(void * buffer, uint32 size)
{
   int32 ret = 0;

   if (_inputBufferSizeBytesRead < sizeof(uint32))
   {
      uint8 * ip = (uint8 *) &_inputBufferSize;
      const int32 numSizeBytesRead = ProxyDataIO::Read(&ip[_inputBufferSizeBytesRead], sizeof(uint32)-_inputBufferSizeBytesRead);
      if (numSizeBytesRead < 0) return -1;
      _inputBufferSizeBytesRead += numSizeBytesRead;
      if (_inputBufferSizeBytesRead == sizeof(uint32))
      {
         _inputBufferSize = B_LENDIAN_TO_HOST_INT32(_inputBufferSize);
         if (_inputBufferSize > _maxTransferUnit)
         {
            LogTime(MUSCLE_LOG_ERROR, "PacketizedProxyDataIO:  Error, incoming packet with size " UINT32_FORMAT_SPEC ", max transfer unit is set to " UINT32_FORMAT_SPEC "\n", _inputBufferSize, _maxTransferUnit);
            return -1;
         }
         if (_inputBuffer.SetNumBytes(_inputBufferSize, false) != B_NO_ERROR) return -1;
         _inputBufferBytesRead = 0;

         // Special case for empty packets
         if (_inputBufferSize == 0) _inputBufferSizeBytesRead = 0;
      }
   }

   const uint32 inBufSize = _inputBuffer.GetNumBytes();
   if ((_inputBufferSizeBytesRead == sizeof(uint32))&&(_inputBufferBytesRead < inBufSize))
   {
      const int32 numBytesRead = ProxyDataIO::Read(_inputBuffer.GetBuffer()+_inputBufferBytesRead, inBufSize-_inputBufferBytesRead);
      if (numBytesRead < 0) return -1;

      _inputBufferBytesRead += numBytesRead;
      if (_inputBufferBytesRead == inBufSize)
      {
         const uint32 copyBytes = muscleMin(size, inBufSize);
         if (size < inBufSize) LogTime(MUSCLE_LOG_WARNING, "PacketizedProxyDataIO:  Truncating incoming packet (" UINT32_FORMAT_SPEC " bytes available, only " UINT32_FORMAT_SPEC " bytes in user buffer)\n", inBufSize, size);
         memcpy(buffer, _inputBuffer.GetBuffer(), copyBytes);
         ret = copyBytes;

         _inputBufferSizeBytesRead = _inputBufferBytesRead = 0;
         _inputBuffer.Clear(inBufSize>(64*1024));  // free up memory after a large packet recv
      }
   }
   return ret;
}
void
MesaSoftwareRenderer::_ClearFront(gl_context* ctx)
{
	CALLED();

	MesaSoftwareRenderer* mr = (MesaSoftwareRenderer*)ctx->DriverCtx;
	BGLView* bglview = mr->GLView();
	assert(bglview);
	BBitmap* bitmap = mr->fBitmap;
	assert(bitmap);
	GLuint* start = (GLuint*)bitmap->Bits();
	size_t pixelSize = 0;
	get_pixel_size_for(bitmap->ColorSpace(), &pixelSize, NULL, NULL);
	const GLuint* clearPixelPtr = (const GLuint*)mr->fClearColor;
	const GLuint clearPixel = B_LENDIAN_TO_HOST_INT32(*clearPixelPtr);

	int x = ctx->DrawBuffer->_Xmin;
	int y = ctx->DrawBuffer->_Ymin;
	uint32 width = ctx->DrawBuffer->_Xmax - x;
	uint32 height = ctx->DrawBuffer->_Ymax - y;
	GLboolean all = (width == ctx->DrawBuffer->Width
		&& height == ctx->DrawBuffer->Height);

	if (all) {
		const int numPixels = mr->fWidth * mr->fHeight;
		if (clearPixel == 0) {
			memset(start, 0, numPixels * pixelSize);
		} else {
			for (int i = 0; i < numPixels; i++) {
				start[i] = clearPixel;
			}
		}
	} else {
		// XXX untested
		start += y * mr->fWidth + x;
		for (uint32 i = 0; i < height; i++) {
			for (uint32 j = 0; j < width; j++) {
				start[j] = clearPixel;
			}
			start += mr->fWidth;
		}
	}
}
Ejemplo n.º 9
0
status_t MMUnflattenMessage(MMessage * msg, const void * inBuf, uint32 inputBufferBytes)
{
   uint32 i, readOffset = 0;
   const uint8 * buffer = (const uint8 *) inBuf;

   /* Read and check protocol version number */
   uint32 networkByteOrder, numEntries;
   {
      uint32 messageProtocolVersion;
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;

      messageProtocolVersion = B_LENDIAN_TO_HOST_INT32(networkByteOrder);
      if ((messageProtocolVersion < OLDEST_SUPPORTED_PROTOCOL_VERSION)||(messageProtocolVersion > CURRENT_PROTOCOL_VERSION)) return B_ERROR;
   
      /* Read 'what' code */
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;
      msg->what = B_LENDIAN_TO_HOST_INT32(networkByteOrder);

      /* Read number of entries */
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;
      numEntries = B_LENDIAN_TO_HOST_INT32(networkByteOrder);
   }

   MMClearMessage(msg);

   /* Read entries */
   for (i=0; i<numEntries; i++)
   {
      const char * fieldName;
      uint32 nameLength, tc, eLength;
      MMessageField * newField = NULL;
      MBool doAddField = MTrue;
      const uint8 * dataPtr;

      /* Read entry name length */
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;

      nameLength = B_LENDIAN_TO_HOST_INT32(networkByteOrder);
      if (nameLength > inputBufferBytes-readOffset) return B_ERROR;

      /* Read entry name */
      fieldName = (const char *) &buffer[readOffset];
      readOffset += nameLength;

      /* Read entry type code */
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;
      tc = B_LENDIAN_TO_HOST_INT32(networkByteOrder);

      /* Read entry data length */
      if (ReadData(buffer, inputBufferBytes, &readOffset, &networkByteOrder, sizeof(networkByteOrder)) != B_NO_ERROR) return B_ERROR;
      eLength = B_LENDIAN_TO_HOST_INT32(networkByteOrder);
      if (eLength > inputBufferBytes-readOffset) return B_ERROR;
      
      dataPtr = &buffer[readOffset];
      switch(tc)
      {
         case B_BOOL_TYPE:   newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(MBool), sizeof(MBool)); break;
         case B_DOUBLE_TYPE: newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(double),   sizeof(double));   break;
         case B_FLOAT_TYPE:  newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(float),    sizeof(float));    break;
         case B_INT64_TYPE:  newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(int64),    sizeof(int64));    break;
         case B_INT32_TYPE:  newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(int32),    sizeof(int32));    break;
         case B_INT16_TYPE:  newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(int16),    sizeof(int16));    break;
         case B_INT8_TYPE:   newField = ImportMMessageField(fieldName, nameLength, tc, eLength, dataPtr, sizeof(int8),     sizeof(int8));     break;

         case B_MESSAGE_TYPE:
         {
            /* Annoying special case, since this type doesn't contain a number-of-items field,   */
            /* we have to read them in to a temporary linked list and find out how many there are that way */
            MMessage * head = NULL, * tail = NULL;
            uint32 eUsed = 0;
            uint32 eOffset = readOffset;
            uint32 listLength = 0;
            status_t ret = B_NO_ERROR;
            while((eUsed < eLength)&&(ret == B_NO_ERROR))
            {
               uint32 entryLen;
               ret = B_ERROR;  /* go pessimistic for a bit */
               if (ReadData(buffer, inputBufferBytes, &eOffset, &entryLen, sizeof(entryLen)) == B_NO_ERROR)
               {
                  entryLen = B_LENDIAN_TO_HOST_INT32(entryLen);
                  if (eOffset + entryLen <= inputBufferBytes)
                  {
                     MMessage * newMsg = MMAllocMessage(0);
                     if (newMsg)
                     {
                        if (MMUnflattenMessage(newMsg, &buffer[eOffset], entryLen) == B_NO_ERROR)
                        {
                           ret = B_NO_ERROR;
                           eOffset += entryLen;
                           eUsed   += (sizeof(uint32) + entryLen);
                           if (tail) 
                           {
                              tail->scratch = newMsg;
                              tail = newMsg;
                           }
                           else head = tail = newMsg;

                           listLength++;
                        }
                        else MMFreeMessage(newMsg);
                     }
                  }
               }
            }
            if (ret == B_NO_ERROR)
            {
               MMessage ** newMsgField = MMPutMessageField(msg, MFalse, fieldName, listLength);
               if (newMsgField)
               {
                  uint32 i;
                  for (i=0; i<listLength; i++) 
                  {
                     newMsgField[i] = head;
                     head = head->scratch;
                  }
                  doAddField = MFalse;
               }
               else ret = B_ERROR; 
            }
            if (ret != B_NO_ERROR)
            {
               /* Clean up on error */
               while(head)
               {
                  MMessage * next = head->scratch;
                  MMFreeMessage(head);
                  head = next; 
               }
               MMRemoveField(msg, fieldName);
               return B_ERROR;
            }
         }
         break;

         /** Note that this should never really happen since we don't put pointers in flattened messages anymore, but it's here for backwards compatibility
           * with older code that did do that.
           */
         case B_POINTER_TYPE: newField = ImportMMessageField(fieldName, nameLength, B_INT32_TYPE, eLength, dataPtr, sizeof(int32),   sizeof(int32)); break;
         case B_POINT_TYPE:   newField = ImportMMessageField(fieldName, nameLength, tc,           eLength, dataPtr, sizeof(float)*2, sizeof(float)); break;
         case B_RECT_TYPE:    newField = ImportMMessageField(fieldName, nameLength, tc,           eLength, dataPtr, sizeof(float)*4, sizeof(float)); break;

         default: 
         {
            /* All other types get loaded as variable-sized byte buffers */
            uint32 numItems;
            uint32 eOffset = readOffset;
            if (ReadData(buffer, inputBufferBytes, &eOffset, &numItems, sizeof(numItems)) == B_NO_ERROR)
            {
               MByteBuffer ** bufs;
               numItems = B_LENDIAN_TO_HOST_INT32(numItems);
               bufs = PutMMVariableFieldAux(msg, MFalse, tc, fieldName, numItems);
               if (bufs)
               {
                  uint32 eLeft = eLength;
                  uint32 i;

                  doAddField = MFalse;
                  for (i=0; i<numItems; i++)
                  {
                     uint32 itemSize; 
                     MBool ok = MFalse;
                     if (ReadData(buffer, inputBufferBytes, &eOffset, &itemSize, sizeof(itemSize)) == B_NO_ERROR)
                     {
                        itemSize = B_LENDIAN_TO_HOST_INT32(itemSize);
                        if ((itemSize+sizeof(uint32) <= eLeft)&&((bufs[i] = MBAllocByteBuffer(itemSize, MFalse)) != NULL))
                        {
                           eLeft -= (itemSize + sizeof(uint32));
                           memcpy(&bufs[i]->bytes, &buffer[eOffset], itemSize);
                           eOffset += itemSize;
                           ok = true; 
                        }
                     }
                     if (ok == MFalse)
                     {
                        MMRemoveField(msg, fieldName);
                        return B_ERROR;
                     }
                  }
               }
            }
         }
         break;
      }

      if (doAddField)
      {
         if (newField) AddMMessageField(msg, newField);
                  else return B_ERROR;
      }

      readOffset += eLength;
   }
   return B_NO_ERROR;
}
Ejemplo n.º 10
0
int32 PacketTunnelIOGateway :: DoInputImplementation(AbstractGatewayMessageReceiver & receiver, uint32 maxBytes)
{
   if (_inputPacketBuffer.SetNumBytes(_maxTransferUnit, false) != B_NO_ERROR) return -1;

   bool firstTime = true;
   uint32 totalBytesRead = 0;
   while((totalBytesRead < maxBytes)&&((firstTime)||(IsSuggestedTimeSliceExpired() == false)))
   {
      firstTime = false;

      int32 bytesRead = GetDataIO()()->Read(_inputPacketBuffer.GetBuffer(), _inputPacketBuffer.GetNumBytes());
//printf("   READ " INT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC " bytes\n", bytesRead, _inputPacketBuffer.GetNumBytes());
      if (bytesRead > 0)
      {
         totalBytesRead += bytesRead;

         IPAddressAndPort fromIAP;
         const PacketDataIO * packetIO = dynamic_cast<PacketDataIO *>(GetDataIO()());
         if (packetIO) fromIAP = packetIO->GetSourceOfLastReadPacket();

         const uint8 * p = (const uint8 *) _inputPacketBuffer.GetBuffer();
         if ((_allowMiscData)&&((bytesRead < (int32)FRAGMENT_HEADER_SIZE)||(((uint32)B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(p))) != _magic)))
         {
            // If we're allowed to handle miscellaneous data, we'll just pass it on through verbatim
            ByteBuffer temp;
            temp.AdoptBuffer(bytesRead, const_cast<uint8 *>(p));
            HandleIncomingMessage(receiver, ByteBufferRef(&temp, false), fromIAP);
            (void) temp.ReleaseBuffer();
         }
         else
         {
            const uint8 * invalidByte = p+bytesRead;
            while(invalidByte-p >= (int32)FRAGMENT_HEADER_SIZE)
            {
               const uint32 magic     = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[0*sizeof(uint32)]));
               const uint32 sexID     = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[1*sizeof(uint32)]));
               const uint32 messageID = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[2*sizeof(uint32)]));
               const uint32 offset    = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[3*sizeof(uint32)]));
               const uint32 chunkSize = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[4*sizeof(uint32)]));
               const uint32 totalSize = B_LENDIAN_TO_HOST_INT32(muscleCopyIn<uint32>(&p[5*sizeof(uint32)]));
//printf("   PARSE magic=" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC " sex=" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC " messageID=" UINT32_FORMAT_SPEC " offset=" UINT32_FORMAT_SPEC " chunkSize=" UINT32_FORMAT_SPEC " totalSize=" UINT32_FORMAT_SPEC "\n", magic, _magic, sexID, _sexID, messageID, offset, chunkSize, totalSize);

               p += FRAGMENT_HEADER_SIZE;
               if ((magic == _magic)&&((_sexID == 0)||(_sexID != sexID))&&((invalidByte-p >= (int32)chunkSize)&&(totalSize <= _maxIncomingMessageSize)))
               {
                  ReceiveState * rs = _receiveStates.Get(fromIAP);
                  if (rs == NULL)
                  {
                     if (offset == 0) rs = _receiveStates.PutAndGet(fromIAP, ReceiveState(messageID));
                     if (rs)
                     {
                        rs->_buf = GetByteBufferFromPool(totalSize);
                        if (rs->_buf() == NULL)
                        {
                           _receiveStates.Remove(fromIAP);
                           rs = NULL;
                        }
                     }
                  }
                  if (rs)
                  {
                     if ((offset == 0)||(messageID != rs->_messageID))
                     {
                        // A new message... start receiving it (but only if we are starting at the beginning)
                        rs->_messageID = messageID;
                        rs->_offset    = 0;
                        rs->_buf()->SetNumBytes(totalSize, false);
                     }

                     uint32 rsSize = rs->_buf()->GetNumBytes();
//printf("  CHECK:  offset=" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC " %s\n", offset, rs->_offset, (offset==rs->_offset)?"":"DISCONTINUITY!!!");
                     if ((messageID == rs->_messageID)&&(totalSize == rsSize)&&(offset == rs->_offset)&&(offset+chunkSize <= rsSize))
                     {
                        memcpy(rs->_buf()->GetBuffer()+offset, p, chunkSize);
                        rs->_offset += chunkSize;
                        if (rs->_offset == rsSize) 
                        {
                           HandleIncomingMessage(receiver, rs->_buf, fromIAP);
                           rs->_offset = 0;
                           rs->_buf()->Clear(rsSize > MAX_CACHE_SIZE);
                        }
                     }
                     else 
                     {
                        LogTime(MUSCLE_LOG_DEBUG, "Unknown fragment (" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC "/" UINT32_FORMAT_SPEC ") received from %s, ignoring it.\n", messageID, offset, chunkSize, totalSize, fromIAP.ToString()());
                        rs->_offset = 0;
                        rs->_buf()->Clear(rsSize > MAX_CACHE_SIZE);
                     }
                  }
                  p += chunkSize;
               }
               else break;
            }
         }
      }
      else if (bytesRead < 0) return -1;
      else break;
   }
   return totalBytesRead;
}
Ejemplo n.º 11
0
status_t
pll_adjust(pll_info* pll, display_mode* mode, uint8 crtcID)
{
	radeon_shared_info &info = *gInfo->shared_info;

	uint32 pixelClock = pll->pixelClock;
		// original as pixel_clock will be adjusted

	uint32 connectorIndex = gDisplay[crtcID]->connectorIndex;
	connector_info* connector = gConnector[connectorIndex];

	uint32 encoderID = connector->encoder.objectID;
	uint32 encoderMode = display_get_encoder_mode(connectorIndex);
	uint32 connectorFlags = connector->flags;

	uint32 externalEncoderID = 0;
	pll->adjustedClock = pll->pixelClock;
	if (connector->encoderExternal.isDPBridge)
		externalEncoderID = connector->encoderExternal.objectID;

	if (info.dceMajor >= 3) {

		uint8 tableMajor;
		uint8 tableMinor;

		int index = GetIndexIntoMasterTable(COMMAND, AdjustDisplayPll);
		if (atom_parse_cmd_header(gAtomContext, index, &tableMajor, &tableMinor)
			!= B_OK) {
			ERROR("%s: Couldn't find AtomBIOS PLL adjustment\n", __func__);
			return B_ERROR;
		}

		TRACE("%s: table %" B_PRIu8 ".%" B_PRIu8 "\n", __func__,
			tableMajor, tableMinor);

		// Prepare arguments for AtomBIOS call
		union adjustPixelClock {
			ADJUST_DISPLAY_PLL_PS_ALLOCATION v1;
			ADJUST_DISPLAY_PLL_PS_ALLOCATION_V3 v3;
		};
		union adjustPixelClock args;
		memset(&args, 0, sizeof(args));

		switch (tableMajor) {
			case 1:
				switch (tableMinor) {
					case 1:
					case 2:
						args.v1.usPixelClock
							= B_HOST_TO_LENDIAN_INT16(pixelClock / 10);
						args.v1.ucTransmitterID = encoderID;
						args.v1.ucEncodeMode = encoderMode;
						if (pll->ssPercentage > 0) {
							args.v1.ucConfig
								|= ADJUST_DISPLAY_CONFIG_SS_ENABLE;
						}

						atom_execute_table(gAtomContext, index, (uint32*)&args);
						// get returned adjusted clock
						pll->adjustedClock
							= B_LENDIAN_TO_HOST_INT16(args.v1.usPixelClock);
						pll->adjustedClock *= 10;
						break;
					case 3:
						args.v3.sInput.usPixelClock
							= B_HOST_TO_LENDIAN_INT16(pixelClock / 10);
						args.v3.sInput.ucTransmitterID = encoderID;
						args.v3.sInput.ucEncodeMode = encoderMode;
						args.v3.sInput.ucDispPllConfig = 0;
						if (pll->ssPercentage > 0) {
							args.v3.sInput.ucDispPllConfig
								|= DISPPLL_CONFIG_SS_ENABLE;
						}

						// Handle DP adjustments
						if (encoderMode == ATOM_ENCODER_MODE_DP
							|| encoderMode == ATOM_ENCODER_MODE_DP_MST) {
							TRACE("%s: encoderMode is DP\n", __func__);
							args.v3.sInput.ucDispPllConfig
								|= DISPPLL_CONFIG_COHERENT_MODE;
							/* 162000 or 270000 */
							uint32 dpLinkSpeed
								= dp_get_link_rate(connectorIndex, mode);
							/* 16200 or 27000 */
							args.v3.sInput.usPixelClock
								= B_HOST_TO_LENDIAN_INT16(dpLinkSpeed / 10);
						} else if ((connectorFlags & ATOM_DEVICE_DFP_SUPPORT)
							!= 0) {
							#if 0
							if (encoderMode == ATOM_ENCODER_MODE_HDMI) {
								/* deep color support */
								args.v3.sInput.usPixelClock =
									cpu_to_le16((mode->clock * bpc / 8) / 10);
							}
							#endif
							if (pixelClock > 165000) {
								args.v3.sInput.ucDispPllConfig
									|= DISPPLL_CONFIG_DUAL_LINK;
							}
							if (1) {	// dig coherent mode?
								args.v3.sInput.ucDispPllConfig
									|= DISPPLL_CONFIG_COHERENT_MODE;
							}
						}

						args.v3.sInput.ucExtTransmitterID = externalEncoderID;

						atom_execute_table(gAtomContext, index, (uint32*)&args);

						// get returned adjusted clock
						pll->adjustedClock = B_LENDIAN_TO_HOST_INT32(
								args.v3.sOutput.ulDispPllFreq);
						pll->adjustedClock *= 10;
							// convert to kHz for storage

						if (args.v3.sOutput.ucRefDiv) {
							pll->flags |= PLL_USE_FRAC_FB_DIV;
							pll->flags |= PLL_USE_REF_DIV;
							pll->referenceDiv = args.v3.sOutput.ucRefDiv;
						}
						if (args.v3.sOutput.ucPostDiv) {
							pll->flags |= PLL_USE_FRAC_FB_DIV;
							pll->flags |= PLL_USE_POST_DIV;
							pll->postDiv = args.v3.sOutput.ucPostDiv;
						}
						break;
					default:
						TRACE("%s: ERROR: table version %" B_PRIu8 ".%" B_PRIu8
							" unknown\n", __func__, tableMajor, tableMinor);
						return B_ERROR;
				}
				break;
			default:
				TRACE("%s: ERROR: table version %" B_PRIu8 ".%" B_PRIu8
					" unknown\n", __func__, tableMajor, tableMinor);
				return B_ERROR;
		}
	}

	TRACE("%s: was: %" B_PRIu32 ", now: %" B_PRIu32 "\n", __func__,
		pixelClock, pll->adjustedClock);

	return B_OK;
}
Ejemplo n.º 12
0
status_t
pll_asic_ss_probe(pll_info* pll, uint32 ssID)
{
	uint8 tableMajor;
	uint8 tableMinor;
	uint16 headerOffset;
	uint16 headerSize;

	int index = GetIndexIntoMasterTable(DATA, ASIC_InternalSS_Info);
	if (atom_parse_data_header(gAtomContext, index, &headerSize,
		&tableMajor, &tableMinor, &headerOffset) != B_OK) {
		ERROR("%s: Couldn't parse data header\n", __func__);
		return B_ERROR;
	}

	union asicSSInfo {
		struct _ATOM_ASIC_INTERNAL_SS_INFO info;
		struct _ATOM_ASIC_INTERNAL_SS_INFO_V2 info_2;
		struct _ATOM_ASIC_INTERNAL_SS_INFO_V3 info_3;
	};

	union asicSSInfo *ss_info
		= (union asicSSInfo*)((uint16*)gAtomContext->bios + headerOffset);

	int i;
	int indices;
	switch (tableMajor) {
		case 1:
			indices = (headerSize - sizeof(ATOM_COMMON_TABLE_HEADER))
				/ sizeof(ATOM_ASIC_SS_ASSIGNMENT);

			for (i = 0; i < indices; i++) {
				if (ss_info->info.asSpreadSpectrum[i].ucClockIndication
					!= ssID) {
					continue;
				}
				TRACE("%s: ss match found\n", __func__);
				if (pll->pixelClock * 10 > B_LENDIAN_TO_HOST_INT32(
					ss_info->info.asSpreadSpectrum[i].ulTargetClockRange)) {
					TRACE("%s: pixelClock > targetClockRange!\n", __func__);
					continue;
				}

				pll->ssPercentage = B_LENDIAN_TO_HOST_INT16(
					ss_info->info.asSpreadSpectrum[i].usSpreadSpectrumPercentage
					);

				pll->ssType
					= ss_info->info.asSpreadSpectrum[i].ucSpreadSpectrumMode;
				pll->ssRate = B_LENDIAN_TO_HOST_INT16(
					ss_info->info.asSpreadSpectrum[i].usSpreadRateInKhz);
				return B_OK;
			}
			break;
		case 2:
			indices = (headerSize - sizeof(ATOM_COMMON_TABLE_HEADER))
				/ sizeof(ATOM_ASIC_SS_ASSIGNMENT_V2);

			for (i = 0; i < indices; i++) {
				if (ss_info->info_2.asSpreadSpectrum[i].ucClockIndication
					!= ssID) {
					continue;
				}
				TRACE("%s: ss match found\n", __func__);
				if (pll->pixelClock * 10 > B_LENDIAN_TO_HOST_INT32(
					ss_info->info_2.asSpreadSpectrum[i].ulTargetClockRange)) {
					TRACE("%s: pixelClock > targetClockRange!\n", __func__);
					continue;
				}

				pll->ssPercentage = B_LENDIAN_TO_HOST_INT16(
					ss_info
						->info_2.asSpreadSpectrum[i].usSpreadSpectrumPercentage
					);

				pll->ssType
					= ss_info->info_2.asSpreadSpectrum[i].ucSpreadSpectrumMode;
				pll->ssRate = B_LENDIAN_TO_HOST_INT16(
					ss_info->info_2.asSpreadSpectrum[i].usSpreadRateIn10Hz);
				return B_OK;
			}
			break;
		case 3:
			indices = (headerSize - sizeof(ATOM_COMMON_TABLE_HEADER))
				/ sizeof(ATOM_ASIC_SS_ASSIGNMENT_V3);

			for (i = 0; i < indices; i++) {
				if (ss_info->info_3.asSpreadSpectrum[i].ucClockIndication
					!= ssID) {
					continue;
				}
				TRACE("%s: ss match found\n", __func__);
				if (pll->pixelClock * 10 > B_LENDIAN_TO_HOST_INT32(
					ss_info->info_3.asSpreadSpectrum[i].ulTargetClockRange)) {
					TRACE("%s: pixelClock > targetClockRange!\n", __func__);
					continue;
				}

				pll->ssPercentage = B_LENDIAN_TO_HOST_INT16(
					ss_info
						->info_3.asSpreadSpectrum[i].usSpreadSpectrumPercentage
					);

				pll->ssType
					= ss_info->info_3.asSpreadSpectrum[i].ucSpreadSpectrumMode;
				pll->ssRate = B_LENDIAN_TO_HOST_INT16(
					ss_info->info_3.asSpreadSpectrum[i].usSpreadRateIn10Hz);
				return B_OK;
			}
			break;
		default:
			ERROR("%s: Unknown SS table version!\n", __func__);
			return B_ERROR;
	}

	ERROR("%s: No potential spread spectrum data found!\n", __func__);
	return B_ERROR;
}
Ejemplo n.º 13
0
status_t
pll_limit_probe(pll_info *pll)
{
	int index = GetIndexIntoMasterTable(DATA, FirmwareInfo);
	uint8 tableMajor;
	uint8 tableMinor;
	uint16 tableOffset;

	if (atom_parse_data_header(gAtomContext, index, NULL,
		&tableMajor, &tableMinor, &tableOffset) != B_OK) {
		ERROR("%s: Couldn't parse data header\n", __func__);
		return B_ERROR;
	}

	union firmware_info *firmwareInfo
		= (union firmware_info *)(gAtomContext->bios + tableOffset);

	/* pixel clock limits */
	pll->referenceFreq
		= B_LENDIAN_TO_HOST_INT16(firmwareInfo->info.usReferenceClock) * 10;

	if (tableMinor < 2) {
		pll->pllOutMin
			= B_LENDIAN_TO_HOST_INT16(
				firmwareInfo->info.usMinPixelClockPLL_Output) * 10;
	} else {
		pll->pllOutMin
			= B_LENDIAN_TO_HOST_INT32(
				firmwareInfo->info_12.ulMinPixelClockPLL_Output) * 10;
	}

	pll->pllOutMax
		= B_LENDIAN_TO_HOST_INT32(
			firmwareInfo->info.ulMaxPixelClockPLL_Output) * 10;

	if (tableMinor >= 4) {
		pll->lcdPllOutMin
			= B_LENDIAN_TO_HOST_INT16(
				firmwareInfo->info_14.usLcdMinPixelClockPLL_Output) * 1000;

		if (pll->lcdPllOutMin == 0)
			pll->lcdPllOutMin = pll->pllOutMin;

		pll->lcdPllOutMax
			= B_LENDIAN_TO_HOST_INT16(
				firmwareInfo->info_14.usLcdMaxPixelClockPLL_Output) * 1000;

		if (pll->lcdPllOutMax == 0)
			pll->lcdPllOutMax = pll->pllOutMax;

	} else {
		pll->lcdPllOutMin = pll->pllOutMin;
		pll->lcdPllOutMax = pll->pllOutMax;
	}

	if (pll->pllOutMin == 0) {
		pll->pllOutMin = 64800 * 10;
			// Avivo+ limit
	}

	pll->minPostDiv = POST_DIV_MIN;
	pll->maxPostDiv = POST_DIV_LIMIT;
	pll->minRefDiv = REF_DIV_MIN;
	pll->maxRefDiv = REF_DIV_LIMIT;
	pll->minFeedbackDiv = FB_DIV_MIN;
	pll->maxFeedbackDiv = FB_DIV_LIMIT;

	pll->pllInMin = B_LENDIAN_TO_HOST_INT16(
		firmwareInfo->info.usMinPixelClockPLL_Input) * 10;
	pll->pllInMax = B_LENDIAN_TO_HOST_INT16(
		firmwareInfo->info.usMaxPixelClockPLL_Input) * 10;

	TRACE("%s: referenceFreq: %" B_PRIu16 "; pllOutMin: %" B_PRIu16 "; "
		" pllOutMax: %" B_PRIu16 "; pllInMin: %" B_PRIu16 ";"
		"pllInMax: %" B_PRIu16 "\n", __func__, pll->referenceFreq,
		pll->pllOutMin, pll->pllOutMax, pll->pllInMin, pll->pllInMax);

	return B_OK;
}
Ejemplo n.º 14
0
status_t
pll_adjust(pll_info *pll, uint8 crtcID)
{
	// TODO: PLL flags
	radeon_shared_info &info = *gInfo->shared_info;

	uint32 pixelClock = pll->pixelClock;
		// original as pixel_clock will be adjusted

	uint32 connectorIndex = gDisplay[crtcID]->connectorIndex;
	uint32 encoderID = gConnector[connectorIndex]->encoder.objectID;
	uint32 encoderMode = display_get_encoder_mode(connectorIndex);

	if (info.device_chipset >= (RADEON_R600 | 0x20)) {
		union adjust_pixel_clock args;

		uint8 tableMajor;
		uint8 tableMinor;

		int index = GetIndexIntoMasterTable(COMMAND, AdjustDisplayPll);

		if (atom_parse_cmd_header(gAtomContext, index, &tableMajor, &tableMinor)
			!= B_OK) {
			return B_ERROR;
		}

		memset(&args, 0, sizeof(args));
		switch (tableMajor) {
			case 1:
				switch (tableMinor) {
					case 1:
					case 2:
						args.v1.usPixelClock
							= B_HOST_TO_LENDIAN_INT16(pixelClock / 10);
						args.v1.ucTransmitterID = encoderID;
						args.v1.ucEncodeMode = encoderMode;
						// TODO: SS and SS % > 0
						if (0) {
							args.v1.ucConfig
								|= ADJUST_DISPLAY_CONFIG_SS_ENABLE;
						}

						atom_execute_table(gAtomContext, index, (uint32*)&args);
						// get returned adjusted clock
						pll->pixelClock
							= B_LENDIAN_TO_HOST_INT16(args.v1.usPixelClock);
						pll->pixelClock *= 10;
						break;
					case 3:
						args.v3.sInput.usPixelClock
							= B_HOST_TO_LENDIAN_INT16(pixelClock / 10);
						args.v3.sInput.ucTransmitterID = encoderID;
						args.v3.sInput.ucEncodeMode = encoderMode;
						args.v3.sInput.ucDispPllConfig = 0;
						// TODO: SS and SS % > 0
						if (0) {
							args.v3.sInput.ucDispPllConfig
								|= DISPPLL_CONFIG_SS_ENABLE;
						}
						// TODO: if ATOM_DEVICE_DFP_SUPPORT
						// TODO: display port DP

						// TODO: is DP?
						args.v3.sInput.ucExtTransmitterID = 0;

						atom_execute_table(gAtomContext, index, (uint32*)&args);
						// get returned adjusted clock
						pll->pixelClock
							= B_LENDIAN_TO_HOST_INT32(
								args.v3.sOutput.ulDispPllFreq);
						pll->pixelClock *= 10;
							// convert to kHz for storage

						if (args.v3.sOutput.ucRefDiv) {
							pll->flags |= PLL_USE_FRAC_FB_DIV;
							pll->flags |= PLL_USE_REF_DIV;
							pll->referenceDiv = args.v3.sOutput.ucRefDiv;
						}
						if (args.v3.sOutput.ucPostDiv) {
							pll->flags |= PLL_USE_FRAC_FB_DIV;
							pll->flags |= PLL_USE_POST_DIV;
							pll->postDiv = args.v3.sOutput.ucPostDiv;
						}
						break;
					default:
						TRACE("%s: ERROR: table version %" B_PRIu8 ".%" B_PRIu8
							" unknown\n", __func__, tableMajor, tableMinor);
						return B_ERROR;
				}
				break;
			default:
				TRACE("%s: ERROR: table version %" B_PRIu8 ".%" B_PRIu8
					" unknown\n", __func__, tableMajor, tableMinor);
				return B_ERROR;
		}
	}

	TRACE("%s: was: %" B_PRIu32 ", now: %" B_PRIu32 "\n", __func__,
		pixelClock, pll->pixelClock);

	return B_OK;
}
Ejemplo n.º 15
0
static inline uint32 UMReadInt32(const uint8 * ptr)      {return B_LENDIAN_TO_HOST_INT32(*((uint32 *)ptr));}
Ejemplo n.º 16
0
uint32
tga_uint32(char *buffer, int32 offset)
{
	return B_LENDIAN_TO_HOST_INT32(*(reinterpret_cast<uint32 *>(buffer + offset)));
}
Ejemplo n.º 17
0
/*!
  \internal
  This method will check the buffer for the next packet ID and try
  to build it if it have already been fully received. If the packet
  have arrived incomplete it will leave the data in buffer.
  Built packets are queued for core's retrieve.
*/
void cAsyncNetIO::buildUOPackets( cAsyncNetIOPrivate* d )
{
	bool keepExtracting = d->rsize > 1;
	while ( keepExtracting )
	{
		int packetID = d->getch();
		if ( packetID != -1 )
		{
			Q_UINT16 length = packetLengths[packetID];
			if ( length != 0x0000 )
			{
				// fixed size.
				d->ungetch( packetID );

				if ( length == 0xFFFF )
				{
					QByteArray packetData( d->rsize );
					d->readBlock( packetData.data(), d->rsize );
					qWarning( cUOPacket::dump( packetData ) );
					continue;
				}

				if ( d->rsize >= length )
				{
					QByteArray packetData( length );
					d->readBlock( packetData.data(), length );
					cUOPacket* packet = getUORxPacket( packetData );
					if ( !packet )
						d->socket->close();
					QMutexLocker lock( &d->packetsMutex );
					d->packets.push_back( packet );
				}
				else
					keepExtracting = false; // we have to wait some more.
			}
			else
			{
				// variable length
				if ( d->rsize < 3 ) // Packet ID, size + 1 byte data.
				{
					keepExtracting = false;
					d->ungetch( packetID ); // byte was read, put back to buffer.
					continue;
				}
				Q_UINT16 length = 0;
				Q_UINT8* p = ( Q_UINT8* ) &length;
				*( p + 1 ) = ( Q_UINT8 ) d->getch();
				*p = ( Q_UINT8 ) d->getch();
				d->ungetch( *p );
				d->ungetch( *( p + 1 ) );
				d->ungetch( packetID );
				length = B_LENDIAN_TO_HOST_INT32( length ); // Because we built as little
				if ( d->rsize < length )
				{
					keepExtracting = false;
					continue;
				}

				QByteArray packetData( length );
				d->readBlock( packetData.data(), length );
				cUOPacket* packet = getUORxPacket( packetData );
				if ( !packet )
					d->socket->close();
				QMutexLocker lock( &d->packetsMutex );
				d->packets.push_back( packet );
			}
		}
		else
			keepExtracting = false; // no more data in buffer.
	}
}
Ejemplo n.º 18
0
int32 getShares(void *data)
{
	bt_request request;
	bt_resource resource;
	struct sockaddr_in ourAddr, toAddr, fromAddr;
	char buffer[8192];
	int sock, addrLen, bytes, bufPos = 0;

	ThreadInfo *info = (ThreadInfo *) data;
	unsigned int serverIP = ntohl(info->GetHostAddress());

	memset(&toAddr, 0, sizeof(toAddr));
	toAddr.sin_family = AF_INET;
	toAddr.sin_port = htons(BT_QUERYHOST_PORT);
	toAddr.sin_addr.s_addr = htonl(serverIP);

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock == INVALID_SOCKET)
		return 0;

	memset(&ourAddr, 0, sizeof(ourAddr));
	ourAddr.sin_family = AF_INET;
	ourAddr.sin_port = htons(BT_QUERYHOST_PORT);
	ourAddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(sock, (struct sockaddr *) &ourAddr, sizeof(ourAddr)))
		if (errno != EADDRINUSE)
		{
			closesocket(sock);
			return 0;
		}

	strcpy(request.signature, BT_RPC_SIGNATURE);
	request.command = BT_REQ_SHARE_PROBE;
	sendto(sock, (char *) &request, sizeof(request), 0, (struct sockaddr *) &toAddr, sizeof(toAddr));

	signal(SIGALRM, recvAlarm);
	alarm(4);

	addrLen = sizeof(fromAddr);
	bytes = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *) &fromAddr, &addrLen);
	if (bytes > 0)
		if (strncmp(buffer, BT_RPC_SIGNATURE, strlen(BT_RPC_SIGNATURE)) != 0)
		{
			info->GetColumnListView()->LockLooper();

			while (bufPos < bytes)
			{
				memcpy(&resource, buffer + bufPos, sizeof(bt_resource));
				resource.type = B_LENDIAN_TO_HOST_INT32(resource.type);
				resource.subType = B_LENDIAN_TO_HOST_INT32(resource.subType);
				if (resource.type == BT_SHARED_NULL)
					break;

				bufPos += sizeof(bt_resource);
				info->GetColumnListView()->AddItem(new ResourceItem(resource.name, resource.type));
			}

			info->GetColumnListView()->UnlockLooper();
		}

	alarm(0);
	signal(SIGALRM, SIG_DFL);
	closesocket(sock);
	return 1;
}
Ejemplo n.º 19
0
int32 getHostInfo(void *data)
{
	bt_request request;
	struct sockaddr_in ourAddr, toAddr, fromAddr;
	char buffer[1024];
	int sock, addrLen, bytes;
	bool retry = true;

	HostInfoView *view = (HostInfoView *) data;
	unsigned int serverIP = ntohl(view->address);

	memset(&toAddr, 0, sizeof(toAddr));
	toAddr.sin_family = AF_INET;
	toAddr.sin_port = htons(BT_QUERYHOST_PORT);
	toAddr.sin_addr.s_addr = htonl(serverIP);

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock == INVALID_SOCKET)
		return 0;

	memset(&ourAddr, 0, sizeof(ourAddr));
	ourAddr.sin_family = AF_INET;
	ourAddr.sin_port = htons(BT_QUERYHOST_PORT);
	ourAddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(sock, (struct sockaddr *) &ourAddr, sizeof(ourAddr)))
		if (errno != EADDRINUSE)
		{
			closesocket(sock);
			return 0;
		}

sendReq:
	strcpy(request.signature, BT_RPC_SIGNATURE);
	request.command = BT_REQ_HOST_INFO;
	sendto(sock, (char *) &request, sizeof(request), 0, (struct sockaddr *) &toAddr, sizeof(toAddr));

	signal(SIGALRM, recvAlarm);
	alarm(3);

	addrLen = sizeof(fromAddr);
	bytes = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *) &fromAddr, &addrLen);
	if (bytes > 0)
	{
		memcpy(&view->hostInfo, buffer, sizeof(bt_hostinfo));

		view->hostInfo.cpus = B_LENDIAN_TO_HOST_INT32(view->hostInfo.cpus);
		view->hostInfo.connections = B_LENDIAN_TO_HOST_INT32(view->hostInfo.connections);
		view->hostInfo.maxConnections = B_LENDIAN_TO_HOST_INT32(view->hostInfo.maxConnections);
	}
	else if (retry)
	{
		retry = false;
		goto sendReq;
	}

	alarm(0);
	signal(SIGALRM, SIG_DFL);
	closesocket(sock);
	return 1;
}
Ejemplo n.º 20
0
// btRPCSimpleCall()
//
bt_inPacket *btRPCSimpleCall(unsigned int serverIP, int port, bt_outPacket *outPacket)
{
	struct timeval timeout;
	bt_inPacket *inPacket;
	fd_set sockSet;
	char *buffer;
	int session;
	int32 xid, length;

	// Establish a connection with the requested server, on the requested port.
	// If we can't connect, abort and return a NULL packet.
	inPacket = NULL;
	session = btRPCConnect(serverIP, port);
	if (session == INVALID_SOCKET)
		return NULL;

	// If we connected, send the requested RPC packet.  If the packet cannot be
	// sent, the connection has dropped and we'll abort the call.
	if (!btRPCSend(session, outPacket))
	{
		closesocket(session);
		return NULL;
	}

	// Set a reasonable timeout period.  Select() is used in leiu of alarm() because
	// select() also aborts on error, alarm() effects all threads in a process.
	FD_ZERO(&sockSet);
	timeout.tv_sec = 8;
	timeout.tv_usec = 0;

	// Block in select() waiting for activity.  This will block until data is available
	// or until a socket error is pending.
	FD_SET(session, &sockSet);
	select(session + 1, &sockSet, NULL, NULL, &timeout);

	// If our socket has data pending, then read the incoming RPC response packet.
	// This should consist of a valid RPC signature, a tranaction ID (xid), the length
	// of the variable data, and the data itself.
	if (FD_ISSET(session, &sockSet))
		if (btRPCCheckSignature(session))
		{
			if (btRecvMsg(session, &xid, sizeof(int32), 0) == -1 ||
				btRecvMsg(session, &length, sizeof(int32), 0) == -1)
				goto abortCall;

			// Now allocate a buffer of the appropriate length.  If one cannot be
			// allocated, we won't be able to store incoming information and the call
			// must be aborted.
			xid = B_LENDIAN_TO_HOST_INT32(xid);
			length = B_LENDIAN_TO_HOST_INT32(length);
			if (length > 0 && length < BT_RPC_MAX_PACKET_SIZE)
			{
				buffer = (char *) malloc(length + 1);
				if (buffer)
				{
					// Read the remaining packet contents.  The btRecvMsg() function takes
					// care of restarting the recv() when signal interrupts occur.  It
					// will always return -1 on error, even upon orderly shutdown of the peer.
					if (btRecvMsg(session, buffer, length, 0) == -1)
					{
						free(buffer);
						goto abortCall;
					}

					// Terminate the buffer.
					buffer[length] = 0;

					// Allocate a new incoming packet and set its buffer and length.
					inPacket = (bt_inPacket *) malloc(sizeof(bt_inPacket));
					if (inPacket)
					{
						inPacket->buffer = buffer;
						inPacket->length = length;
						inPacket->offset = 0;
					}
					else
						free(buffer);
				}
			}
		}

	// Execution can naturally lead here or we can jump here from a failed attempt to
	// send or receive an RPC packet.  The socket is closed and the current incoming
	// packet returned, which will be NULL upon failure.
abortCall:
	shutdown(session, 2);
	close(session);
	return inPacket;
}
Ejemplo n.º 21
0
Layer*
Layer::readLayer(BFile& file, ImageView* imageView, int32 new_id,
                 bool is_little_endian, int32 compression_method)
{
    // This is the new way of reading the layers.
    int32 marker;
    if (file.Read(&marker,sizeof(int32)) != sizeof(int32))
        return NULL;

    if (is_little_endian)
        marker = B_LENDIAN_TO_HOST_INT32(marker);
    else
        marker = B_BENDIAN_TO_HOST_INT32(marker);

    if (marker != PROJECT_FILE_LAYER_START_MARKER)
        return NULL;

    int32 width;
    int32 height;
    layer_type layerType;
    int32 layer_visibility;
    int64 length;
    if (file.Read(&width,sizeof(int32)) != sizeof(int32))
        return NULL;
    if (file.Read(&height,sizeof(int32)) != sizeof(int32))
        return NULL;
    if (file.Read(&layerType,sizeof(int32)) != sizeof(int32))
        return NULL;
    if (file.Read(&layer_visibility,sizeof(int32)) != sizeof(int32))
        return NULL;
    if (file.Read(&length,sizeof(int64)) != sizeof(int64))
        return NULL;

    if (is_little_endian) {
        width = B_LENDIAN_TO_HOST_INT32(width);
        height = B_LENDIAN_TO_HOST_INT32(height);
        layerType = layer_type(B_LENDIAN_TO_HOST_INT32(layerType));
        length = B_LENDIAN_TO_HOST_INT64(length);
    }
    else {
        width = B_BENDIAN_TO_HOST_INT32(width);
        height = B_BENDIAN_TO_HOST_INT32(height);
        layerType = layer_type(B_BENDIAN_TO_HOST_INT32(layerType));
        length = B_BENDIAN_TO_HOST_INT64(length);
    }

    Layer* layer = new Layer(BRect(0, 0, width - 1, height - 1), new_id,
                             imageView, layerType);
    layer->SetVisibility((uint32(layer_visibility) == 0xFFFFFFFF));
    int8* bits = (int8*)layer->Bitmap()->Bits();
    if (file.Read(bits,length) != length) {
        delete layer;
        return NULL;
    }

    // Read the end-marker.
    if (file.Read(&marker,sizeof(int32)) != sizeof(int32)) {
        delete layer;
        return NULL;
    }
    if (is_little_endian)
        marker = B_LENDIAN_TO_HOST_INT32(marker);
    else
        marker = B_BENDIAN_TO_HOST_INT32(marker);

    if (marker != PROJECT_FILE_LAYER_END_MARKER) {
        delete layer;
        return NULL;
    }

    // Here try to read the extra-data block.
    if (file.Read(&marker,sizeof(int32)) == sizeof(int32)) {
        if (is_little_endian)
            marker = B_LENDIAN_TO_HOST_INT32(marker);
        else
            marker = B_BENDIAN_TO_HOST_INT32(marker);

        if (marker == PROJECT_FILE_LAYER_EXTRA_DATA_START_MARKER) {
            // Read the length of this section
            int32 length;
            if (file.Read(&length,sizeof(int32)) != sizeof(int32)) {
                delete layer;
                return NULL;
            }

            if (is_little_endian)
                length = B_LENDIAN_TO_HOST_INT32(length);
            else
                length = B_BENDIAN_TO_HOST_INT32(length);

            // Read the transparency coefficient
            float coeff;
            if (file.Read(&coeff,sizeof(float)) != sizeof(float)) {
                delete layer;
                return NULL;
            }
            if (is_little_endian)
                coeff = B_LENDIAN_TO_HOST_FLOAT(coeff);
            else
                coeff = B_BENDIAN_TO_HOST_FLOAT(coeff);

            layer->SetTransparency(coeff);
            length -= sizeof(float);

            // Skip the extra data that we do not recognize.
            file.Seek(length,SEEK_CUR);

            // Here we should get the end-marker for layer's extra data
            if (file.Read(&marker,sizeof(int32)) != sizeof(int32)) {
                delete layer;
                return NULL;
            }
            if (is_little_endian)
                marker = B_LENDIAN_TO_HOST_INT32(marker);
            else
                marker = B_BENDIAN_TO_HOST_INT32(marker);

            if (marker != PROJECT_FILE_LAYER_EXTRA_DATA_END_MARKER) {
                delete layer;
                return NULL;
            }

        }
        else {
            // Somehow -sizeof(int32) does not seem to work????
            file.Seek(-4,SEEK_CUR);
        }
    }

    // Before returning calculate the layer's miniature image.
    layer->calc_mini_image();

    return layer;
}