コード例 #1
0
ファイル: ShaderCache.cpp プロジェクト: xukunn1226/VRI3
void FShaderCache::Load(FArchive& Ar)
{
	Ar << m_nPlatform;

	UINT NumShaderBuilderCRC = 0;
	Ar << NumShaderBuilderCRC;
	for(UINT IndexBuilder = 0; IndexBuilder < NumShaderBuilderCRC; ++IndexBuilder)
	{
		FShaderBuilder* ShaderBuilder = NULL;
		Ar << ShaderBuilder;
		DWORD CRC = 0;
		Ar << CRC;

		if( ShaderBuilder )
		{
			m_mapShaderBuilderCRC[ShaderBuilder] = CRC;
		}
	}

	// serialize the global shaders
	UINT NumShaders = 0;
	UINT NumDesertedShaders = 0; 
	UINT NumRedundantShaders = 0;
	vector<FString> OutdatedShaderBuilders;

	Ar << NumShaders;
	for(UINT IndexShader = 0; IndexShader < NumShaders; ++IndexShader)
	{
		FShaderBuilder* ShaderBuilder = NULL;
		FGuid ShaderId;
		Ar << ShaderBuilder << ShaderId;

		INT SkipOffset = 0;
		Ar << SkipOffset;

		if( !ShaderBuilder )
		{
			++NumDesertedShaders;
			Ar.Seek(SkipOffset);		// this shader builder doesn't exist any more, skip the shader
		}
		else
		{
			DWORD CurrentCRC = 0;
			DWORD SavedCRC = 0;

			// 比较当前与之前版本的CRC,检测是否有改动
			CurrentCRC = ShaderBuilder->GetSourceCRC();
			map<FShaderBuilder*, DWORD>::const_iterator it = m_mapShaderBuilderCRC.find(ShaderBuilder);
			if( it != m_mapShaderBuilderCRC.end() )
			{
				SavedCRC = it->second;
			}

			FShader* Shader = ShaderBuilder->FindShaderById(ShaderId);
			if( Shader )
			{
				++NumRedundantShaders;
				Ar.Seek(SkipOffset);		// has already exist, skip it		
			}
			else if( SavedCRC != CurrentCRC )
			{
				++NumDesertedShaders;
				Ar.Seek(SkipOffset);
				if( SavedCRC != 0 )			// denote SHADER BUILDER exists, but it has changed
				{
					OutdatedShaderBuilders.push_back(ShaderBuilder->GetShaderName());
				}
			}
			else
			{
				// the shader is compatiable, create it
				Shader = ShaderBuilder->ConstructSerialization();

				UBOOL bShaderHasOutdatedParameters = Shader->Serialize(Ar);
				if( bShaderHasOutdatedParameters )
				{
					ShaderBuilder->UnregisterShader(Shader);
					delete Shader;
				}
				check(Ar.Tell() == SkipOffset);
			}
		}
	}

	if( OutdatedShaderBuilders.size() > 0 )
	{
		debugf(TEXT("Skip %d outdated FShaderBuilder"), OutdatedShaderBuilders.size());
		for(UINT IndexBuilder = 0; IndexBuilder < OutdatedShaderBuilders.size(); ++IndexBuilder)
		{
			debugf(TEXT("	%s"), OutdatedShaderBuilders.at(IndexBuilder).c_str());
		}
	}

	if( NumShaders > 0 )
	{
		debugf(TEXT("Loaded %d shaders (%d deserted, %d redundant)"), NumShaders, NumDesertedShaders, NumRedundantShaders);
	}
}
コード例 #2
0
int jvm_core_core_handler(struct _JVM *jvm, struct _JVMBundle *bundle, struct _JVMClass *jclass,
                               uint8 *method8, uint8 *type8, JVMLocal *locals,
                               int localCnt, JVMLocal *result) {
  int                   x;
  int                   c;
  int                   error;
  JVMBundleClass        *cbc;
  JVMObject             *jobject;
  JVMObject             *sobject;
  JVMObject             *pobject;
  uint8                 *cn;
  uint8                 lbuf[128];
  uint8                 *buf;
  FILE                  *fp;
  struct stat           _stat;
  JVMObject             *_jobject;
  
  debugf("success:%s:%s\n", method8, type8);
  // determine what is being called
  for (x = 0, c = 0; method8[x] != 0; ++x)
    c += method8[x];

  debugf("native:%s:%x\n", method8, c);
  //jvm_exit(-5);
  switch (c) {
    // Collect
    case 0x2c6:
      jvm_Collect(jvm);
      result->data = 0;
      result->flags = 0;
      break;
    // LoadResource
    case 0x4c8:
      sobject = (JVMObject*)locals[0].data;
      debugf("sobject %x\n", sobject);
      if (!sobject)
        break;
      pobject = (JVMObject*)sobject->_fields[0].value;
      for (c = 0; c < pobject->fieldCnt; ++c)
        lbuf[c] = ((uint8*)pobject->fields)[c];
      lbuf[c] = 0;

      fp = fopen(&lbuf[0], "rb");
      fstat(fileno(fp), &_stat);
      c = _stat.st_size;
      buf = (uint8*)jvm_malloc(sizeof(uint8) * c);
      fread(&buf[0], c, 1, fp);
      fclose(fp);

      error = jvm_CreatePrimArray(jvm, bundle, JVM_ATYPE_BYTE, c, &_jobject, buf);
      if (error)
        return error;
      result->data = (uint64)_jobject;
      result->flags = JVM_STACK_ISARRAYREF | JVM_STACK_ISOBJECTREF | JVM_STACK_ISBYTE;
      break;
    // Exit
    case 0x19a:
      jvm_exit(-1);
      break;
    // Print
    case 0x20d:
      sobject = (JVMObject*)locals[0].data;
      debugf("sobject %x\n", sobject);
      if (!sobject)
        break;
      pobject = (JVMObject*)sobject->_fields[0].value;
      debugf("pobject %x %u\n", pobject, sobject->fieldCnt);
      if (!pobject)
        break;

      debugf("##:printc[%u]:", pobject->fieldCnt);
      for (c = 0; c < pobject->fieldCnt; ++c) {
        jvm_printf("%c", ((uint16*)pobject->fields)[c]);
      }
      jvm_printf("\n");
      exit(-3);
      break;
    // EnumClasses
    case 0x463:
      // get count of classes
      for (c = 0, cbc = bundle->first; cbc != 0; cbc = cbc->next, ++c);
      error = jvm_CreateObjectArray(jvm, bundle, "java/lang/String", c, &jobject);
      if (error) {
        return error;
      }
      for (c = 0, cbc = bundle->first; cbc != 0; cbc = cbc->next, ++c) {
        // create string object
        error = jvm_CreateObject(jvm, bundle, "java/lang/String", &sobject);
        if (error)
          return error;
        // get string we need to put in it
        cn = jvm_GetClassNameFromClass(cbc->jclass);
        // get length of that string
        for (x = 0; cn[x] != 0; ++x);
        // create primitive array to hold string
        error = jvm_CreatePrimArray(jvm, bundle, JVM_ATYPE_BYTE, x, &pobject, 0);
        // fill primitive array
        for (x = 0; cn[x] != 0; ++x)
          ((uint8*)pobject->fields)[x] = cn[x];
        if (error)
           return error;
        // add primitive array to String field
        sobject->_fields[0].value = (uintptr)pobject;
        sobject->_fields[0].jclass = 0;
        sobject->_fields[0].aflags = JVM_STACK_ISOBJECTREF | JVM_STACK_ISARRAYREF;
        // add to object array of String
        jobject->fields[c] = (uint64)sobject;
        //jvm_exit(-5);
      }
      // return the object array of String
      result->data = (uintptr)jobject;
      result->flags = JVM_STACK_ISOBJECTREF | JVM_STACK_ISARRAYREF;
      return JVM_SUCCESS;
  }
  return JVM_SUCCESS;
}
コード例 #3
0
ファイル: fuse-ext2.c プロジェクト: pexip/os-fuse-umfuse-ext2
int main (int argc, char *argv[])
{
	int err = 0;
	struct stat sbuf;
	char *parsed_options = NULL;
	struct fuse_args fargs = FUSE_ARGS_INIT(0, NULL);
	struct extfs_data opts;

	debugf("version:'%s', fuse_version:'%d'", VERSION, fuse_version());

	memset(&opts, 0, sizeof(opts));

	if (parse_options(argc, argv, &opts)) {
		usage();
		return -1;
	}

	if (stat(opts.device, &sbuf)) {
		debugf_main("Failed to access '%s'", opts.device);
		err = -3;
		goto err_out;
	}

	parsed_options = parse_mount_options(opts.options ? opts.options : "", &opts);
	if (!parsed_options) {
		err = -2;
		goto err_out;
	}

	if (do_probe(&opts) != 0) {
		debugf_main("Probe failed");
		err = -4;
		goto err_out;
	}

	debugf_main("opts.device: %s", opts.device);
	debugf_main("opts.mnt_point: %s", opts.mnt_point);
	debugf_main("opts.volname: %s", (opts.volname != NULL) ? opts.volname : "");
	debugf_main("opts.options: %s", opts.options);
	debugf_main("parsed_options: %s", parsed_options);

	if (fuse_opt_add_arg(&fargs, PACKAGE) == -1 ||
	    fuse_opt_add_arg(&fargs, "-s") == -1 ||
	    fuse_opt_add_arg(&fargs, "-o") == -1 ||
	    fuse_opt_add_arg(&fargs, parsed_options) == -1 ||
	    fuse_opt_add_arg(&fargs, opts.mnt_point) == -1) {
		debugf_main("Failed to set FUSE options");
		fuse_opt_free_args(&fargs);
		err = -5;
		goto err_out;
	}

	if (opts.readonly == 0) {
		debugf_main("mounting read-write");
	} else {
		debugf_main("mounting read-only");
	}

	fuse_main(fargs.argc, fargs.argv, &ext2fs_ops, &opts);

err_out:
	fuse_opt_free_args(&fargs);
	free(parsed_options);
	free(opts.options);
	free(opts.device);
	free(opts.volname);
	free(opts.ext2_options);
	return err;
}
コード例 #4
0
ファイル: commonpal.c プロジェクト: pdh11/intergif
BOOL Anim_CommonPalette( anim a )
{
    unsigned int colours[256];
    unsigned int nColours = 0;
    unsigned int nThisFrame;
    pixel *image, *mask;
    pixel map[256];
    unsigned char used[256];
    unsigned char dstused[256];
    unsigned int i, j;
    unsigned int len = a->nWidth * a->nHeight;
    BOOL result = TRUE;
    BOOL compatible;
    frame f;
    unsigned int mincolours = 0;
    unsigned int nUsedOnFrame;

    image = Anim_Allocate( len );
    mask  = Anim_Allocate( len );
    if ( !image || !mask )
    {
        Anim_NoMemory( "commonpal" );
        result = FALSE;
    }
    else
    {
        Workspace_Claim( gifcompress_WORKSIZE );

        for ( i=0; i < a->nFrames; i++ )
        {
            f = a->pFrames + i;

            if ( !Anim_Decompress( f->pImageData, f->nImageSize, len, image ) )
            {
                result = FALSE;
                break;
            }

            if ( f->pMaskData )
            {
                if ( !Anim_Decompress( f->pMaskData, f->nMaskSize, len, mask ) )
                {
                    result = FALSE;
                    break;
                }
            }
            else
                memset( mask, 1, len );     /* all solid */

            memset( used, 0, 256 );

            for ( j=0; j<len; j++ )
                if ( mask[j] )
                    used[ image[j] ] = 1;

            compatible = TRUE;

            nThisFrame = nColours;

            memset( dstused, 0, 256 );

            for ( j=0; j<256; j++ )
            {
                if ( used[j] )
                {
                    int n = FindColour( colours, &nColours,
                                        f->pal->pColours[j] );

                    if ( n<0 )
                    {
                        compatible = FALSE;
                        break;
                    }
                    map[j] = (pixel) n;
                    dstused[n] = 1;
                }
            }

            if ( compatible )
            {
                debugf( "commonpal: frame %d compatible\n", i );

#if DEBUG
                debugf( "map" );
                for ( j=0; j<f->pal->nColours; j++ )
                {
                    if ( used[j] )
                        debugf( " %d", map[j] );
                    else
                        debugf( " -" );
                }
                debugf( "\n" );
#endif

                Palette_Destroy( &f->pal );     /* sets to NULL */

                /* Remap the frame to the new palette */
                for ( j=0; j<len; j++ )
                    image[j] = map[image[j]];
                Anim_Free( &f->pImageData );

                f->pImageData = Anim_Compress( image, len, &f->nImageSize );

                if ( !f->pImageData )
                {
                    result = FALSE;
                    break;
                }

                nUsedOnFrame = 0;

                for ( j=0; j<256; j++ )
                    if ( dstused[j] )
                        nUsedOnFrame++;

                if ( nUsedOnFrame >= mincolours && (i || f->pMaskData) )
                {
                    mincolours = nUsedOnFrame + 1;
                }
            }
            else
            {
                debugf( "commonpal: frame %d INcompatible!\n", i );

                nColours = nThisFrame;
            }
        }

        Workspace_Release();
    }

    Anim_Free( &image );
    Anim_Free( &mask );

    if ( result )
    {
        /* Allow an extra colour for transparency if possible */
        if ( mincolours > nColours && nColours < 256 )
        {
            /* And make it black, to avoid BUGS in the Microsoft Java VM */
            colours[nColours] = 0;
            nColours++;
        }

        debugf( "mincolours=%d nColours=%d\n", mincolours, nColours );

        for ( i=0; i < a->nFrames; i++ )
        {
            f = a->pFrames+i;

            if ( !f->pal )
            {
                f->pal = Palette_Create( colours, nColours );
                if ( !f->pal )
                {
                    result = FALSE;
                    break;
                }
            }
        }
    }
    return result;
}
コード例 #5
0
int main(int argc, char *argv[])
{
  uint8                 *buf;
  JVMMemoryStream       m;
  JVMClass              *jclass;
  JVMBundle             jbundle;
  JVMBundleClass        *jbclass;
  JVM                   jvm;
  JVMObject             *jobject;
  JVMLocal              locals[10];
  uint32                size;
  int                   result;
  JVMLocal              jvm_result;
  JVMLocal              _result;
  int                   x;
  uint8                 *entryClass;
  uint8                 *utf8;

  uint8                 o;
  uintptr               n;
  void                  *p;
  
  jvm.objects = 0;
  jvm.cmark = 0;
  jvm.mutex = 0;
  jbundle.first = 0;
  jvm.bundle = &jbundle;
  
  //x = jvm_GetMethodTypeArgumentCount("(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
  //jvm_printf("argcnt:%u\n", x);
  
  // if the internal malloc is enabled we simply just hand it
  // a rather large chunk of memory to use
  #ifdef INTERNALMALLOC
  p = malloc(1024 * 1024 * 8);
  jvm_m_give(p, 1024 * 1024 * 8);
  #endif

  buf = jvm_ReadWholeFile("./ert/sys/Core.class", &size);
  msWrap(&m, buf, size);
  jclass = jvm_LoadClass(&m);
  jclass->flags = JVM_CLASS_NATIVE;
  jclass->nhand = jvm_core_core_handler;
  jvm_free(buf);
  jvm_AddClassToBundle(&jbundle, jclass);
  
  entryClass = 0;
  for (x = 1; x < argc; ++x) {
    if (argv[x][0] == ':') {
      // holds classpath and class name for entry
      entryClass = &argv[x][1];
    } else {
      debugf("@@>loading %s\n", argv[x]);
      buf = jvm_ReadWholeFile(argv[x], &size);
      msWrap(&m, buf, size);
      jclass = jvm_LoadClass(&m);
      jvm_free(buf);
      debugf("@@>jclass: %lx\n", jclass);
      jvm_AddClassToBundle(&jbundle, jclass);
    }
  }

  // make static fields for all classes in bundle,
  // also this calls the special <clinit>:()V method
  debugf("here\n");
  jvm_MakeStaticFieldsOnBundle(&jvm, &jbundle);
  debugf("here\n");
  
  // catch common mistake and present user with something meaningful
  if (!entryClass) {
    debugf("No entry class specified on command line with :<entryclass>\n");
    return -1;
  }
  
  /// create initial object
  result = jvm_CreateObject(&jvm, &jbundle, entryClass, &jobject);
  jclass = jvm_FindClassInBundle(&jbundle, entryClass);

  if (!jobject) {
    debugf("could not create object?\n");
    jvm_exit(-1);
  }

  locals[0].data = (uint64)jobject;
  locals[0].flags = JVM_STACK_ISOBJECTREF;
  jvm_result.data = 0;
  jvm_result.flags = 0;
  result = jvm_ExecuteObjectMethod(&jvm, &jbundle, jclass, "main", "()J", &locals[0], 1, &jvm_result);
  if (result < 0) {
    if (!jvm_result.data) {
      debugf("error occured too soon; error-code:%i\n", result);
      exit(-1);
    }
    // the exception should be stored in jvm_result
    debugf("exception code:%i\n", result);
    debugf("jvm_result.data:%x jvm_result.flags:%x\n", jvm_result.data, jvm_result.flags);
    // walk the stack
    errorf("-------- UNCAUGHT EXCEPTION ---------\n");
    errorf("  %s\n", jvm_GetClassNameFromClass(((JVMObject*)jvm_result.data)->class));
    jvm_GetField((JVMObject*)jvm_result.data, "msg", &_result);
    debugf("here %x\n", _result.data);
    jvm_GetString((JVMObject*)_result.data, &utf8);
    errorf(" msg:%s\n", utf8);
    jvm_GetField((JVMObject*)jvm_result.data, "code", &_result);
    errorf(" code:%i\n", _result.data);
    result = jvm_GetField((JVMObject*)jvm_result.data, "first", &_result);
    while (_result.data != 0) {
      result = jvm_GetField((JVMObject*)_result.data, "methodName", &jvm_result);
      jvm_GetString((JVMObject*)jvm_result.data, &utf8);
      errorf("    method:%s", utf8);
      result = jvm_GetField((JVMObject*)_result.data, "className", &jvm_result);
      jvm_GetString((JVMObject*)jvm_result.data, &utf8);
      errorf(" class:%s", utf8);
      result = jvm_GetField((JVMObject*)_result.data, "methodType", &jvm_result);
      jvm_GetString((JVMObject*)jvm_result.data, &utf8);
      errorf(" type:%s", utf8);
      result = jvm_GetField((JVMObject*)_result.data, "opcodeIndex", &jvm_result);
      errorf(" opcode:%u\n", jvm_result.data);
      //result = jvm_GetField((JVMObject*)_result.data, "sourceLine", &jvm_result);
      //debugf("sourceLine:%u\n", jvm_result.data);
      // get next item, if any
      debugf("    -----\n");
      result = jvm_GetField((JVMObject*)_result.data, "next", &_result);
    }
    debugf("calling collect.. %x\n", jobject);
    jvm_Collect(&jvm);
    return -1;
  }

  jvm_printf("done! result.data:%i result.flags:%u\n", jvm_result.data, jvm_result.flags);

  jvm_Collect(&jvm);

  return 1;
}
コード例 #6
0
ファイル: cli-cccam.c プロジェクト: digrobot/multics-r63
void cc_srv_recvmsg(struct cs_server_data *srv)
{     
	unsigned char buf[CC_MAXMSGSIZE];
	struct cs_card_data *card;
	struct cardserver_data *cs;
	int i, len;
	ECM_DATA *ecm;

	if ( (srv->type==TYPE_CCCAM)&&(srv->handle>0) ) {
		len = cc_msg_chkrecv(srv->handle,&srv->recvblock);
		if (len==0) {
			debugf(" CCcam: server (%s:%d) read failed %d\n", srv->host->name, srv->port, len);
			cc_disconnect_srv(srv);
		}
		else if (len==-1) {
			if (!srv->chkrecvtime) srv->chkrecvtime = GetTickCount();
			else if ( (srv->chkrecvtime+500)<GetTickCount() ) {
				debugf(" CCcam: server (%s:%d) read failed %d\n", srv->host->name, srv->port, len);
				cc_disconnect_srv(srv);
			}
		}
		else if (len>0) {
			srv->chkrecvtime = 0;
			len = cc_msg_recv(srv->handle, &srv->recvblock, buf, 3);
			if (len==0) {
				debugf(" CCcam: server (%s:%d) read failed %d\n", srv->host->name, srv->port, len);
				cc_disconnect_srv(srv);
			}
			else if (len<0) {
				debugf(" CCcam: server (%s:%d) read failed %d(%d)\n", srv->host->name, srv->port, len, errno);
				cc_disconnect_srv(srv);
			}
			else if (len>0) {
				switch (buf[1]) {
				case CC_MSG_CLI_INFO:
					debugf(" CCcam: Client data ACK from Server (%s:%d)\n", srv->host->name,srv->port);
					break;

				case CC_MSG_ECM_REQUEST: // Get CW
					if (!srv->busy) {
						debugf(" [!] dcw error from server (%s:%d), unknown ecm request\n",srv->host->name,srv->port);
						break;
					}

					uint8 dcw[16];
					cc_crypt_cw( cfg.cccam.nodeid, srv->busycardid, &buf[4]);
					memcpy(dcw, &buf[4], 16);
					cc_decrypt(&srv->recvblock, buf+4, len-4); // additional crypto step				

					srv->busy = 0;
					srv->lastdcwtime = GetTickCount();

					pthread_mutex_lock(&prg.lockecm); //###

					ecm = getecmbyid(srv->busyecmid);
					if (!ecm) {
						debugf(" [!] error cw from server (%s:%d), ecm not found!!!\n",srv->host->name,srv->port);
						pthread_mutex_unlock(&prg.lockecm); //###
						srv->busy = 0;
						break;
					}
					// check for ECM???
					if (ecm->hash!=srv->busyecmhash) {
						debugf(" [!] error cw from server (%s:%d), ecm deleted!!!\n",srv->host->name,srv->port);
						pthread_mutex_unlock(&prg.lockecm); //###
						srv->busy = 0;
						break;
					}

					cs = getcsbyid(ecm->csid);
					int cardcheck = istherecard( srv, srv->busycard );
					// Check for DCW
					if (!acceptDCW(dcw)) {
						srv->ecmerrdcw ++;
						if (cs&&cardcheck) {
							cardsids_update( srv->busycard, ecm->provid, ecm->sid, -1);
							srv_cstatadd( srv, cs->id, 0 , 0);
						}
						ecm_setsrvflag(srv->busyecmid, srv->id, ECM_SRV_REPLY_FAIL);

						pthread_mutex_unlock(&prg.lockecm); //###
						break;
					}
//					else {

					srv->lastecmoktime = GetTickCount()-srv->lastecmtime;
					srv->ecmoktime += srv->lastecmoktime;
					srv->ecmok++;

					ecm_setsrvflagdcw(srv->busyecmid, srv->id, ECM_SRV_REPLY_GOOD,dcw);
					if (cs&&cardcheck) {
						cardsids_update( srv->busycard, ecm->provid, ecm->sid, 1); /// + Card nodeID
						srv_cstatadd( srv, cs->id, 1 , srv->lastecmoktime);
					}
					if (cardcheck) {
						srv->busycard->ecmoktime += GetTickCount()-srv->lastecmtime;
						srv->busycard->ecmok++;
					}

					if (ecm->dcwstatus!=STAT_DCW_SUCCESS) {
						static char msg[] = "Good dcw from CCcam server";
						ecm->statusmsg = msg;
						ecm_setdcw( cs, ecm, dcw, DCW_SOURCE_SERVER, srv->id );
						debugf(" <= cw from CCcam server (%s:%d) ch %04x:%06x:%04x (%dms)\n", srv->host->name,srv->port, ecm->caid,ecm->provid,ecm->sid, GetTickCount()-srv->lastecmtime);
					}

					pthread_mutex_unlock(&prg.lockecm); //###
					break;

				case CC_MSG_ECM_NOK1: // EAGAIN, Retry
/*
					if (!srv->busy) break;
					ecm = srv->busyecm;
					debugf(" <| decode1 failed from CCcam server (%s:%d) ch %04x:%06x:%04x (%dms)\n", srv->host->name,srv->port, ecm->caid,ecm->provid,ecm->sid, GetTickCount()-srv->lastecmtime);

					if ( (GetTickCount()-srv->lastecmtime)<CC_ECMRETRY_TIMEOUT ) {
						if (srv->retry<CC_ECMRETRY_MAX) {
							srv->busy = 0;
							if (cc_sendecm_srv(srv, ecm)) {
								srv->lastecmtime = GetTickCount();
								srv->busy = 1;
								srv->retry++;
								break;
							}
						}
					}
					if (srv->retry>=CC_ECMRETRY_MAX) {
						ecm_setsrvflag(ecm, srv->id, ECM_SRV_EXCLUDE); 
					}
					srv->busy = 0;
					break;
*/
				case CC_MSG_ECM_NOK2: // ecm decode failed
					if (!srv->busy) {
						debugf(" [!] dcw error from server (%s:%d), unknown ecm request\n",srv->host->name,srv->port);
						break;
					}

					pthread_mutex_lock(&prg.lockecm); //###

					ecm = getecmbyid(srv->busyecmid);
					if (!ecm) {
						debugf(" [!] dcw error from server (%s:%d), ecm not found!!!\n",srv->host->name,srv->port);
						pthread_mutex_unlock(&prg.lockecm); //###
						srv->busy = 0;
						break;
					}
					// check for ECM???
					if (ecm->hash!=srv->busyecmhash) {
						debugf(" [!] dcw error from server (%s:%d), ecm deleted!!!\n",srv->host->name,srv->port);
						pthread_mutex_unlock(&prg.lockecm); //###
						srv->busy = 0;
						break;
					}

					debugf(" <| decode failed from CCcam server (%s:%d) ch %04x:%06x:%04x (%dms)\n", srv->host->name,srv->port, ecm->caid,ecm->provid,ecm->sid, GetTickCount()-srv->lastecmtime);
					cs = getcsbyid(ecm->csid);

					if (ecm->dcwstatus!=STAT_DCW_SUCCESS) {
						if ( cs && (GetTickCount()-ecm->recvtime)<cs->cstimeout ) {
							if (srv->retry<cs->ccretry) {
								srv->busy = 0;
								if (cc_sendecm_srv(srv, ecm)) {
									srv->lastecmtime = GetTickCount();
									srv->busy = 1;
									srv->retry++;
									debugf(" (RE%d) -> ecm to CCcam server (%s:%d) ch %04x:%06x:%04x\n",srv->retry,srv->host->name,srv->port,ecm->caid,ecm->provid,ecm->sid);
									pthread_mutex_unlock(&prg.lockecm); //###
									break;
								}
							}
						}
					}

					if (cs) {
						if ( istherecard( srv, srv->busycard ) ) cardsids_update( srv->busycard, ecm->provid, ecm->sid, -1);
						srv_cstatadd( srv, cs->id, 0 , 0);
					}
					ecm_setsrvflag(srv->busyecmid, srv->id, ECM_SRV_REPLY_FAIL);

					srv->busy = 0;
					pthread_mutex_unlock(&prg.lockecm); //###
					break;


				case CC_MSG_BAD_ECM: // Add Card
					cc_msg_send( srv->handle, &srv->sendblock, CC_MSG_BAD_ECM, 0, NULL);
					//debugf(" CCcam: cmd 0x05 from Server (%s:%d)\n",srv->host->name,srv->port);
					//currentecm.state = ECM_STATUS_FAILED;
					break;

				case CC_MSG_KEEPALIVE:
					srv->keepalivesent = 0;
					//debugf(" CCcam: Keepalive ACK from Server (%s:%d)\n",srv->host->name,srv->port);
					break;

				case CC_MSG_CARD_DEL: // Delete Card
					card = srv->card;
					uint32 k = buf[4]<<24 | buf[5]<<16 | buf[6]<<8 | buf[7];
					struct cs_card_data *prevcard = NULL;
					while (card) {
						if (card->shareid==k) {
							debugf(" CCcam: server (%s:%d), remove share-id %d\n",srv->host->name,srv->port,k);
							if (prevcard) prevcard->next = card->next; else srv->card = card->next;
							//Free SIDs
							while (card->sids) {
								struct sid_data *sid = card->sids;
								card->sids = card->sids->next;
								free(sid);
							}
							free(card);
							// check for current ecm
							if (srv->busy && (srv->busycardid==k) ) ecm_setsrvflag(srv->busyecmid, srv->id, ECM_SRV_EXCLUDE);
							break;
						}
						prevcard = card;
						card = card->next;
					}
			  		break;

				case CC_MSG_CARD_ADD:
					// remove own cards -> same nodeid "cfg.cccam.nodeid"
					if ( (buf[14]<srv->uphops) && (buf[24]<=16) && memcmp(buf+26+buf[24]*7,cfg.cccam.nodeid,8) ) { // check Only the first 4 bytes
						// nodeid index = 26 + 7 * buf[24]
						struct cs_card_data *card = malloc( sizeof(struct cs_card_data) );
						memset(card, 0, sizeof(struct cs_card_data) );
						card->shareid = buf[4]<<24 | buf[5]<<16 | buf[6]<<8 | buf[7];
						card->uphops = buf[14]+1;
						memcpy( card->nodeid, buf+26+buf[24]*7, 8);
						card->caid = (buf[12]<<8)+(buf[13]);
						card->nbprov = buf[24];
						card->sids = NULL;

						i = 26+buf[24]*7;
						debugf(" CCcam: new card (%s:%d) %02x%02x%02x%02x%02x%02x%02x%02x_%x uphops %d caid %04x providers %d\n",srv->host->name,srv->port, buf[i],buf[i+1],buf[i+2],buf[i+3],buf[i+4],buf[i+5],buf[i+6],buf[i+7],card->shareid ,card->uphops, card->caid, card->nbprov);

						if (card->nbprov>CARD_MAXPROV) card->nbprov = CARD_MAXPROV;
						for (i=0;i<card->nbprov; i++) {
							card->prov[i] = (buf[25+i*7]<<16) | (buf[26+i*7]<<8) | (buf[27+i*7]);
							//debugf("   Provider %d = %06x\n",i, card->prov[i]);
						}
						card->next = srv->card;
						srv->card = card;
					}
					break;

				case CC_MSG_SRV_INFO:
					memcpy(srv->nodeid, buf+4, 8);
					memcpy(srv->version, buf+12, 31);
					for (i=12; i<53; i++) {
						if (!buf[i]) break;
						if ( (buf[i]<32)||(buf[i]>'z') ) {
							memset(srv->version, 0, 31);
							break;
						}
					}
					memcpy(srv->build, buf+44, 31);
					debugf(" CCcam: server (%s:%d), info: version %s build %s\n",srv->host->name,srv->port,buf+12, buf+44);
					break;

				//default: debugdump(buf,len," CCcam: unknown packet from server (%s:%d): ",srv->host->name,srv->port);
				} // switch
			}
			srv->keepalivetime = GetTickCount();
		}
	}
}
コード例 #7
0
ファイル: commonpal.c プロジェクト: pdh11/intergif
BOOL Anim_AddToHistogram( anim a )
{
    pixel *buffer;
    pixel *mask;
    unsigned int size = a->nWidth * a->nHeight;
    unsigned int i, j;

    debugf( "in Anim_AddToHistogram(%d)\n", a->nFrames );

    buffer = Anim_Allocate( size );
    mask   = Anim_Allocate( size );

    if ( !buffer
         || !mask )
    {
        Anim_NoMemory( "addhist" );
        Anim_Free( &buffer );
        Anim_Free( &mask );
        return FALSE;
    }

    Workspace_Claim(0);

    for ( i=0; i<a->nFrames; i++ )
    {
        frame f = a->pFrames + i;
        unsigned int *pal = f->pal->pColours;

        memset( mask, 1, size );

        if ( !Anim_Decompress( f->pImageData, f->nImageSize, size, buffer )
             || ( f->pMaskData
                  && !Anim_Decompress( f->pMaskData, f->nMaskSize, size, mask )
                )
            )
        {
            Anim_Free( &buffer );
            Anim_Free( &mask );
            Workspace_Release();
            return FALSE;
        }

        for ( j=0; j<size; j++ )
            if ( mask[j] )
                if ( !Histogram_Pixel( pal[ buffer[j] ] ) )
                {
                    Anim_Free( &buffer );
                    Anim_Free( &mask );
                    Workspace_Release();
                    return FALSE;
                }
    }

    Workspace_Release();

    Anim_Free( &buffer );
    Anim_Free( &mask );

    debugf( "Anim_AddToHistogram exits\n" );

    return TRUE;
}
コード例 #8
0
ファイル: files.c プロジェクト: niubl/trinity
static int ignore_files(const char *path)
{
	unsigned int i, j;
	unsigned int pathlen, offset = 0;

	/* These are exact matches. */
	const char *ignored_paths[] = {
		".", "..",

		/* dangerous/noisy/annoying stuff in /proc */
		"/proc/sysrq-trigger", "/proc/kmem", "/proc/kcore",

		/* dangerous/noisy/annoying stuff in /dev */
		"/dev/log", "/dev/mem", "/dev/kmsg", "/dev/kmem",
		NULL
	};

	/* Partial matches. */	//FIXME: This whole function should just use globs to pattern match.
	const char *ignored_patterns[] = {

		/* dangerous/noisy/annoying per-process stuff. */
		"coredump_filter", "make-it-fail", "oom_adj", "oom_score_adj",
		NULL
	};

	pathlen = strlen(path);

	/* First do the exact matches */
	for (i = 0; ignored_paths[i]; i++) {
		if (strlen(ignored_paths[i]) != pathlen) {
			continue;
		}

		if (!strcmp(path, ignored_paths[i])) {
			debugf("Skipping %s\n", path);
			return 1;
		}
	}

	/* Now make sure none of the patterns match the end of the pathname */
	for (j = 0; j < pathlen; j++) {
		if (path[j] == '/')
			offset = j;
	}
	offset++;

	if (offset == 1)
		return 0;

	for (i = 0; ignored_patterns[i]; i++) {
		if (!strcmp(path + offset, ignored_patterns[i])) {
			debugf("Skipping pattern %s\n", path);
			return 1;
		}
	}

	/* special case to match tty* until I do globbing */
	if (!strncmp(path + offset, "tty", 3)) {
		debugf("Skipping %s\n", path);
		return 1;
	}

	/* seriously though, I should add globbing */
	if (!strncmp(path + offset, "sd", 2)) {
		debugf("Skipping %s\n", path);
		return 1;
	}

	return 0;
}
コード例 #9
0
VOID CServiceModule::RunAsExecutable()
{
	//Imago: we parents needs to keep track of our children
#if defined(SRV_PARENT)
	InitPIDs();
#endif

	HRESULT hr;
#if defined(SRV_PARENT)
	if (g.bRestarting == false) {
		ZVersionInfo vi;
		printf("%s\n%s\n\n", (LPCSTR)vi.GetFileDescription(), (LPCSTR)vi.GetLegalCopyright());
	}
#else
#if !defined(SRV_CHILD)
	ZVersionInfo vi;
	printf("%s\n%s\n\n",
		(LPCSTR)vi.GetFileDescription(), (LPCSTR)vi.GetLegalCopyright());
#endif
#endif

	if (IsWinNT())
		printf("Running as an executable.\n");

	printf("Initializing...\n");

	hr = FedSrv_Init();

#if !defined(_CONSOLE)
	if (SUCCEEDED(hr))
	{
		RunAsWindow();
		return;
	}
#endif


	if (SUCCEEDED(hr))
	{
		HANDLE hConsole;

		printf("\rType 'Q' to Quit.\n");
		printf("\rType 'P' to Pause.\n");
		printf("\rType 'C' to Continue.\n");

		hConsole = GetStdHandle(STD_INPUT_HANDLE);
		SetConsoleMode(hConsole, 0);

		SetConsoleCtrlHandler(HandlerRoutine, true);

		assert(g.hKillReceiveEvent);
		//Imago - parents restart everything after tricking the lobby into sending the client to our child
#if defined(SRV_PARENT)
		g.bRestarting = false;
#endif

		HANDLE hEventArray[] = { g.hKillReceiveEvent, hConsole };

		DWORD dwAwaker;

		//
		// Wait until Receive Thread dies; if Q is pressed, kill Receive Thread
		//
		do
		{
			dwAwaker = MsgWaitForMultipleObjects(2, hEventArray, FALSE, INFINITE, 0);

			if (dwAwaker == WAIT_OBJECT_0 + 1)
			{
				INPUT_RECORD Key;
				DWORD dwRead;

				ReadConsoleInput(hConsole, &Key, 1, &dwRead);

				if (Key.EventType == KEY_EVENT &&
					Key.Event.KeyEvent.wVirtualKeyCode == 'Q')
				{
					debugf("Q pressed\n");
					SetEvent(g.hKillReceiveEvent);
				}
				if (Key.EventType == KEY_EVENT &&
					Key.Event.KeyEvent.wVirtualKeyCode == 'P')
				{
					debugf("P pressed\n");
					FedSrv_Pause();
				}
				if (Key.EventType == KEY_EVENT &&
					Key.Event.KeyEvent.wVirtualKeyCode == 'C')
				{
					debugf("C pressed\n");
					FedSrv_Continue();
				}
			}

		} while (dwAwaker != WAIT_OBJECT_0);

		FedSrv_Terminate();

		// here is a good spot to restart -Imago
#if defined(SRV_PARENT)
		if (g.bRestarting)
			RunAsExecutable();
#endif

	}
	else
	{
		printf("\rInitialization failed. (%x)\n", hr);
	}
}
コード例 #10
0
ファイル: asus-tcci.c プロジェクト: cav94mat/asus-tcci
/** @main Application entry-point. */
int main(int argc, char* argv[])
{
    int c;
    strcpy(initcmd, DEF_CMD_INIT);
    while (true)
    {
        static struct option long_options[] =
        {
            {"adapter", required_argument, 0, 'a'},
            {"remote-adapter", required_argument, 0, 'b'},
            {"close", no_argument, 0, 'c'},
            {"blink-on-receive", no_argument, 0, 'k'},
            {"log-packets", no_argument, 0, 'p'},
            {"verbose", no_argument, 0, 'v'},
            {"version", no_argument, 0, 'V'},
            {"help", no_argument, 0, 'h'},
            {0, 0, 0, 0}
        };
        /* getopt_long stores the option index here. */
        int option_index = 0;
        c = getopt_long (argc, argv, "a:b:ckpvV?", long_options, &option_index);
        
        /* Detect the end of the options. */
        if (c == -1)
            break;
        switch (c) {
            case 'a':
                tc_eth_adapter = optarg;
                break;
            case 'b':
                tc_eth_remoteAdapter = optarg;
                break;
            case 'c':
                exitReason = 0;
                break;
            case 'p':
                dbg_logPackets = true;
                break;
            case 'v':
                dbg_debugOut = true;
                break;
            case 'k':
                dbg_blinkOnReceive = true;
                break;
            case 'V':
                printf("Asus-TCCI (TrendChip Command Interpreter), version %s, build %s\n", VERSION, VERSION_BUILD);
                printf(" by %s. Sources and updates: %s\n", AUTHOR, URL);
                return EC_NORMAL;
            case 'h':
                /* getopt_long already printed an error message. */
                printf("usage: %s -V|--version\n", argv[0]); 
                printf("or: %s [-a|--adapter=\"%s\"] [-b|--remote-adapter=\"%s\"] [-c|--close] [-p|--log-packets] [-v|--verbose] [-k|--blink-on-receive] [<%s>]\n", argv[0], tc_eth_adapter, tc_eth_remoteAdapter, initcmd);
                
                return EC_NORMAL;
            default:
                return 9;
        }
    }
    
    /* Print any remaining command line arguments (not options). */
    if (optind < argc) {
        initcmd[0] = '\0'; // Clear string
        while (optind < argc)
            strncat(initcmd, argv[optind++], sizeof(initcmd));
    }
    debugf("-- Starting...\n");
    // Initialize in-socket
    tc_eth_sockIn = socket(AF_INET, SOCK_DGRAM, 0);
    if (tc_eth_sockIn < 0)
    {
        errorf("-- E: Input socket init failed!\n");
        return EC_APIFAIL;
    }
	/*debugf("-- dbg_debugOut = %d, dbg_logPackets = %d, tc_eth_adapter = \"%s\", initcmd = \"%s\"\n",
	    dbg_debugOut, dbg_logPackets, tc_eth_adapter, initcmd);*/
	// Initialize adapter
	eth_adapterId = if_nametoindex(tc_eth_adapter);
    initAdapter(tc_eth_adapter);
    // Initialize out-socket
    tc_eth_sockOut = socket(AF_PACKET,SOCK_RAW, htons(ETH_P_ALL));
    if (tc_eth_sockOut < 0)
    {
        errorf("-- E: Output socket init failed!\n");
        return EC_APIFAIL;
    }
    // Acquired MACs
    debugf("Remote (TrendChip) MAC: ");
    printmac(debugf, tc_eth_remoteMac);
    debugf("\nLocal (terminal) MAC: ");
    printmac(debugf, tc_eth_localMac);
    // Initial command execution
    debugf("\n-- Phase 2 - Perform init-command (%s)\n", initcmd);
    if (!tc_exec(initcmd))
        return EC_NETFAIL;
    // Interactive shell
    char inbuff[TC_CMD_MAX_LEN];
    fd_set rfds;
    struct timeval tv;
    int retval;
    while(exitReason < 0) {
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
        tv.tv_sec = 0;
        tv.tv_usec = 100000; //100ms
        retval = select(1, &rfds, NULL, NULL, &tv);
        if (retval == -1){
            perror("-- select(stdin)");
            return EC_APIFAIL;
        }
        else if (retval){   
            debugf("-- Gathering input... "); 
            char* cmd = fgets(inbuff, TC_CMD_MAX_LEN, stdin);
            if (cmd[strlen(cmd)-1] == '\n')
                cmd[strlen(cmd)-1] = '\0'; // Trim the trailing '\n' char.
            debugf("Got '%s'\n", cmd); 
            if (cmd[0] == '\0')
                {} // Do nothing on blank lines.
            else if (strcmp(cmd, "!q") == 0 || strcmp(cmd, "!quit") == 0)
                exitReason = EC_NORMAL;
            else if (strcmp(cmd, "!v") == 0 || strcmp(cmd, "!verbose") == 0)
                errorf("-- Verbose output is now %s.\n", (dbg_debugOut = !dbg_debugOut) ? "ON" : "OFF");
            else if (strcmp(cmd, "!p") == 0 || strcmp(cmd, "!logpackets") == 0)
                errorf("-- Packet logging is now %s.\n", (dbg_logPackets = !dbg_logPackets) ? "ON" : "OFF");
            else if (strcmp(cmd, "!k") == 0 || strcmp(cmd, "!blink") == 0)
                errorf("-- Blink-on-receive is now %s.\n", (dbg_blinkOnReceive = !dbg_blinkOnReceive) ? "ON" : "OFF");
            else if (strcmp(cmd, "!h") == 0 || strcmp(cmd, "!help") == 0)
                errorf("-- Valid client commands: \n--  ![blin]k, !h[elp], ![log]p[ackets], !q[uit], !v[erbose].\n"); 
            else if (cmd[0] == '!')
                errorf("-- Unrecognized client command. Please try \"!help\" if you aren't sure.\n"); 
            else if (!tc_exec(cmd))
                errorf("-- W: Command request fail!\n");
                //exitReason = EC_NETFAIL; // I/O error?
        }
        if (!tc_listen())
            exitReason = EC_NETFAIL;
    }
    if (tc_eth_sockIn) 
        close(tc_eth_sockIn);
    else
        debugf("-- W: Input socket already closed!");
    if (tc_eth_sockOut) 
        close(tc_eth_sockOut);
    else
        debugf("-- W: Output socket already closed!");
    debugf("-- Connection closed, reason = %d (-1).\n", exitReason);
    return exitReason-1;
}
コード例 #11
0
ファイル: acl.cpp プロジェクト: Barrett17/haiku
status_t
AclAssembly(net_buffer* nbuf, hci_id hid)
{
	status_t	error = B_OK;

	// Check ACL data packet. Driver should ensure report complete ACL packets
	if (nbuf->size < sizeof(struct hci_acl_header)) {
		debugf("Invalid ACL data packet, small length=%ld\n", nbuf->size);
		gBufferModule->free(nbuf);
		return (EMSGSIZE);
	}

	// Strip ACL data packet header
	NetBufferHeaderReader<struct hci_acl_header> aclHeader(nbuf);
	status_t status = aclHeader.Status();
	if (status < B_OK) {
		gBufferModule->free(nbuf);
		return ENOBUFS;
	}


	// Get ACL connection handle, PB flag and payload length
	aclHeader->handle = le16toh(aclHeader->handle);

	uint16 con_handle = get_acl_handle(aclHeader->handle);
	uint16 pb = get_acl_pb_flag(aclHeader->handle);
	uint16 length = le16toh(aclHeader->alen);

	aclHeader.Remove();

	debugf("ACL data packet, handle=%#x, PB=%#x, length=%d\n",
		con_handle, pb, length);

	// a) Ensure there is HCI connection
	// b) Get connection descriptor
	// c) veryfy the status of the connection

	HciConnection* conn = btCoreData->ConnectionByHandle(con_handle, hid);
	if (conn == NULL) {
		debugf("Uexpected handle=%#x does not exist!\n", con_handle);
		conn = btCoreData->AddConnection(con_handle, BT_ACL, BDADDR_NULL, hid);
	}

	// Verify connection state
	if (conn->status!= HCI_CONN_OPEN) {
		flowf("unexpected ACL data packet. Connection not open\n");
		gBufferModule->free(nbuf);
		return EHOSTDOWN;
	}


	// Process packet
	if (pb == HCI_ACL_PACKET_START) {
		if (conn->currentRxPacket != NULL) {
			debugf("Dropping incomplete L2CAP packet, got %ld want %d \n",
				conn->currentRxPacket->size, length );
			gBufferModule->free(conn->currentRxPacket);
			conn->currentRxPacket = NULL;
			conn->currentRxExpectedLength = 0;
		}

		// Get L2CAP header, ACL header was dimissed
		if (nbuf->size < sizeof(l2cap_hdr_t)) {
			debugf("Invalid L2CAP start fragment, small, length=%ld\n",
				nbuf->size);
			gBufferModule->free(nbuf);
			return (EMSGSIZE);
		}


		NetBufferHeaderReader<l2cap_hdr_t> l2capHeader(nbuf);
		status_t status = l2capHeader.Status();
		if (status < B_OK) {
			gBufferModule->free(nbuf);
			return ENOBUFS;
		}

		l2capHeader->length = le16toh(l2capHeader->length);
		l2capHeader->dcid = le16toh(l2capHeader->dcid);

		debugf("New L2CAP, handle=%#x length=%d\n", con_handle,
			le16toh(l2capHeader->length));

		// Start new L2CAP packet
		conn->currentRxPacket = nbuf;
		conn->currentRxExpectedLength = l2capHeader->length + sizeof(l2cap_hdr_t);


	} else if (pb == HCI_ACL_PACKET_FRAGMENT) {
		if (conn->currentRxPacket == NULL) {
			gBufferModule->free(nbuf);
			return (EINVAL);
		}

		// Add fragment to the L2CAP packet
		gBufferModule->merge(conn->currentRxPacket, nbuf, true);

	} else {
		debugf("invalid ACL data packet. Invalid PB flag=%#x\n", pb);
		gBufferModule->free(nbuf);
		return (EINVAL);
	}

	// substract the length of content of the ACL packet
	conn->currentRxExpectedLength -= length;

	if (conn->currentRxExpectedLength < 0) {

		debugf("Mismatch. Got %ld, expected %ld\n",
			conn->currentRxPacket->size, conn->currentRxExpectedLength);

		gBufferModule->free(conn->currentRxPacket);
		conn->currentRxPacket = NULL;
		conn->currentRxExpectedLength = 0;

	} else if (conn->currentRxExpectedLength == 0) {
		// OK, we have got complete L2CAP packet, so process it
		debugf("L2cap packet ready %ld bytes\n", conn->currentRxPacket->size);
		error = PostToUpper(conn, conn->currentRxPacket);
		// clean
		conn->currentRxPacket = NULL;
		conn->currentRxExpectedLength = 0;
	} else {
		debugf("Expected %ld current adds %d\n",
			conn->currentRxExpectedLength, length);
	}

	return error;
}
コード例 #12
0
ファイル: main.c プロジェクト: wphungsuk/trinity
static void fork_children(void)
{
	int pidslot;
	static char childname[17];

	/* Generate children*/

	while (shm->running_childs < shm->max_children) {
		int pid = 0;

		/* Find a space for it in the pid map */
		pidslot = find_pid_slot(EMPTY_PIDSLOT);
		if (pidslot == PIDSLOT_NOT_FOUND) {
			printf("[%d] ## Pid map was full!\n", getpid());
			dump_pid_slots();
			exit(EXIT_FAILURE);
		}

		(void)alarm(0);
		fflush(stdout);
		pid = fork();
		if (pid != 0)
			shm->pids[pidslot] = pid;
		else {
			/* Child process. */
			int ret = 0;

			mask_signals_child();

			memset(childname, 0, sizeof(childname));
			sprintf(childname, "trinity-child%d", pidslot);
			prctl(PR_SET_NAME, (unsigned long) &childname);

			oom_score_adj(500);

			/* Wait for parent to set our pidslot */
			while (shm->pids[pidslot] != getpid()) {
				/* Make sure parent is actually alive to wait for us. */
				ret = pid_alive(shm->parentpid);
				if (ret != 0) {
					shm->exit_reason = EXIT_SHM_CORRUPTION;
					printf("[%d] " BUGTXT "parent (%d) went away!\n", getpid(), shm->parentpid);
					sleep(20000);
				}
			}

			init_child(pidslot);

			ret = child_process(pidslot);

			output(1, "child %d exiting\n", getpid());

			_exit(ret);
		}
		shm->running_childs++;
		debugf("[%d] Created child %d in pidslot %d [total:%d/%d]\n",
			getpid(), shm->pids[pidslot], pidslot,
			shm->running_childs, shm->max_children);

		if (shm->exit_reason != STILL_RUNNING)
			return;

	}
	debugf("[%d] created enough children\n", getpid());
}
コード例 #13
0
ファイル: main.c プロジェクト: wphungsuk/trinity
static void handle_child(pid_t childpid, int childstatus)
{
	unsigned int i;
	int slot;

	switch (childpid) {
	case 0:
		//debugf("[%d] Nothing changed. children:%d\n", getpid(), shm->running_childs);
		break;

	case -1:
		if (shm->exit_reason != STILL_RUNNING)
			return;

		if (errno == ECHILD) {
			debugf("[%d] All children exited!\n", getpid());
			for_each_pidslot(i) {
				if (shm->pids[i] != EMPTY_PIDSLOT) {
					if (pid_alive(shm->pids[i]) == -1) {
						debugf("[%d] Removing %d from pidmap\n", getpid(), shm->pids[i]);
						shm->pids[i] = EMPTY_PIDSLOT;
						shm->running_childs--;
					} else {
						debugf("[%d] %d looks still alive! ignoring.\n", getpid(), shm->pids[i]);
					}
				}
			}
			break;
		}
		output(0, "error! (%s)\n", strerror(errno));
		break;

	default:
		debugf("[%d] Something happened to pid %d\n", getpid(), childpid);

		if (WIFEXITED(childstatus)) {

			slot = find_pid_slot(childpid);
			if (slot == PIDSLOT_NOT_FOUND) {
				printf("[%d] ## Couldn't find pid slot for %d\n", getpid(), childpid);
				shm->exit_reason = EXIT_LOST_PID_SLOT;
				dump_pid_slots();
			} else {
				debugf("[%d] Child %d exited after %ld syscalls.\n", getpid(), childpid, shm->child_syscall_count[slot]);
				reap_child(childpid);
			}
			break;

		} else if (WIFSIGNALED(childstatus)) {

			switch (WTERMSIG(childstatus)) {
			case SIGALRM:
				debugf("[%d] got a alarm signal from pid %d\n", getpid(), childpid);
				break;
			case SIGFPE:
			case SIGSEGV:
			case SIGKILL:
			case SIGPIPE:
			case SIGABRT:
				debugf("[%d] got a signal from pid %d (%s)\n", getpid(), childpid, strsignal(WTERMSIG(childstatus)));
				reap_child(childpid);
				break;
			default:
				debugf("[%d] ** Child got an unhandled signal (%d)\n", getpid(), WTERMSIG(childstatus));
				break;
			}
			break;

		} else if (WIFSTOPPED(childstatus)) {

			switch (WSTOPSIG(childstatus)) {
			case SIGALRM:
				debugf("[%d] got an alarm signal from pid %d\n", getpid(), childpid);
				break;
			case SIGSTOP:
				debugf("[%d] Sending PTRACE_DETACH (and then KILL)\n", getpid());
				ptrace(PTRACE_DETACH, childpid, NULL, NULL);
				kill(childpid, SIGKILL);
				reap_child(childpid);
				break;
			case SIGFPE:
			case SIGSEGV:
			case SIGKILL:
			case SIGPIPE:
			case SIGABRT:
				debugf("[%d] Child %d was stopped by %s\n", getpid(), childpid, strsignal(WTERMSIG(childstatus)));
				reap_child(childpid);
				break;
			default:
				debugf("[%d] Child %d was stopped by unhandled signal (%s).\n", getpid(), childpid, strsignal(WSTOPSIG(childstatus)));
				break;
			}
			break;

		} else if (WIFCONTINUED(childstatus)) {
			break;
		} else {
			output(0, "erk, wtf\n");
		}
	}
コード例 #14
0
ファイル: cli-cccam.c プロジェクト: digrobot/multics-r63
///////////////////////////////////////////////////////////////////////////////
// Connect to a server.
// Return
// 0: no error
int cc_connect_srv(struct cs_server_data *srv, int fd)
{
	int n;
	uint8 data[20];
	uint8 hash[SHA_DIGEST_LENGTH];
	uint8 buf[CC_MAXMSGSIZE];
	char pwd[64];
	//
	if (fd < 0) return -1;
	// INIT
	srv->progname = NULL;
	memset( srv->version, 0, sizeof(srv->version) );
	// get init seed(random) from server
	if((n = recv_nonb(fd, data, 16,3000)) != 16) {
		static char msg[]= "Server does not return init sequence";
		srv->statmsg = msg;
		//debugf("Client: Server (%s:%d) does not return 16 bytes\n", srv->host->name,srv->port);
		close(fd);
		return -2;
	}

	if (flag_debugnet) {
		debugf(" CCcam: receive server init seed (%d)\n",n);
		debughex(data,n);
	}

	// Check Multics
	int ismultics = 0;
	uchar a = (data[0]^'M') + data[1] + data[2];
	uchar b = data[4] + (data[5]^'C') + data[6];
	uchar c = data[8] + data[9] + (data[10]^'S');
	if ( (a==data[3])&&(b==data[7])&&(c==data[11]) ) ismultics = 1;

	cc_crypt_xor(data);  // XOR init bytes with 'CCcam'

	SHA_CTX ctx;
	SHA1_Init(&ctx);
	SHA1_Update(&ctx, data, 16);
	SHA1_Final(hash, &ctx);

	//debugdump(hash, sizeof(hash), "CCcam: sha1 hash:");

	//initialisate crypto states
	cc_crypt_init(&srv->recvblock, hash, 20);
	cc_decrypt(&srv->recvblock, data, 16); 
	cc_crypt_init(&srv->sendblock, data, 16);
	cc_decrypt(&srv->sendblock, hash, 20);

	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 20,hash);   // send crypted hash to server
	memset(buf, 0, sizeof(buf));
	memcpy(buf, srv->user, 20);
	//debugf(" CCcam: username '%s'\n",srv->username);
	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 20, buf);    // send usr '0' padded -> 20 bytes

	memset(buf, 0, sizeof(buf));
	memset(pwd, 0, sizeof(pwd));

	//debugf("CCcam: 'CCcam' xor\n");
	memcpy(buf, "CCcam", 5);
	strncpy(pwd, srv->pass, 63);
	cc_encrypt(&srv->sendblock, (uint8 *)pwd, strlen(pwd));
	cc_msg_send( fd, &srv->sendblock, CC_MSG_NO_HEADER, 6, buf); // send 'CCcam' xor w/ pwd
	if ((n = recv_nonb(fd, data, 20,3000)) != 20) {
		static char msg[]= "Password ACK not received";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), pwd ack not received (n = %d)\n",srv->host->name,srv->port, n);
		return -2;
	}
	cc_decrypt(&srv->recvblock, data, 20);
	//hexdump(data, 20, "CCcam: pwd ack received:");

	if (memcmp(data, buf, 5)) {  // check server response
		static char msg[]= "Invalid user/pass";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), usr/pwd invalid\n",srv->host->name,srv->port);
		return -2;
	}// else debugf(" CCcam: login succeeded to Server (%s:%d)\n",srv->host->name,srv->port);

	srv->handle = fd;
	if (!cc_sendinfo_srv(srv,ismultics)) {
		srv->handle = -1;
		static char msg[]= "Error sending client data";
		srv->statmsg = msg;
		debugf(" CCcam: login failed to Server (%s:%d), could not send client data\n",srv->host->name,srv->port);
		return -3;
	}

	static char msg[]= "Connected";
	srv->statmsg = msg;

	srv->keepalivesent = 0;
	srv->keepalivetime = GetTickCount();
	srv->connected = GetTickCount();

	srv->busy = 0;
	srv->lastecmoktime = 0;
	srv->lastecmtime = 0;
	srv->lastdcwtime = 0;
	srv->chkrecvtime = 0;

	memset(srv->version,0,32);
	pipe_wakeup( srvsocks[1] );
	return 0;
}
コード例 #15
0
static int
fdt_localbus_reg_decode(phandle_t node, struct localbus_softc *sc,
    struct localbus_devinfo *di)
{
	u_long start, end, count;
	pcell_t *reg, *regptr;
	pcell_t addr_cells, size_cells;
	int tuple_size, tuples;
	int i, rv, bank;

