DWORD CopyWideString(
    IN _In_ LPWSTR pSrcWString,
    OUT _Out_ LPWSTR *pDestWString)
{
    DWORD retCode = NO_ERROR;
    HRESULT hr = S_OK;
    size_t dwStringLength = 0;
    LPWSTR pTempString = NULL;

    *pDestWString = NULL;

    // Nothing to copy
    if(!pSrcWString)
        goto Cleanup;

    hr = StringCbLengthW(pSrcWString, (size_t)(STRSAFE_MAX_CCH * sizeof(wchar_t)), &dwStringLength);
    if (FAILED(hr))
    {
        retCode = HRESULT_CODE(hr);
        goto Cleanup;
    }

    // StringCbLengthW - returns the length of string in bytes (excluding the null character).
    // StringCbCopyW expects the length of string in bytes (including the null character).
    dwStringLength += sizeof(wchar_t);
    retCode = AllocateMemory((DWORD)dwStringLength, (PVOID *)&pTempString);
    if(retCode != NO_ERROR)
    {
        goto Cleanup;
    }

    hr = StringCbCopyW((LPTSTR)pTempString, dwStringLength, pSrcWString);
    if (FAILED(hr))
    {
        retCode = HRESULT_CODE(hr);
        goto Cleanup;
    }

    //
    // Set the OUT parameter
    //
    *pDestWString = pTempString;

Cleanup:
    if((retCode != NO_ERROR) && (pTempString != NULL))
        FreeMemory((PVOID *)&pTempString);
    pTempString = NULL;
    return retCode;
}
Example #2
0
UPK_STATUS
NitroPlus::Open(
    PCWSTR FileName
)
{
    PVOID                   EntryBuffer;
    LARGE_INTEGER           BytesRead;
    NTSTATUS                Status;
    NITRO_PLUS_NPA_HEADER   Header;

    Status = m_File.Open(FileName);
    FAIL_RETURN(Status);

    Status = m_File.Read(&Header, sizeof(Header), &BytesRead);
    FAIL_RETURN(Status);

    if (
        BytesRead.LowPart != sizeof(Header) ||
        (*(PULONG)Header.Signature & 0x00FFFFFF) != NPA_HEADER_MAGIC
       )
    {
        return STATUS_UNSUCCESSFUL;
    }

    switch (Header.Version)
    {
        case NPA_GCLX_VERSION:
            break;

        default:
            return STATUS_UNSUCCESSFUL;
    }

    EntryBuffer = AllocateMemory(Header.EntrySize);
    if (EntryBuffer == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    Status = m_File.Read(EntryBuffer, Header.EntrySize, &BytesRead);
    FAIL_RETURN(Status);

    if (BytesRead.LowPart != Header.EntrySize)
        return STATUS_UNSUCCESSFUL;

    Status = InitIndex(EntryBuffer, &Header);

    FreeMemory(EntryBuffer);

    return Status;
}
Example #3
0
Bool LoadBofName(char *fname)
{
   FILE *f = fopen(fname, "rb");
	if (f == NULL)
   {
      eprintf("LoadBofName can't open %s\n", fname);
		return False;
   }

   for (int i = 0; i < BOF_MAGIC_LEN; ++i)
   {
      unsigned char c;
      if (fread(&c, 1, 1, f) != 1 || c != magic_num[i])
      {
         eprintf("LoadBofName %s is not in BOF format\n", fname);
         fclose(f);
         return False;
      }
   }
   
   int version;
   if (fread(&version, 1, 4, f) != 4 || version != 5)
	{
		eprintf("LoadBofName %s can't understand bof version != 5\n",fname);
      fclose(f);
		return False;
	}
   
   // Go back to start of file and read the whole thing into memory.
   fseek(f, 0, SEEK_SET);
   
   struct stat st;
   stat(fname, &st);
   int file_size = st.st_size;

	char *ptr = (char *)AllocateMemory(MALLOC_ID_LOADBOF,file_size);
   if (fread(ptr, 1, file_size, f) != file_size)
   {
      fclose(f);
      return False;
   }

   fclose(f);

	AddFileMem(fname,ptr,file_size);
	
	return True;
}
Example #4
0
int CreateStringWithLen(char *buf,int len)
{
   int string_id;
   string_node *snod;
   
   /* note:  new_str is NOT null-terminated */
   string_id = AllocateString();
   snod = GetStringByID(string_id);

   snod->data = (char *)AllocateMemory(MALLOC_ID_STRING,len+1);
   memcpy(snod->data,buf,len);
   snod->len_data = len;
   snod->data[snod->len_data] = '\0';
   
   return string_id;
}
TripletSparseMatrix::TripletSparseMatrix(int num_rows,
                                         int num_cols,
                                         int max_num_nonzeros)
    : num_rows_(num_rows),
      num_cols_(num_cols),
      max_num_nonzeros_(max_num_nonzeros),
      num_nonzeros_(0),
      rows_(NULL),
      cols_(NULL),
      values_(NULL) {
  // All the sizes should at least be zero
  CHECK_GE(num_rows, 0);
  CHECK_GE(num_cols, 0);
  CHECK_GE(max_num_nonzeros, 0);
  AllocateMemory();
}
Example #6
0
void InitAccount(void)
{
   accounts = NULL;
   next_account_id = 1;

   console_account = &console_account_node;
   console_account->account_id = 0;
   console_account->name = ConfigStr(CONSOLE_ADMINISTRATOR);
   console_account->password = (char *)AllocateMemory(MALLOC_ID_ACCOUNT,1);
   console_account->password[0] = 0;

   console_account->type = ACCOUNT_ADMIN;
   console_account->last_login_time = 0;
   console_account->suspend_time = 0;
   console_account->credits = 0;
}
Example #7
0
int AllocateObject(int class_id)
{
   int old_objects;
   class_node *c;

   c = GetClassByID(class_id);
   if (c == NULL)
   {
      eprintf("AllocateObject can't find class id %i\n",class_id);
      return INVALID_OBJECT;
   }

   if (num_objects == max_objects)
   {
      old_objects = max_objects;
      max_objects = max_objects * 2;
      objects = (object_node *)
	 ResizeMemory(MALLOC_ID_OBJECT,objects,old_objects*sizeof(object_node),
		      max_objects*sizeof(object_node));
      lprintf("AllocateObject resized to %i objects\n",max_objects);
   }

   objects[num_objects].object_id = num_objects;
   objects[num_objects].class_id = class_id;
   objects[num_objects].deleted = False;
   objects[num_objects].num_props = 1 + c->num_properties;
   objects[num_objects].p = (prop_type *)AllocateMemory(MALLOC_ID_OBJECT_PROPERTIES,
							sizeof(prop_type)*(1+c->num_properties));

   if (ConfigBool(DEBUG_INITPROPERTIES))
   {
      int i;
      prop_type p;

      p.id = 0;
      p.val.v.tag = TAG_INVALID;
      p.val.v.data = 0;

      for (i = 0; i < (1+c->num_properties); i++)
      {
	 objects[num_objects].p[i] = p;
      }
   }

   return num_objects++;
}
Example #8
0
void CreateAccountFromSMTPMail(smtp_node *smtp)
{
#ifdef SMTP_TEST
	return;
#else
	
	int len_buf;
	char *buf;
	string_list *sl;
	
	/* put mail into buffer, than analyze, then free buffer */
	
	len_buf = 0;
	sl = smtp->data;
	while (sl != NULL)
	{
		len_buf += strlen(sl->str);
		sl = sl->next;
	}
	
	buf = (char *) AllocateMemory(MALLOC_ID_SMTP,len_buf+1);
	len_buf = 0;
	
	sl = smtp->data;
	while (sl != NULL)
	{
		strcpy(buf+len_buf,sl->str);
		len_buf += strlen(sl->str);
		sl = sl->next;
	}
	
	if (strcmp(smtp->forward_path->str,ConfigStr(EMAIL_ACCOUNT_CREATE_NAME)) == 0)
	{
		CreateAccountFromBuffer(buf);
	}
	else
	{
		if (strcmp(smtp->forward_path->str,ConfigStr(EMAIL_ACCOUNT_DELETE_NAME)) == 0)
			DeleteAccountFromBuffer(buf);
	}
	
	FreeMemory(MALLOC_ID_SMTP,buf,len_buf+1);
#endif
}
Example #9
0
PQUEUE_HEAD
CreateQueueHead(PEHCI_HOST_CONTROLLER hcd)
{
    PQUEUE_HEAD CurrentQH;
    ULONG PhysicalAddress , i;
    KIRQL OldIrql;

    KeAcquireSpinLock(&hcd->Lock, &OldIrql);
    CurrentQH = (PQUEUE_HEAD)AllocateMemory(hcd, sizeof(QUEUE_HEAD), &PhysicalAddress);
    RtlZeroMemory(CurrentQH, sizeof(QUEUE_HEAD));

    ASSERT(CurrentQH);
    CurrentQH->PhysicalAddr = PhysicalAddress;
    CurrentQH->HorizontalLinkPointer = TERMINATE_POINTER;
    CurrentQH->AlternateNextPointer = TERMINATE_POINTER;
    CurrentQH->NextPointer = TERMINATE_POINTER;

    /* 1 for non high speed, 0 for high speed device */
    CurrentQH->EndPointCharacteristics.ControlEndPointFlag = 0;
    CurrentQH->EndPointCharacteristics.HeadOfReclamation = FALSE;
    CurrentQH->EndPointCharacteristics.MaximumPacketLength = 64;

    /* Set NakCountReload to max value possible */
    CurrentQH->EndPointCharacteristics.NakCountReload = 0xF;

    /* Get the Initial Data Toggle from the QEDT */
    CurrentQH->EndPointCharacteristics.QEDTDataToggleControl = FALSE;

    /* High Speed Device */
    CurrentQH->EndPointCharacteristics.EndPointSpeed = QH_ENDPOINT_HIGHSPEED;

    CurrentQH->EndPointCapabilities.NumberOfTransactionPerFrame = 0x03;

    CurrentQH->Token.DWord = 0;
    CurrentQH->NextQueueHead = NULL;
    CurrentQH->PreviousQueueHead = NULL;
    for (i=0; i<5; i++)
        CurrentQH->BufferPointer[i] = 0;

    CurrentQH->Token.Bits.InterruptOnComplete = FALSE;

    KeReleaseSpinLock(&hcd->Lock, OldIrql);
    return CurrentQH;
}
Example #10
0
void initializeTestData()
{
  root = AllocateMemory(1);
  struct tree *left1 = AllocateMemory(2);
  struct tree *left11 = AllocateMemory(4);
  struct tree *left12 = AllocateMemory(5);
  struct tree *right1 = AllocateMemory(3);
  struct tree *right11 = AllocateMemory(6);
  struct tree *right12 = AllocateMemory(7);
  root->left = left1;
  root->right=right1;
  left1->left=left11;
  left1->right=left12;
  right1->left=right11;
  right1->right=right12;
  
}   
Example #11
0
    void Kernel::CreateProcess(const std::string &name)
    {
        if (_last_issued_process_id == std::numeric_limits<Process::process_id_type>::max()) {
            std::cerr << "Kernel: failed to create a new process. The maximum number of processes has been reached." << std::endl;
        } else {
            std::ifstream input_stream(name, std::ios::in | std::ios::binary);
            if (!input_stream) {
                std::cerr << "Kernel: failed to open the program file." << std::endl;
            } else {
                MMU::ram_type ops;

                input_stream.seekg(0, std::ios::end);
                auto file_size = input_stream.tellg();
                input_stream.seekg(0, std::ios::beg);
                ops.resize(static_cast<MMU::ram_size_type>(file_size) / 4);

                input_stream.read(reinterpret_cast<char *>(&ops[0]), file_size);

                if (input_stream.bad()) {
                    std::cerr << "Kernel: failed to read the program file." << std::endl;
                } else {
					MMU::ram_size_type new_memory_position = AllocateMemory(ops.size()); // TODO: allocate memory for the process (AllocateMemory)
                    if (new_memory_position == -1) {
                        std::cerr << "Kernel: failed to allocate memory." << std::endl;
                    } else {
                        std::copy(ops.begin(), ops.end(), (machine.mmu.ram.begin() + new_memory_position));

                        Process process(_last_issued_process_id++, new_memory_position,
                                                                   new_memory_position + ops.size());

                        // Old sequential allocation
                        //
                        // std::copy(ops.begin(), ops.end(), (machine.memory.ram.begin() + _last_ram_position));
                        //
                        // Process process(_last_issued_process_id++, _last_ram_position,
                        //                                            _last_ram_position + ops.size());
                        //
                        // _last_ram_position += ops.size();
                    }
                }
            }
        }
    }
Example #12
0
//*****************************************************************************
// Called to read the data into allocated memory and release the backing store.
//  Only available on read-only data.
//*****************************************************************************
HRESULT 
StgIO::LoadFileToMemory()
{
    HRESULT hr;
    void   *pData;          // Allocated buffer for file.
    ULONG   cbData;         // Size of the data.
    ULONG   cbRead = 0;     // Data actually read.
    
    // Make sure it is a read-only file.
    if (m_fFlags & DBPROP_TMODEF_WRITE)
        return E_INVALIDARG;
    
    // Try to allocate the buffer.
    cbData = m_cbData;
    pData = AllocateMemory(cbData);
    IfNullGo(pData);
    
    // Try to read the file into the buffer.
    IfFailGo(Read(pData, cbData, &cbRead));
    if (cbData != cbRead)
    {
        _ASSERTE_MSG(FALSE, "Read didn't succeed.");
        IfFailGo(CLDB_E_FILE_CORRUPT);
    }
    
    // Done with the old data.
    Close();
    
    // Open with new data.
    hr = Open(NULL /* szName */, STGIO_READ, pData, cbData, NULL /* IStream* */, NULL /* lpSecurityAttributes */);
    _ASSERTE(SUCCEEDED(hr)); // should not be a failure code path with open on buffer.
    
    // Mark the new memory so that it will be freed later.
    m_pBaseData = m_pData;
    m_bFreeMem = true;
    
ErrExit:
    if (FAILED(hr) && pData)
       FreeMemory(pData);
    
    return hr;
} // StgIO::LoadFileToMemory
Example #13
0
GrVkSubHeap::GrVkSubHeap(const GrVkGpu* gpu, uint32_t memoryTypeIndex,
                         VkDeviceSize size, VkDeviceSize alignment)
    : INHERITED(size, alignment)
    , fGpu(gpu)
    , fMemoryTypeIndex(memoryTypeIndex) {

    VkMemoryAllocateInfo allocInfo = {
        VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,      // sType
        NULL,                                        // pNext
        size,                                        // allocationSize
        memoryTypeIndex,                             // memoryTypeIndex
    };

    VkResult err = GR_VK_CALL(gpu->vkInterface(), AllocateMemory(gpu->device(),
                              &allocInfo,
                              nullptr,
                              &fAlloc));
    if (VK_SUCCESS != err) {
        this->reset();
    }
}
Example #14
0
/* add a filename and mapped ptr to the list of loaded files */
void AddFileMem(char *fname,char *ptr,int size)
{
	loaded_bof_node *lf;
	
	/* make new loaded_file node */
	lf = (loaded_bof_node *)AllocateMemory(MALLOC_ID_LOADBOF,sizeof(loaded_bof_node));
	strcpy(lf->fname,fname);
	lf->mem = ptr;
	lf->length = size;
	
	/* we store the fname so the class structures can point to it, but kill the path */
	
	if (strrchr(lf->fname,'\\') == NULL)
		FindClasses(lf->mem,lf->fname); 
	else
		FindClasses(lf->mem,strrchr(lf->fname,'\\')+1); 
	
	/* add to front of list */
	lf->next = mem_files;
	mem_files = lf;
}
Example #15
0
Bool AssociateUser(int account_id,int object_id)
{
   user_node *u;

   u = users;
   while (u != NULL)
   {
      if (u->object_id == object_id)
	 return False;
      u = u->next;
   }

   u = (user_node *)AllocateMemory(MALLOC_ID_USER,sizeof(user_node));
   u->account_id = account_id;
   u->object_id = object_id;

   u->next = users;
   users = u;

   return True;
}
Example #16
0
File: p2.c Project: ttrask/eggen-os
pid_t ForkStoreManager() {

	pid_t sm_pid;

	int quit = 0;

	switch ((sm_pid = fork())) {
	case 0:

		logFilePointer = OpenLogFile();

		//allocate shared memory
		AllocateMemory();

		LoadTable();

		while (quit == 0) {

			if (pipe1Done == 0)
				GetThreadedMessages(1, pipe1, pipe3);

			if (pipe2Done == 0)
				GetThreadedMessages(2, pipe2, pipe4);

			if (pipe1Done != 0 && pipe2Done != 0) {
				printf("quitting app\n");
				quit = 1;
			}

			usleep(100);
		}

		exit(1);

		break;

	}
	return sm_pid;

}
Example #17
0
int MakeStringFromSMTPMail(smtp_node *smtp)
{
#ifdef SMTP_TEST
	return 0;
#else
	
	int len_buf,string_id;
	char *buf;
	string_list *sl;
	
	/* cheesy here--allocate buffer, make the string, then free buffer.
	would be nice to not have to allocate here */
	
	len_buf = 0;
	sl = smtp->data;
	while (sl != NULL)
	{
		len_buf += strlen(sl->str);
		sl = sl->next;
	}
	
	buf = (char *) AllocateMemory(MALLOC_ID_SMTP,len_buf+1);
	len_buf = 0;
	
	sl = smtp->data;
	while (sl != NULL)
	{
		strcpy(buf+len_buf,sl->str);
		len_buf += strlen(sl->str);
		sl = sl->next;
	}
	
	string_id = CreateStringWithLen(buf,len_buf+1);
	
	FreeMemory(MALLOC_ID_SMTP,buf,len_buf);
	
	return string_id;
	
#endif
}
Example #18
0
File: low.c Project: BuloZB/WinNT4
ARC_STATUS
LowQueryPathFromComponent(
    IN  PCONFIGURATION_COMPONENT    Component,
    OUT PCHAR*                      Path
    )
/*++

Routine Description:

    This routine computes a path from a component.  The resulting
    path is allocated on the heap.

Arguments:

    Component   - Supplies a component.
    Path        - Returns the path corresponding to that component.

Return Value:

    ENOMEM, ESUCCESS

--*/
{
    PCHAR   p;
    PCHAR   path;

    p = AlGetPathnameFromComponent(Component);

    path = AllocateMemory(strlen(p) + 1);

    if (!path) {
        return ENOMEM;
    }

    strcpy(path, p);

    *Path = path;

    return ESUCCESS;
}
Example #19
0
int CreateTimer(int object_id,int message_id,int milliseconds)
{
   timer_node *t;

   if (deleted_timers == NULL)
      t = (timer_node *)AllocateMemory(MALLOC_ID_TIMER,sizeof(timer_node));
   else
   {
      /* dprintf("recovering former timer id %i\n",deleted_timers->timer_id); */
      t = deleted_timers;
      deleted_timers = deleted_timers->next;
   }
      
   t->timer_id = next_timer_num++;
   t->object_id = object_id;
   t->message_id = message_id;
   t->time = GetMilliCount() + milliseconds;

   AddTimerNode(t);
   numActiveTimers++;

   return t->timer_id;
}
Example #20
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   S e t M a g i c k I n f o                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method SetMagickInfo allocates a MagickInfo structure and initializes the
%  members to default values.
%
%  The format of the SetMagickInfo method is:
%
%      MagickInfo *SetMagickInfo(const char *tag)
%
%  A description of each parameter follows:
%
%    o magick_info: Method SetMagickInfo returns the allocated and initialized
%      MagickInfo structure.
%
%    o tag: a character string that represents the image format associated
%      with the MagickInfo structure.
%
%
*/
Export MagickInfo *SetMagickInfo(const char *tag)
{
  MagickInfo
    *entry;

  entry=(MagickInfo *) AllocateMemory(sizeof(MagickInfo));
  if (entry == (MagickInfo *) NULL)
    MagickError(ResourceLimitError,"Unable to allocate image",
      "Memory allocation failed");
  entry->tag=AllocateString(tag);
  entry->decoder=(Image *(*)(const ImageInfo *)) NULL;
  entry->encoder=(unsigned int (*)(const ImageInfo *,Image *)) NULL;
  entry->magick=
    (unsigned int (*)(const unsigned char *,const unsigned int)) NULL;
  entry->adjoin=True;
  entry->blob_support=True;
  entry->raw=False;
  entry->description=(char *) NULL;
  entry->data=(void *) NULL;
  entry->previous=(MagickInfo *) NULL;
  entry->next=(MagickInfo *) NULL;
  return(entry);
}
Example #21
0
void	CDib::CreatFromHandle(HDIB	hDib)
{
    ASSERT (hDib!=NULL);
    DWORD	dwSizeDib=GlobalSize(hDib);
    void* lpDib = ::GlobalLock(hDib);
    m_dwLength=dwSizeDib+sizeof(BITMAPFILEHEADER);
    DWORD	dwLenHead=sizeof(BITMAPFILEHEADER);
    DWORD	dwLen = m_dwLength-dwLenHead;

    if(!AllocateMemory())
        return;

    memcpy((LPBYTE)m_lpBMIH,lpDib,dwLen);
    int		nPaletteSize=PaletteSize(m_lpBMI);
    m_lpBMFH->bfType=0x4d42;//"BM"
    m_lpBMFH->bfSize=m_dwLength;
    m_lpBMFH->bfReserved1=0;
    m_lpBMFH->bfReserved2=0;
    m_lpBMFH->bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+
                        nPaletteSize;

    ::GlobalUnlock(hDib);
}
Example #22
0
Bool LoadTimer(int timer_id,int object_id,char *message_name,int milliseconds)
{
   object_node *o;
   timer_node *t;
   message_node *m;

   o = GetObjectByID(object_id);
   if (o == NULL)
   {
      eprintf("LoadTimer can't find object %i\n",object_id);
      return False;
   }

   m = GetMessageByName(o->class_id,message_name,NULL);
   if (m == NULL) 
   {
      eprintf("LoadTimer can't find message name %s\n",message_name);
      return False;
   }

   t = (timer_node *)AllocateMemory(MALLOC_ID_TIMER,sizeof(timer_node));
   t->timer_id = timer_id;
   t->object_id = object_id;
   t->message_id = m->message_id;
   t->time = GetMilliCount() + milliseconds;

   AddTimerNode(t);
   numActiveTimers++;

   /* the timers weren't saved in numerical order, but they were
    * compacted to first x non-negative integers
    */
   if (timer_id >= next_timer_num)
      next_timer_num = timer_id + 1;

   return True;
}
Example #23
0
bool MemoryContext::MapDocument(Document const& rDoc, CpuContext const* pCpuCtxt)
{
  bool Res = true;
  rDoc.ForEachMemoryArea([&](MemoryArea const& rMemArea)
  {
    Address const& rMemAreaAddr = rMemArea.GetBaseAddress();
    u32 MemAreaSize             = rMemArea.GetSize();
    u32 MemAreaFileSize         = rMemArea.GetFileSize();

    void* pRawMemory;
    u64 LinearAddress;
    if (pCpuCtxt->Translate(rMemAreaAddr, LinearAddress) == false)
      LinearAddress = rMemAreaAddr.GetOffset();

    if (AllocateMemory(LinearAddress, MemAreaSize, &pRawMemory) == false)
    {
      Res = false;
      return;
    }

    // TODO: Do we have to zero-out memory?
    if (MemAreaFileSize == 0x0)
      return;

    TOffset MemAreaFileOff;
    if (rMemArea.ConvertOffsetToFileOffset(rMemAreaAddr.GetOffset(), MemAreaFileOff) == false)
      return;

    if (!rDoc.GetBinaryStream().Read(MemAreaFileOff, pRawMemory, MemAreaFileSize))
    {
      FreeMemory(LinearAddress);
      Res = false;
      return;
    }
  });
  return Res;
}
Example #24
0
void AddBlock(int iSeconds, struct in_addr* piaPeer)
{
	block_node* pBlock = FindBlock(piaPeer);
	int iExpires = (iSeconds < 0)? -1 : GetTime() + iSeconds;

    // A block set to expire at -1 will stay in effect until all blocks are deleted.
	// (Usually when server is shut down and later restarted.)

	if (pBlock)
	{
		if (pBlock->iExpires >= 0)
			pBlock->iExpires = iExpires;
		return;
	}

	pBlock = (block_node *) AllocateMemory(MALLOC_ID_BLOCK,sizeof(block_node));
	if (pBlock)
	{
		pBlock->iExpires = iExpires;
		pBlock->iaPeer = *piaPeer;
		pBlock->next = block_head;
		block_head = pBlock;
	}
}
Example #25
0
int main(int argc, char ** argv)
{
    //-----------------------
    // Input pointers

    float           *h_fMRI_Volumes = NULL;
    float           *h_Certainty = NULL;

    //--------------

    void*           allMemoryPointers[500];
    for (int i = 0; i < 500; i++)
    {
        allMemoryPointers[i] = NULL;
    }

    nifti_image*	allNiftiImages[500];
    for (int i = 0; i < 500; i++)
    {
        allNiftiImages[i] = NULL;
    }

    int             numberOfMemoryPointers = 0;
    int				numberOfNiftiImages = 0;

    size_t			allocatedHostMemory = 0;

    //--------------

    // Default parameters
    int             OPENCL_PLATFORM = 0;
    int             OPENCL_DEVICE = 0;
    bool            DEBUG = false;
    const char*     FILENAME_EXTENSION = "_sm";
    bool            PRINT = true;
    bool			VERBOS = false;

    size_t          DATA_W, DATA_H, DATA_D, DATA_T;
    float           EPI_VOXEL_SIZE_X, EPI_VOXEL_SIZE_Y, EPI_VOXEL_SIZE_Z;

    bool			CHANGE_OUTPUT_FILENAME = false;

    // Settings

    float           EPI_SMOOTHING_AMOUNT = 6.0f;
    bool			MASK = false;
    bool			AUTO_MASK = false;
    const char*		MASK_NAME;

    //-----------------------
    // Output parameters

    const char      *outputFilename;

    //---------------------

    /* Input arguments */
    FILE *fp = NULL;

    // No inputs, so print help text
    if (argc == 1)
    {
        printf("Usage:\n\n");
        printf("Smoothing input.nii [options]\n\n");
        printf("Options:\n\n");
        printf(" -platform        The OpenCL platform to use (default 0) \n");
        printf(" -device          The OpenCL device to use for the specificed platform (default 0) \n");
        printf(" -fwhm            Amount of smoothing to apply (in mm, default 6 mm) \n");
        printf(" -mask            Perform smoothing inside mask (normalized convolution) \n");
        printf(" -automask        Generate a mask and perform smoothing inside mask (normalized convolution) \n");
        printf(" -output          Set output filename (default input_sm.nii) \n");
        printf(" -quiet           Don't print anything to the terminal (default false) \n");
        printf(" -verbose         Print extra stuff (default false) \n");
        printf("\n\n");

        return EXIT_SUCCESS;
    }
    // Try to open file
    else if (argc > 1)
    {
        fp = fopen(argv[1],"r");
        if (fp == NULL)
        {
            printf("Could not open file %s !\n",argv[1]);
            return EXIT_FAILURE;
        }
        fclose(fp);
    }

    // Loop over additional inputs
    int i = 2;
    while (i < argc)
    {
        char *input = argv[i];
        char *p;
        if (strcmp(input,"-platform") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -platform !\n");
                return EXIT_FAILURE;
            }

            OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10);

            if (!isspace(*p) && *p != 0)
            {
                printf("OpenCL platform must be an integer! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if (OPENCL_PLATFORM < 0)
            {
                printf("OpenCL platform must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-device") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -device !\n");
                return EXIT_FAILURE;
            }

            OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10);

            if (!isspace(*p) && *p != 0)
            {
                printf("OpenCL device must be an integer! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if (OPENCL_DEVICE < 0)
            {
                printf("OpenCL device must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-fwhm") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -fwhm !\n");
                return EXIT_FAILURE;
            }

            EPI_SMOOTHING_AMOUNT = (float)strtod(argv[i+1], &p);

            if (!isspace(*p) && *p != 0)
            {
                printf("Smoothing must be a float! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if ( EPI_SMOOTHING_AMOUNT <= 0.0f )
            {
                printf("Smoothing must be > 0.0 !\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-mask") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read name after -mask !\n");
                return EXIT_FAILURE;
            }

            MASK = true;
            MASK_NAME = argv[i+1];
            i += 2;
        }
        else if (strcmp(input,"-automask") == 0)
        {
            AUTO_MASK = true;
            i += 1;
        }
        else if (strcmp(input,"-debug") == 0)
        {
            DEBUG = true;
            i += 1;
        }
        else if (strcmp(input,"-quiet") == 0)
        {
            PRINT = false;
            i += 1;
        }
        else if (strcmp(input,"-verbose") == 0)
        {
            VERBOS = true;
            i += 1;
        }
        else if (strcmp(input,"-output") == 0)
        {
            CHANGE_OUTPUT_FILENAME = true;

            if ( (i+1) >= argc  )
            {
                printf("Unable to read name after -output !\n");
                return EXIT_FAILURE;
            }

            outputFilename = argv[i+1];
            i += 2;
        }
        else
        {
            printf("Unrecognized option! %s \n",argv[i]);
            return EXIT_FAILURE;
        }
    }

    // Check if BROCCOLI_DIR variable is set
    if (getenv("BROCCOLI_DIR") == NULL)
    {
        printf("The environment variable BROCCOLI_DIR is not set!\n");
        return EXIT_FAILURE;
    }

    double startTime = GetWallTime();

    // ---------------------
    // Read data
    // ---------------------
    nifti_image *inputData = nifti_image_read(argv[1],1);

    if (inputData == NULL)
    {
        printf("Could not open nifti file!\n");
        return EXIT_FAILURE;
    }
    allNiftiImages[numberOfNiftiImages] = inputData;
    numberOfNiftiImages++;

    // -----------------------
    // Read mask
    // -----------------------

    nifti_image *inputMask;
    if (MASK)
    {
        inputMask = nifti_image_read(MASK_NAME,1);
        if (inputMask == NULL)
        {
            printf("Could not open mask volume!\n");
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
        allNiftiImages[numberOfNiftiImages] = inputMask;
        numberOfNiftiImages++;
    }

    double endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to read the nifti file\n",(float)(endTime - startTime));
    }

    // Get data dimensions
    DATA_W = inputData->nx;
    DATA_H = inputData->ny;
    DATA_D = inputData->nz;
    DATA_T = inputData->nt;

    // Check if mask volume has the same dimensions as the data
    if (MASK)
    {
        size_t TEMP_DATA_W = inputMask->nx;
        size_t TEMP_DATA_H = inputMask->ny;
        size_t TEMP_DATA_D = inputMask->nz;

        if ( (TEMP_DATA_W != DATA_W) || (TEMP_DATA_H != DATA_H) || (TEMP_DATA_D != DATA_D) )
        {
            printf("Input data has the dimensions %zu x %zu x %zu, while the mask volume has the dimensions %zu x %zu x %zu. Aborting! \n",DATA_W,DATA_H,DATA_D,TEMP_DATA_W,TEMP_DATA_H,TEMP_DATA_D);
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
    }

    // Get voxel sizes
    EPI_VOXEL_SIZE_X = inputData->dx;
    EPI_VOXEL_SIZE_Y = inputData->dy;
    EPI_VOXEL_SIZE_Z = inputData->dz;

    // Calculate size, in bytes
    size_t DATA_SIZE = DATA_W * DATA_H * DATA_D * DATA_T * sizeof(float);
    size_t VOLUME_SIZE = DATA_W * DATA_H * DATA_D * sizeof(float);

    // Print some info
    if (PRINT)
    {
        printf("Authored by K.A. Eklund \n");
        printf("Data size: %zu x %zu x %zu x %zu \n",  DATA_W, DATA_H, DATA_D, DATA_T);
        printf("Voxel size: %f x %f x %f mm \n", EPI_VOXEL_SIZE_X, EPI_VOXEL_SIZE_Y, EPI_VOXEL_SIZE_Z);
        printf("Smoothing filter size: %f mm \n", EPI_SMOOTHING_AMOUNT);
    }

    // ------------------------------------------------

    // Allocate memory on the host

    startTime = GetWallTime();

    // If the data is in float format, we can just copy the pointer
    if ( inputData->datatype != DT_FLOAT )
    {
        AllocateMemory(h_fMRI_Volumes, DATA_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, allocatedHostMemory, "INPUT_DATA");
    }
    else
    {
        allocatedHostMemory += DATA_SIZE;
    }
    AllocateMemory(h_Certainty, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, allocatedHostMemory, "CERTAINTY");

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to allocate memory\n",(float)(endTime - startTime));
    }

    startTime = GetWallTime();

    // Convert data to floats
    if ( inputData->datatype == DT_SIGNED_SHORT )
    {
        short int *p = (short int*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT8 )
    {
        unsigned char *p = (unsigned char*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT16 )
    {
        unsigned short int *p = (unsigned short int*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    // Correct data type, just copy the pointer
    else if ( inputData->datatype == DT_FLOAT )
    {
        h_fMRI_Volumes = (float*)inputData->data;

        // Save the pointer in the pointer list
        allMemoryPointers[numberOfMemoryPointers] = (void*)h_fMRI_Volumes;
        numberOfMemoryPointers++;

        //float *p = (float*)inputData->data;

        //for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        //{
        //    h_fMRI_Volumes[i] = p[i];
        //}
    }
    else
    {
        printf("Unknown data type in input data, aborting!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }

    // Free input fMRI data, it has been converted to floats
    if ( inputData->datatype != DT_FLOAT )
    {
        free(inputData->data);
        inputData->data = NULL;
    }
    // Pointer has been copied to h_fMRI_Volumes and pointer list, so set the input data pointer to NULL
    else
    {
        inputData->data = NULL;
    }

    // Mask is provided by user
    if (MASK)
    {
        if ( inputMask->datatype == DT_SIGNED_SHORT )
        {
            short int *p = (short int*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else if ( inputMask->datatype == DT_UINT16 )
        {
            unsigned short int *p = (unsigned short int*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else if ( inputMask->datatype == DT_FLOAT )
        {
            float *p = (float*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = p[i];
            }
        }
        else if ( inputMask->datatype == DT_UINT8 )
        {
            unsigned char *p = (unsigned char*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else
        {
            printf("Unknown data type in mask volume, aborting!\n");
            FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
    }
    // Mask is NOT provided by user, set all mask voxels to 1
    else
    {
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Certainty[i] = 1.0f;
        }
    }

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to convert data to floats\n",(float)(endTime - startTime));
    }

    //------------------------

    startTime = GetWallTime();

    // Initialize BROCCOLI
    BROCCOLI_LIB BROCCOLI(OPENCL_PLATFORM,OPENCL_DEVICE,2,VERBOS); // 2 = Bash wrapper

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to initiate BROCCOLI\n",(float)(endTime - startTime));
    }

    // Print build info to file (always)
    std::vector<std::string> buildInfo = BROCCOLI.GetOpenCLBuildInfo();
    std::vector<std::string> kernelFileNames = BROCCOLI.GetKernelFileNames();

    std::string buildInfoPath;
    buildInfoPath.append(getenv("BROCCOLI_DIR"));
    buildInfoPath.append("compiled/Kernels/");

    for (int k = 0; k < BROCCOLI.GetNumberOfKernelFiles(); k++)
    {
        std::string temp = buildInfoPath;
        temp.append("buildInfo_");
        temp.append(BROCCOLI.GetOpenCLPlatformName());
        temp.append("_");
        temp.append(BROCCOLI.GetOpenCLDeviceName());
        temp.append("_");
        std::string name = kernelFileNames[k];
        // Remove "kernel" and ".cpp" from kernel filename
        name = name.substr(0,name.size()-4);
        name = name.substr(6,name.size());
        temp.append(name);
        temp.append(".txt");
        fp = fopen(temp.c_str(),"w");
        if (fp == NULL)
        {
            printf("Could not open %s for writing ! \n",temp.c_str());
        }
        else
        {
            if (buildInfo[k].c_str() != NULL)
            {
                int error = fputs(buildInfo[k].c_str(),fp);
                if (error == EOF)
                {
                    printf("Could not write to %s ! \n",temp.c_str());
                }
            }
            fclose(fp);
        }
    }

    // Something went wrong...
    if (!BROCCOLI.GetOpenCLInitiated())
    {
        printf("Initialization error is \"%s\" \n",BROCCOLI.GetOpenCLInitializationError().c_str());
        printf("OpenCL error is \"%s\" \n",BROCCOLI.GetOpenCLError());

        // Print create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[i]));
            }
        }

        printf("OpenCL initialization failed, aborting! \nSee buildInfo* for output of OpenCL compilation!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }
    // Initialization OK
    else
    {
        // Set all necessary pointers and values
        BROCCOLI.SetInputfMRIVolumes(h_fMRI_Volumes);
        BROCCOLI.SetAutoMask(AUTO_MASK);
        BROCCOLI.SetInputCertainty(h_Certainty);

        BROCCOLI.SetEPISmoothingAmount(EPI_SMOOTHING_AMOUNT);
        BROCCOLI.SetAllocatedHostMemory(allocatedHostMemory);

        BROCCOLI.SetEPIWidth(DATA_W);
        BROCCOLI.SetEPIHeight(DATA_H);
        BROCCOLI.SetEPIDepth(DATA_D);
        BROCCOLI.SetEPITimepoints(DATA_T);

        BROCCOLI.SetEPIVoxelSizeX(EPI_VOXEL_SIZE_X);
        BROCCOLI.SetEPIVoxelSizeY(EPI_VOXEL_SIZE_Y);
        BROCCOLI.SetEPIVoxelSizeZ(EPI_VOXEL_SIZE_Z);

        // Run the actual slice timing correction
        startTime = GetWallTime();
        BROCCOLI.PerformSmoothingNormalizedHostWrapper();
        endTime = GetWallTime();

        if (VERBOS)
        {
            printf("\nIt took %f seconds to run the smoothing\n",(float)(endTime - startTime));
        }

        // Print create buffer errors
        int* createBufferErrors = BROCCOLI.GetOpenCLCreateBufferErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createBufferErrors[i] != 0)
            {
                printf("Create buffer error %i is %s \n",i,BROCCOLI.GetOpenCLErrorMessage(createBufferErrors[i]));
            }
        }

        // Print create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[i]));
            }
        }

        // Print run kernel errors
        int* runKernelErrors = BROCCOLI.GetOpenCLRunKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (runKernelErrors[i] != 0)
            {
                printf("Run kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(runKernelErrors[i]));
            }
        }
    }

    // Write results to file
    startTime = GetWallTime();

    if (!CHANGE_OUTPUT_FILENAME)
    {
        WriteNifti(inputData,h_fMRI_Volumes,FILENAME_EXTENSION,ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
    }
    else
    {
        nifti_set_filenames(inputData, outputFilename, 0, 1);
        WriteNifti(inputData,h_fMRI_Volumes,"",DONT_ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
    }

    if (AUTO_MASK)
    {
        nifti_image *outputNiftifMRISingleVolume = nifti_copy_nim_info(inputData);
        outputNiftifMRISingleVolume->nt = 1;
        outputNiftifMRISingleVolume->dim[0] = 3;
        outputNiftifMRISingleVolume->dim[4] = 1;
        outputNiftifMRISingleVolume->nvox = DATA_W * DATA_H * DATA_D;
        allNiftiImages[numberOfNiftiImages] = outputNiftifMRISingleVolume;
        numberOfNiftiImages++;

        if (!CHANGE_OUTPUT_FILENAME)
        {
            WriteNifti(outputNiftifMRISingleVolume,h_Certainty,"_mask",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
        }
        else
        {
            nifti_set_filenames(outputNiftifMRISingleVolume, outputFilename, 0, 1);
            WriteNifti(outputNiftifMRISingleVolume,h_Certainty,"_mask",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
        }
    }

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to write the nifti file\n",(float)(endTime - startTime));
    }

    // Free all memory
    FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
    FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);

    return EXIT_SUCCESS;
}
Example #26
0
void SetAccountPasswordAlreadyEncrypted(account_node *a,char *password)
{
   FreeMemory(MALLOC_ID_ACCOUNT,a->password,strlen(a->password)+1);
   a->password = (char *)AllocateMemory(MALLOC_ID_ACCOUNT,strlen(password)+1);
   strcpy(a->password,password);
}
Example #27
0
void SetAccountName(account_node *a,char *name)
{
   FreeMemory(MALLOC_ID_ACCOUNT,a->name,strlen(a->name)+1);
   a->name = (char *)AllocateMemory(MALLOC_ID_ACCOUNT,strlen(name)+1);
   strcpy(a->name,name);
}
Example #28
0
    int main(int argc, char **argv)
    {
        struct sockaddr_in addr;
        int sock_fd, addrlen;

        /* 获得程序工作的参数,如 IP 、端口、监听数、网页根目录、目录存放位置等 */
        getoption(argc, argv);

        if (!host) {
            addrlen = strlen(DEFAULTIP);
            AllocateMemory(&host, addrlen, DEFAULTIP);
        }
        if (!port) {
            addrlen = strlen(DEFAULTPORT);
            AllocateMemory(&port, addrlen, DEFAULTPORT);
        }
        if (!back) {
            addrlen = strlen(DEFAULTBACK);
            AllocateMemory(&back, addrlen, DEFAULTBACK);
        }
        if (!dirroot) {
            addrlen = strlen(DEFAULTDIR);
            AllocateMemory(&dirroot, addrlen, DEFAULTDIR);
        }
        if (!logdir) {
            addrlen = strlen(DEFAULTLOG);
            AllocateMemory(&logdir, addrlen, DEFAULTLOG);
        }

        printf
            ("host=%s port=%s back=%s dirroot=%s logdir=%s %s是后台工作模式(进程ID:%d)\n",
             host, port, back, dirroot, logdir, daemon_y_n?"":"不", getpid());

        /* fork() 两次处于后台工作模式下 */
        if (daemon_y_n) {
            if (fork())
                exit(0);
            if (fork())
                exit(0);
            close(0), close(1), close(2);
            logfp = fopen(logdir, "a+");
            if (!logfp)
                exit(0);
        }

        /* 处理子进程退出以免产生僵尸进程 */
        signal(SIGCHLD, SIG_IGN);

        /* 创建 socket */
        if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
            if (!daemon_y_n) {
                prterrmsg("socket()");
            } else {
                wrterrmsg("socket()");
            }
        }

        /* 设置端口快速重用 */
        addrlen = 1;
        setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,
                   sizeof(addrlen));

        addr.sin_family = AF_INET;
        addr.sin_port = htons(atoi(port));
        addr.sin_addr.s_addr = inet_addr(host);
        addrlen = sizeof(struct sockaddr_in);
        /* 绑定地址、端口等信息 */
        if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0) {
            if (!daemon_y_n) {
                prterrmsg("bind()");
            } else {
                wrterrmsg("bind()");
            }
        }

        /* 开启临听 */
        if (listen(sock_fd, atoi(back)) < 0) {
            if (!daemon_y_n) {
                prterrmsg("listen()");
            } else {
                wrterrmsg("listen()");
            }
        }
        while (1) {
            int len;
            int new_fd;
            addrlen = sizeof(struct sockaddr_in);
            /* 接受新连接请求 */
            new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
            if (new_fd < 0) {
                if (!daemon_y_n) {
                    prterrmsg("accept()");
                } else {
                    wrterrmsg("accept()");
                }
                break;
            }
            bzero(buffer, MAXBUF + 1);
            sprintf(buffer, "连接来自于: %s:%d\n",
                    inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
            if (!daemon_y_n) {
                prtinfomsg(buffer);
            } else {
                wrtinfomsg(buffer);
            }
            /* 产生一个子进程去处理请求,当前进程继续等待新的连接到来 */
            if (!fork()) {
                bzero(buffer, MAXBUF + 1);
                if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0) {
                    FILE *ClientFP = fdopen(new_fd, "w");
                    if (ClientFP == NULL) {
                        if (!daemon_y_n) {
                            prterrmsg("fdopen()");
                        } else {
                            prterrmsg("fdopen()");
                        }
                    } else {
                        char Req[MAXPATH + 1] = "";
                        sscanf(buffer, "GET %s HTTP", Req);
                        bzero(buffer, MAXBUF + 1);
                        sprintf(buffer, "请求取文件: \"%s\"\n", Req);
                        if (!daemon_y_n) {
                            prtinfomsg(buffer);
                        } else {
                            wrtinfomsg(buffer);
                        }
                        /* 处理用户请求 */
                        GiveResponse(ClientFP, Req);
                        fclose(ClientFP);
                    }
                }
                exit(0);
            }
            close(new_fd);
        }
        close(sock_fd);
        return 0;
    }
Example #29
0
MainWindow::MainWindow( QWidget * parent)
	: QMainWindow(parent)
{
    setupUi(this);

    version = "2015-08-28";

    inimage = false;
    x1drag = false;
    x2drag = false;
    y1drag = false;
    y2drag = false;

    image = QImage();
    pixmap = scene.addPixmap(QPixmap());
    pixmap->setZValue(0);

    QPen pen;
    pen.setColor(QColor(255,255,0));
    pen.setStyle(Qt::DashLine);
    // limit lines
    x1line = scene.addLine(QLineF(), pen);
    x1line->setZValue(1);
    x2line = scene.addLine(QLineF(), pen);
    x2line->setZValue(1);
    y1line = scene.addLine(QLineF(), pen);
    y1line->setZValue(1);
    y2line = scene.addLine(QLineF(), pen);
    y2line->setZValue(1);

    pen.setColor(QColor(255,0,0));
    pen.setStyle(Qt::SolidLine);
    // projections, beam profile, centroid
    xprojection = scene.addPath(QPainterPath(), pen);
    xprojection->setZValue(2);
    yprojection = scene.addPath(QPainterPath(), pen);
    yprojection->setZValue(2);
    ellipse = scene.addEllipse(0,0,0,0, pen);
    ellipse->setZValue(2);
    centerAline = scene.addLine(QLineF(), pen);
    centerAline->setZValue(2);
    centerBline = scene.addLine(QLineF(), pen);
    centerBline->setZValue(2);

    QObject::connect(&scene, SIGNAL(mouseMoved()), this, SLOT(mouseMovedOnScene()));
    QObject::connect(&scene, SIGNAL(mousePressed()), this, SLOT(mousePressedOnScene()));
    QObject::connect(&scene, SIGNAL(mouseReleased()), this, SLOT(mouseReleasedOnScene()));
    QObject::connect(&scene, SIGNAL(mouseLeft()), this, SLOT(mouseLeftScene()));

    graphicsView->setScene(&scene);
    graphicsView->setContextMenuPolicy(Qt::CustomContextMenu);

    X1SpinBox->setRange(0, MAX_HEIGHT-1);
    X2SpinBox->setRange(0, MAX_HEIGHT-1);
    Y1SpinBox->setRange(0, MAX_WIDTH-1);
    Y2SpinBox->setRange(0, MAX_WIDTH-1);

    scaleLabel->setScaledContents(true);

    AllocateMemory();

    dataloaded = false;
    refloaded = false;
    RestoreSession();

    LoadRef(reffile);
    LoadData(datafile);

    // Scale image
    scale = QImage(20, 256, QImage::Format_Indexed8);
    SetColorTable();
    for(int i=0; i<20; i++)
	for(int j=0; j<=255; j++)
	    scale.setPixel(i, j, 255-j);
    scaleLabel->setPixmap(QPixmap::fromImage(scale));

    graphicsView->scale(pow(2,zoom/2), pow(2,zoom/2));

    InitializeShortcuts();
    UpdateVisibility();
}
Example #30
0
int main(int argc, char **argv)
{
	struct sockaddr_in addr;
	int sock_fd, addrlen;
	
	getoption(argc, argv);

	if (!host) {
		addrlen = strlen(DEFAULTIP);
		AllocateMemory(&host, addrlen, DEFAULTIP);
	}
	if (!port) {
		addrlen = strlen(DEFAULTPORT);
		AllocateMemory(&port, addrlen, DEFAULTPORT);
	}
	if (!back) {
		addrlen = strlen(DEFAULTBACK);
		AllocateMemory(&back, addrlen, DEFAULTBACK);
	}
	if (!dirroot) {
		addrlen = strlen(DEFAULTDIR);
		AllocateMemory(&dirroot, addrlen, DEFAULTDIR);
	}
	if (!logdir) {
		addrlen = strlen(DEFAULTLOG);
		AllocateMemory(&logdir, addrlen, DEFAULTLOG);
	}

	printf
		("host=%s port=%s back=%s dirroot=%s logdir=%s %s daemon mode (pID:%d)\n",
		 host, port, back, dirroot, logdir, daemon_y_n?"":"is not", getpid());

	/* fork() twice for daemon  */
	if (daemon_y_n) {
		if (fork())
		  exit(0);
		if (fork())
		  exit(0);
		close(0), close(1), close(2);
		logfp = fopen(logdir, "a+");
		if (!logfp)
		  exit(0);
	}

	signal(SIGCHLD, SIG_IGN);

	if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		if (!daemon_y_n) {
			prterrmsg("socket()");
		} else {
			wrterrmsg("socket()");
		}
	}

	addrlen = 1;
	setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,
				sizeof(addrlen));

	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(port));
	addr.sin_addr.s_addr = inet_addr(host);
	addrlen = sizeof(struct sockaddr_in);
	
	if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0) {
		if (!daemon_y_n) {
			prterrmsg("bind()");
		} else {
			wrterrmsg("bind()");
		}
	}

	if (listen(sock_fd, atoi(back)) < 0) {
		if (!daemon_y_n) {
			prterrmsg("listen()");
		} else {
			wrterrmsg("listen()");
		}
	}
	while (1) {
		int len;
		int new_fd;
		addrlen = sizeof(struct sockaddr_in);
		
		new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
		if (new_fd < 0) {
			if (!daemon_y_n) {
				prterrmsg("accept()");
			} else {
				wrterrmsg("accept()");
			}
			break;
		}
		bzero(buffer, MAXBUF + 1);
		sprintf(buffer, "connection from : %s:%d\n",
					inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
		if (!daemon_y_n) {
			prtinfomsg(buffer);
		} else {
			wrtinfomsg(buffer);
		}
		
		if (!fork()) {
			bzero(buffer, MAXBUF + 1);
			if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0) {
				FILE *ClientFP = fdopen(new_fd, "w");
				if (ClientFP == NULL) {
					if (!daemon_y_n) {
						prterrmsg("fdopen()");
					} else {
						prterrmsg("fdopen()");
					}
				} else {
					char Req[MAXPATH + 1] = "";
					sscanf(buffer, "GET %s HTTP", Req);
					bzero(buffer, MAXBUF + 1);
					sprintf(buffer, "request file : \"%s\"\n", Req);
					if (!daemon_y_n) {
						prtinfomsg(buffer);
					} else {
						wrtinfomsg(buffer);
					}
					
					GiveResponse(ClientFP, Req);
					fclose(ClientFP);
				}
			}
			exit(0);
		}
		close(new_fd);
	}
	close(sock_fd);
	return 0;
}