	if (fdt_addrsize_cells(OF_parent(node), &addr_cells, &size_cells) != 0)
		return (ENXIO);

	tuple_size = sizeof(pcell_t) * (addr_cells + size_cells);
	tuples = OF_getprop_alloc_multi(node, "reg", tuple_size, (void **)&reg);
	debugf("addr_cells = %d, size_cells = %d\n", addr_cells, size_cells);
	debugf("tuples = %d, tuple size = %d\n", tuples, tuple_size);
	if (tuples <= 0)
		/* No 'reg' property in this node. */
		return (0);

	regptr = reg;
	for (i = 0; i < tuples; i++) {

		bank = fdt_data_get((void *)regptr, 1);

		if (bank >= MV_LOCALBUS_MAX_BANKS) {
			device_printf(sc->sc_dev, "bank number [%d] out of "
			    "range\n", bank);
			continue;
		}

		/*
		 * If device doesn't have virtual to physical mapping don't add
		 * resources
		 */
		if (!(sc->sc_banks[bank].mapped)) {
			device_printf(sc->sc_dev, "device [%d]: missing memory "
			    "mapping\n", bank);
			continue;
		}

		di->di_bank = bank;
		regptr += 1;

		/* Get address/size. */
		rv = fdt_data_to_res(regptr, addr_cells - 1, size_cells, &start,
		    &count);
		if (rv != 0) {
			resource_list_free(&di->di_res);
			goto out;
		}

		/* Check if enough amount of memory is mapped */
		if (sc->sc_banks[bank].size < count) {
			device_printf(sc->sc_dev, "device [%d]: not enough "
			    "memory reserved\n", bank);
			continue;
		}

		regptr += addr_cells - 1 + size_cells;

		/* Calculate address range relative to VA base. */
		start = sc->sc_banks[bank].va + start;
		end = start + count - 1;

		debugf("reg addr bank = %d, start = %lx, end = %lx, "
		    "count = %lx\n", bank, start, end, count);

		/* Use bank (CS) cell as rid. */
		resource_list_add(&di->di_res, SYS_RES_MEMORY, di->di_bank,
		    start, end, count);
	}
	rv = 0;
out:
	OF_prop_free(reg);
	return (rv);
}
コード例 #16
0
ファイル: dev_tree.c プロジェクト: dhs-shine/sprd_project
/* Top level function that updates the device tree. */
int update_device_tree(void *fdt, const char *cmdline,
					   void *ramdisk, uint32_t ramdisk_size)
{
	int ret = 0;
	uint32_t offset;

	/* Check the device tree header */
	ret = fdt_check_header(fdt);
	if (ret)
	{
		debugf( "Invalid device tree header \n");
		return ret;
	}

	/* Add padding to make space for new nodes and properties. */
	ret = fdt_open_into(fdt, fdt, fdt_totalsize(fdt) + DTB_PAD_SIZE);
	if (ret!= 0)
	{
		debugf( "Failed to move/resize dtb buffer: %d\n", ret);
		return ret;
	}

	/* Get offset of the memory node */
	ret = fdt_path_offset(fdt, "/memory");
	if (ret < 0)
	{
		debugf( "Could not find memory node.\n");
		return ret;
	}

	offset = ret;

	ret = target_dev_tree_mem(fdt, offset);
	if(ret)
	{
		debugf( "ERROR: Cannot update memory node\n");
		return ret;
	}

	/* Get offset of the chosen node */
	ret = fdt_path_offset(fdt, "/chosen");
	if (ret < 0)
	{
		debugf("Could not find chosen node.\n");
		return ret;
	}

	offset = ret;
	/* Adding the cmdline to the chosen node */
	ret = fdt_setprop_string(fdt, offset, (const char*)"bootargs", (const void*)cmdline);
	if (ret)
	{
		debugf( "ERROR: Cannot update chosen node [bootargs]\n");
		return ret;
	}

	/* Adding the initrd-start to the chosen node */
	ret = fdt_setprop_u32(fdt, offset, "linux,initrd-start", (uint32_t)ramdisk);
	if (ret)
	{
		debugf( "ERROR: Cannot update chosen node [linux,initrd-start]\n");
		return ret;
	}

	/* Adding the initrd-end to the chosen node */
	ret = fdt_setprop_u32(fdt, offset, "linux,initrd-end", ((uint32_t)ramdisk + ramdisk_size));
	if (ret)
	{
		debugf( "ERROR: Cannot update chosen node [linux,initrd-end]\n");
		return ret;
	}

	fdt_pack(fdt);

	return ret;
}
コード例 #17
0
ExampleCommand::ExampleCommand()
{
	debugf("ExampleCommand Instantiating");
}
コード例 #18
0
// returns -1 if the caller should ignore the result
// returns 1 if the record answers the question
// returns 0 if the record does not answer the question
mDNSexport int AnonInfoAnswersQuestion(const ResourceRecord *const rr, const DNSQuestion *const q)
{
    mDNSexport mDNS mDNSStorage;
    ResourceRecord *nsec3RR;
    int i;
    AnonymousInfo *qai, *rai;
    mDNSu8 *AnonData;
    int AnonDataLen;
    rdataNSEC3 *nsec3;
    int hlen;
    const mDNSu8 hashName[NSEC3_MAX_HASH_LEN];
    int nxtLength;
    mDNSu8 *nxtName;

    debugf("AnonInfoAnswersQuestion: question qname %##s", q->qname.c);

    // Currently only PTR records can have anonymous information
    if (q->qtype != kDNSType_PTR)
    {
        return -1;
    }

    // We allow anonymous questions to be answered by both normal services (without the
    // anonymous information) and anonymous services that are part of the same set. And
    // normal questions discover normal services and all anonymous services. 
    //
    // The three cases have been enumerated clearly even though they all behave the
    // same way.
    if (!q->AnonInfo)
    {
        debugf("AnonInfoAnswersQuestion: not a anonymous type question");
        if (!rr->AnonInfo)
        {
            // case 1
            return -1;
        }
        else
        {
            // case 2
            debugf("AnonInfoAnswersQuestion: Question %##s not answered using anonymous record %##s", q->qname.c, rr->name->c);
            return -1;
        }
    }
    else
    {
        // case 3
        if (!rr->AnonInfo)
        {
            debugf("AnonInfoAnswersQuestion: not a anonymous type record");
            return -1;
        }
    }

    // case 4: We have the anonymous information both in the question and the record. We need
    // two sets of information to validate.
    //
    // 1) Anonymous data that identifies the set/group
    // 2) NSEC3 record that contains the hash and the salt
    //
    // If the question is a remote one, it does not have the anonymous information to validate (just
    // the NSEC3 record) and hence the anonymous data should come from the local resource record. If the
    // question is local, it can come from either of them and if there is a mismatch between the
    // question and record, it won't validate.

    qai = q->AnonInfo;
    rai = rr->AnonInfo;

    if (qai->AnonData && rai->AnonData)
    {
        // Before a cache record is created, if there is a matching question i.e., part
        // of the same set, then when the cache is created we also set the anonymous
        // information. Otherwise, the cache record contains just the NSEC3 record and we
        // won't be here for that case.
        //
        // It is also possible that a local question is matched against the local AuthRecord
        // as that is also the case for which the AnonData would be non-NULL for both.
        // We match questions against AuthRecords (rather than the cache) for LocalOnly case and 
        // to see whether a .local query should be suppressed or not. The latter never happens
        // because PTR queries are never suppressed.

        // If they don't belong to the same anonymous set, then no point in validating.
        if ((qai->AnonDataLen != rai->AnonDataLen) ||
            mDNSPlatformMemCmp(qai->AnonData, rai->AnonData, qai->AnonDataLen) != 0)
        {
            debugf("AnonInfoAnswersQuestion: AnonData mis-match for record  %s question %##s ",
                RRDisplayString(&mDNSStorage, rr), q->qname.c);
            return 0;
        }
        // AnonData matches i.e they belong to the same group and the same service.
        LogInfo("AnonInfoAnswersQuestion: Answering qname %##s, rname %##s, without validation", q->qname.c,
            rr->name->c);
        return 1;
    }
    else
    {
        debugf("AnonInfoAnswersQuestion: question %p, record %p", qai->AnonData, rai->AnonData);
    }

    if (qai->AnonData)
    {
        // If there is AnonData, then this is a local question. The
        // NSEC3 RR comes from the resource record which could be part
        // of the cache or local auth record. The cache entry could
        // be from a remote host or created when we heard our own 
        // announcements. In any case, we use that to see if it matches
        // the question.
        AnonData = qai->AnonData;
        AnonDataLen = qai->AnonDataLen;
        nsec3RR = rai->nsec3RR;
    }
    else
    {
        // Remote question or hearing our own question back
        AnonData = rai->AnonData;
        AnonDataLen = rai->AnonDataLen;
        nsec3RR = qai->nsec3RR;
    }

    if (!AnonData || !nsec3RR)
    {
        // AnonData can be NULL for the cache entry and if we are hearing our own question back, AnonData is NULL for
        // that too and we can end up here for that case.
        debugf("AnonInfoAnswersQuestion: AnonData %p or nsec3RR %p, NULL for question %##s, record %s", AnonData, nsec3RR,
            q->qname.c, RRDisplayString(&mDNSStorage, rr));
        return 0;
    }
    debugf("AnonInfoAnswersQuestion: Validating question %##s, ResourceRecord %s", q->qname.c, RRDisplayString(&mDNSStorage, nsec3RR));


    nsec3 = (rdataNSEC3 *)nsec3RR->rdata->u.data;

    if (!NSEC3HashName(nsec3RR->name, nsec3, AnonData, AnonDataLen, hashName, &hlen))
    {
        LogMsg("AnonInfoAnswersQuestion: NSEC3HashName failed for ##s", nsec3RR->name->c);
        return mDNSfalse;
    }
    if (hlen != SHA1_HASH_LENGTH)
    {
        LogMsg("AnonInfoAnswersQuestion: hlen wrong %d", hlen);
        return mDNSfalse;
    }

    NSEC3Parse(nsec3RR, mDNSNULL, &nxtLength, &nxtName, mDNSNULL, mDNSNULL);

    if (hlen != nxtLength)
    {
        LogMsg("AnonInfoAnswersQuestion: ERROR!! hlen %d not same as nxtLength %d", hlen, nxtLength);
        return mDNSfalse;
    }

    for (i = 0; i < nxtLength; i++)
    {
        if (nxtName[i] != hashName[i])
        {
            debugf("AnonInfoAnswersQuestion: mismatch output %x, digest %x, i %d", nxtName[i+1], hashName[i], i);
            return 0;
        }
    }
    LogInfo("AnonInfoAnswersQuestion: ResourceRecord %s matched question %##s (%s)", RRDisplayString(&mDNSStorage, nsec3RR), q->qname.c, DNSTypeName(q->qtype));
    return 1;
}