コード例 #1
0
int
main_v1_1(void){

	char		*nameOfFunction = "Tspi_Context_GetKeyByPublicInfo02";
	TSS_HCONTEXT	hContext;
	TSS_HTPM	hTPM;
	TSS_FLAG	initFlags;
	TSS_HKEY	hKey;
	TSS_HKEY	hSRK;
	TSS_RESULT	result;
	TSS_UUID	migratableSignUUID={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2};
	TSS_HPOLICY	srkUsagePolicy, keyUsagePolicy;
	TSS_HKEY	hMSigningKey;
	UINT32		ulPublicKeyLength = 2048;
	BYTE*		rgbPublicKeyInfo;
	initFlags	= TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048  |
			TSS_KEY_VOLATILE | TSS_KEY_NO_AUTHORIZATION |
			TSS_KEY_NOT_MIGRATABLE;
	TSS_FLAG	wrongType;
	BYTE		well_known_secret[20] = TSS_WELL_KNOWN_SECRET;
	
	wrongType = (TSS_PS_TYPE_SYSTEM + TSS_PS_TYPE_USER);
	print_begin_test(nameOfFunction);

		//Create
	result = Tspi_Context_Create(&hContext);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Create ", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Connect
	result = Tspi_Context_Connect(hContext, get_server(GLOBALSERVER));
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Connect ", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Get TPM Object
	result = Tspi_Context_GetTpmObject(hContext, &hTPM);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_GetTpmObject ", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Create Object
	result = Tspi_Context_CreateObject(hContext,
				TSS_OBJECT_TYPE_RSAKEY,
				initFlags, &hKey);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CreateObject ", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Load Key by UUID
	result = Tspi_Context_LoadKeyByUUID(hContext, 
					TSS_PS_TYPE_SYSTEM,
					SRK_UUID, &hSRK);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_LoadKeyByUUID ", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
#ifndef TESTSUITE_NOAUTH_SRK
		//Get Policy Object for the srkUsagePolicy
	result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE, &srkUsagePolicy);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_GetPolicyObject ", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Set Secret for the srkUsagePolicy
	result = Tspi_Policy_SetSecret(srkUsagePolicy, TESTSUITE_SRK_SECRET_MODE,
			TESTSUITE_SRK_SECRET_LEN, TESTSUITE_SRK_SECRET);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Policy_SetSecret ", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
#endif
		//Create the hKey with the hSRK wrapping key
	result = Tspi_Key_CreateKey(hKey, hSRK, 0);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Key_CreateKey", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Register the hKey
	result = Tspi_Context_RegisterKey(hContext,
				hKey, TSS_PS_TYPE_SYSTEM, migratableSignUUID,
				TSS_PS_TYPE_SYSTEM, SRK_UUID);
	if (result != TSS_SUCCESS &&
			TSS_ERROR_CODE(result) != TSS_E_KEY_ALREADY_REGISTERED) {
		print_error("Tspi_Context_RegisterKey ", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//Create the hKey with the hSRK wrapping key
	result = Tspi_Context_CloseObject(hContext, hKey);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CloseObject ", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
		//GetKeyByPublicInfo
	result = Tspi_Context_GetKeyByPublicInfo(hContext, 
			wrongType, TSS_ALG_RSA, 
			ulPublicKeyLength,
			rgbPublicKeyInfo, &hKey);
	if (TSS_ERROR_CODE(result) != TSS_E_BAD_PARAMETER) {
		if(!checkNonAPI(result)){
			print_error(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_UnregisterKey(hContext, TSS_PS_TYPE_SYSTEM,
						migratableSignUUID, &hKey);
			Tspi_Context_FreeMemory(hContext, NULL);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
		else{
			print_error_nonapi(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_UnregisterKey(hContext, TSS_PS_TYPE_SYSTEM,
						migratableSignUUID, &hKey);
			Tspi_Context_FreeMemory(hContext, NULL);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	}
	else{
		print_success(nameOfFunction, result);
		print_end_test(nameOfFunction);
		Tspi_Context_UnregisterKey(hContext, TSS_PS_TYPE_SYSTEM,
					migratableSignUUID, &hKey);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(0);
	}
}
コード例 #2
0
ファイル: thumb.c プロジェクト: asteadman/naken_asm
int parse_instruction_thumb(struct _asm_context *asm_context, char *instr)
{
char token[TOKENLEN];
int token_type;
char instr_case[TOKENLEN];
struct _operand operands[3];
int operand_count=0;
int matched=0;
int num;
int n;

  lower_copy(instr_case, instr);

  memset(&operands, 0, sizeof(operands));
  while(1)
  {
    token_type=tokens_get(asm_context, token, TOKENLEN);
    if (token_type==TOKEN_EOL || token_type==TOKEN_EOF)
    {
      break;
    }

    if (operand_count>=3)
    {
      print_error_opcount(instr, asm_context);
      return -1;
    }

    if ((num=get_register_thumb(token))!=-1)
    {
      operands[operand_count].type=OPERAND_REGISTER;
      operands[operand_count].value=num;
      token_type=tokens_get(asm_context, token, TOKENLEN);
      if (IS_TOKEN(token,'!'))
      {
        operands[operand_count].type=OPERAND_REGISTER_INC;
      }
        else
      {
        tokens_push(asm_context, token, token_type);
      }
    }
      else
    if ((num=get_h_register_thumb(token))!=-1)
    {
      operands[operand_count].type=OPERAND_H_REGISTER;
      operands[operand_count].value=num;
    }
      else
    if (token_type==TOKEN_POUND)
    {
      if (eval_expression(asm_context, &num)!=0)
      {
        if (asm_context->pass==1)
        {
          eat_operand(asm_context);
        }
          else
        {
          print_error_illegal_expression(instr, asm_context);
          return -1;
        }
      }

      operands[operand_count].type=OPERAND_NUMBER;
      operands[operand_count].value=num;
    }
      else
    if (IS_TOKEN(token,'['))
    {
      token_type=tokens_get(asm_context, token, TOKENLEN);

      if (strcasecmp(token,"pc")==0 || strcasecmp(token,"r15")==0)
      {
        operands[operand_count].type=OPERAND_PC_AND_REG_IN_BRACKETS;
      }
        else
      if (strcasecmp(token,"sp")==0 || strcasecmp(token,"r13")==0)
      {
        operands[operand_count].type=OPERAND_SP_AND_REG_IN_BRACKETS;
      }
        else
      if ((num=get_register_thumb(token))!=-1)
      {
        operands[operand_count].type=OPERAND_TWO_REG_IN_BRACKETS;
        operands[operand_count].value=num;
      }
        else
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

      if (expect_token_s(asm_context,",")!=0) { return -1; }

      token_type=tokens_get(asm_context, token, TOKENLEN);

      if ((num=get_register_thumb(token))!=-1)
      {
        operands[operand_count].second_value=num;
        if (operands[operand_count].type==OPERAND_PC_AND_NUM_IN_BRACKETS)
        {
          operands[operand_count].type=OPERAND_PC_AND_REG_IN_BRACKETS;
        }
      }
        else
      if (token_type==TOKEN_POUND)
      {
        if (eval_expression(asm_context, &num)!=0)
        {
          if (asm_context->pass==1)
          {
            eat_operand(asm_context);
          }
            else
          {
            print_error_illegal_expression(instr, asm_context);
            return -1;
          }
        }

        operands[operand_count].second_value=num;
        operands[operand_count].type++;
      }
        else
      {
        print_error_unexp(token, asm_context);
        return -1;
      }

      if (expect_token_s(asm_context,"]")!=0) { return -1; }
    }
      else
    if (IS_TOKEN(token,'{'))
    {
      operands[operand_count].type=OPERAND_REGISTER_LIST;
      if (read_register_list(asm_context, &operands[operand_count])==-1)
      {
        return -1;
      }
    }
      else
    {
      tokens_push(asm_context, token, token_type);

      if (eval_expression(asm_context, &num)!=0)
      {
        if (asm_context->pass==1)
        {
          eat_operand(asm_context);
        }
          else
        {
          print_error_illegal_expression(instr, asm_context);
          return -1;
        }
      }

      operands[operand_count].value=num;
      operands[operand_count].type=OPERAND_ADDRESS;
    }

    operand_count++;
    token_type=tokens_get(asm_context, token, TOKENLEN);
    if (token_type==TOKEN_EOL) break;
    if (IS_NOT_TOKEN(token,',') || operand_count==3)
    {
      print_error_unexp(token, asm_context);
      return -1;
    }
  }

  n=0;
  while(table_thumb[n].instr!=NULL)
  {
    if (strcmp(table_thumb[n].instr,instr_case)==0)
    {
      matched=1;

      switch(table_thumb[n].type)
      {
        case OP_SHIFT:
          if (operand_count==3 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REGISTER &&
              operands[2].type==OPERAND_NUMBER)
          {
            if (check_reg_lower(asm_context, operands[0].value)==-1) { return -1; }
            if (check_reg_lower(asm_context, operands[1].value)==-1) { return -1; }
            if (check_range(asm_context, "Offset", operands[2].value, 0, 31)==-1) { return -1; }
#if 0
            if (operands[2].value<0 || operands[2].value>31)
            {
              print_error_range("Offset", 0, 31, asm_context);
              return -1;
            }
#endif
            add_bin16(asm_context, table_thumb[n].opcode|(operands[2].value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_ADD_SUB:
          if (operand_count==3 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REGISTER &&
              operands[2].type==OPERAND_REGISTER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[2].value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
            else
          if (operand_count==3 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REGISTER &&
              operands[2].type==OPERAND_NUMBER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(1<<10)|(operands[2].value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_IMM:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_NUMBER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<8)|(operands[1].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_ALU:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REGISTER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_HI:
          if (operand_count==2)
          {
            if (operands[0].type==OPERAND_H_REGISTER &&
                operands[1].type==OPERAND_REGISTER)
            {
              add_bin16(asm_context, table_thumb[n].opcode|(1<<7)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
              return 2;
            }
              else
            if (operands[0].type==OPERAND_REGISTER &&
                operands[1].type==OPERAND_H_REGISTER)
            {
              add_bin16(asm_context, table_thumb[n].opcode|(1<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
              return 2;
            }
              else
            if (operands[0].type==OPERAND_H_REGISTER &&
                operands[1].type==OPERAND_H_REGISTER)
            {
              add_bin16(asm_context, table_thumb[n].opcode|(1<<7)|(1<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
              return 2;
            }
          }
          break;
        case OP_HI_BX:
          if (operand_count==1 &&
              operands[0].type==OPERAND_REGISTER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<3), IS_OPCODE);
            return 2;
          }
            else
          if (operand_count==1 &&
              operands[0].type==OPERAND_H_REGISTER)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(1<<6)|(operands[0].value<<3), IS_OPCODE);
            return 2;
          }
          break;
        case OP_PC_RELATIVE_LOAD:
          // REVIEW - Docs say this is a 10 bit, 4 byte aligned number
          // and it seems unsigned.  Why isn't this signed?
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_PC_AND_NUM_IN_BRACKETS)
          {
            if (check_range(asm_context, "Offset", operands[1].second_value, 0, 1020)==-1) { return -1; }
            if (is_4_byte_aligned(asm_context, operands[1].second_value)==-1) { return -1; }
#if 0
            if ((operands[1].second_value&0x3)!=0)
            {
              print_error("Offset not 4 byte aligned", asm_context);
              return -1;
            }
#endif
            add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<8)|(operands[1].second_value>>2), IS_OPCODE);
            return 2;
          }
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_ADDRESS)
          {
            // REVIEW: This looks so odd.  Docs say: The value of the PC will
            // be 4 bytes greater than the address of this instruction, but bit
            // 1 of the PC is forced to 0 to ensure it is word aligned.
            if (is_4_byte_aligned(asm_context, operands[1].value)==-1) { return -1; }
#if 0
            if ((operands[1].value&0x3)!=0)
            {
              print_error("Offset not 4 byte aligned", asm_context);
              return -1;
            }
#endif
            int offset=operands[1].value-((asm_context->address+4)&0xfffffffc);
            if (asm_context->pass==1) { offset=0; }
            if (check_range(asm_context, "Offset", offset, 0, 1020)==-1) { return -1; }
#if 0
            if (offset<0 || offset>1020)
            {
              print_error_range("Offset", 0, 1020, asm_context);
              return -1;
            }
#endif
            add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<8)|(offset>>2), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_TWO_REG_IN_BRACKETS)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[1].second_value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE_SIGN_EXT_HALF_WORD:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_TWO_REG_IN_BRACKETS)
          {
            add_bin16(asm_context, table_thumb[n].opcode|(operands[1].second_value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE_IMM_OFFSET_WORD:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REG_AND_NUM_IN_BRACKETS)
          {
            int offset=operands[1].second_value;
            if (check_range(asm_context, "Offset", offset, 0, 124)==-1) { return -1; }
            if (is_4_byte_aligned(asm_context, offset)==-1) { return -1; }
#if 0
            if ((offset&0x3)!=0)
            {
              print_error("Offset not 4 byte aligned", asm_context);
              return -1;
            }
#endif
            offset=offset>>2;
            add_bin16(asm_context, table_thumb[n].opcode|(offset<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE_IMM_OFFSET:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REG_AND_NUM_IN_BRACKETS)
          {
            if (check_range(asm_context, "Offset", operands[1].second_value, 0, 31)==-1) { return -1; }
            add_bin16(asm_context, table_thumb[n].opcode|(operands[1].second_value<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE_IMM_OFFSET_HALF_WORD:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_REG_AND_NUM_IN_BRACKETS)
          {
            int offset=operands[1].second_value;
            if (check_range(asm_context, "Offset", offset, 0, 60)==-1) { return -1; }
            if (is_2_byte_aligned(asm_context, offset)==-1) { return -1; }
#if 0
            if ((offset&0x1)!=0)
            {
              print_error("Offset not 2 byte aligned", asm_context);
              return -1;
            }
#endif
            offset=offset>>1;
            add_bin16(asm_context, table_thumb[n].opcode|(offset<<6)|(operands[1].value<<3)|(operands[0].value), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_STORE_SP_RELATIVE:
          if (operand_count==2 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_SP_AND_NUM_IN_BRACKETS)
          {
            if (check_range(asm_context, "Offset", operands[1].value, 0, 1020)==-1) { return -1; }
            if (is_4_byte_aligned(asm_context, operands[1].value)==-1) { return -1; }
            add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<8)|(operands[1].second_value>>2), IS_OPCODE);
            return 2;
          }
          break;
        case OP_LOAD_ADDRESS:
          if (operand_count==3 &&
              operands[0].type==OPERAND_REGISTER &&
              operands[1].type==OPERAND_H_REGISTER &&
              operands[2].type==OPERAND_NUMBER)
          {
            if (check_range(asm_context, "Offset", operands[2].value, 0, 1020)==-1) { return -1; }
            if (is_4_byte_aligned(asm_context, operands[2].value)==-1) { return -1; }
            if (operands[1].value==7)
            {
              add_bin16(asm_context, table_thumb[n].opcode|(operands[0].value<<8)|(operands[2].value>>2), IS_OPCODE);
              return 2;
            }
              else
            if (operands[1].value==5)
コード例 #3
0
ファイル: db_db2_result.c プロジェクト: unizeto/bmd
/* TODO zaimplementowac FETCH_NEXT */
long db2_bmd_db_result_get_value(void *hDB,void *hRes,long which_row,long which_column,char **value,
							 EnumDbFetchMode_t fetch_mode,long *successfully_fetched)
{
	PRINT_INFO("\n");

	DB_bmd_db_conn_t *db_conn=NULL;
	//DB_bmd_db_result_t *db_res=NULL;
	SQLRETURN     rc;


	/*	walidacja parametrow	*/
	/******************************/
	if(hDB==NULL)			{	BMD_FOK(BMD_DB_INVALID_CONNECTION_HANDLE);	}
	if(which_row<0)					{	BMD_FOK(BMD_ERR_PARAM3);	}
	if(which_column<0)				{	BMD_FOK(BMD_ERR_PARAM4);	}
	if(value == NULL)				{	BMD_FOK(BMD_ERR_PARAM5);	}
	if(*value != NULL)				{       BMD_FOK(BMD_ERR_PARAM5);        }
	if(successfully_fetched == NULL)		{	BMD_FOK(BMD_ERR_PARAM6);	}
	if(*successfully_fetched < 0)			{	BMD_FOK(BMD_ERR_PARAM6);	}
	if( (*((long *)(hDB)) != BMD_DBCONN_MAGIC ) )
		return BMD_ERR_INVALID_PTR;


	db_conn=(DB_bmd_db_conn_t *)hDB;
	//db_res=(DB_bmd_db_result_t *)hRes;
	/*
	 * Only FETCH_NEXT mode implemented	 *
	 */


	//if(which_column != 0)
	//	return BMD_ERR_FORMAT;

	if(*successfully_fetched == 0){		
		rc = SQLFetch(*(db_conn->hstmt));
		long ret = print_error(rc, "SQLFetch");
		if(ret!=BMD_OK)
		{
		    if(ret == 5)
		   		return BMD_ERR_NODATA;
	   		else{
   				extract_error("SQLAllocHandle", *(db_conn->hstmt), SQL_HANDLE_STMT);
   				return BMD_DB_EXECUTION_ERROR;
   			}
		}
	}

    int colNum = 0;
    SQLINTEGER sql_ub;
    rc = SQLGetStmtAttr( *(db_conn->hstmt), SQL_ATTR_USE_BOOKMARKS, &sql_ub, 0, NULL ) ;
    if(print_error(rc, "SQLGetStmtAttr") != BMD_OK)
    			return BMD_ERR_OP_FAILED;
    if ( sql_ub == SQL_UB_OFF )
    	colNum = which_column + 1;
    else
    	colNum = which_column;


	//SQLCHAR *
	SQLINTEGER indicator;

	//TODO - koniecznie zrobiæ bufor dynamiczny!!!

	SQLCHAR buf[32000];
	/* retrieve column data as a string */
	rc = SQLGetData(*(db_conn->hstmt), colNum, SQL_C_CHAR, buf, sizeof(buf), &indicator);

	long retu = print_error(rc, "SQLGetData");
	if(retu!=BMD_OK)
	{
		if(retu == 5)
			return BMD_ERR_NODATA;
	   	else
	   		return BMD_ERR_OP_FAILED;
    }

//PRINT_INFO("Indicator: %d\n", (int)indicator);
if(indicator <= 0)
{
	//PRINT_INFO("Pobrano pust¹ wartoœæ\n");
	asprintf(value,"%s","");
	return BMD_OK;
}
	asprintf(value,"%s",buf);
    return BMD_OK;
}
コード例 #4
0
int ispv1_load_phy_setting(char *filename, u8 *settle_time, u8 *camera_source)
{
	struct kstat stat;
	mm_segment_t fs;
	struct file *fp = NULL;
	int file_flag = O_RDONLY;
	ssize_t ret = 0;
	char addr_array[8] = {0};
	char value_array[6] = {0};
	char temp = 0;
	bool bRegStart = false;

	if (NULL == filename) {
		print_error("%s param error", __func__);
		return -EINVAL;
	}

	print_debug("enter %s", __func__);

	/* must have the following 2 statement */
	fs = get_fs();
	set_fs(KERNEL_DS);

	fp = filp_open(filename, file_flag, 0666);
	if (IS_ERR_OR_NULL(fp)) {
		print_error("open file error!\n");
		return -1;
	}

	if (0 != vfs_stat(filename, &stat)) {
		print_error("failed to get file state!");
		goto error_out;
	}
	print_info("file size : %d", (u32) stat.size);
	while (0 < vfs_read(fp, &temp, 1, &fp->f_pos)) {
		switch (temp) {
		case '{':
			bRegStart = true;
			if (0 == vfs_read(fp, addr_array, 4, &fp->f_pos))
				goto error_out;
			*settle_time = atoi16(addr_array);
			break;

		case '}':
			bRegStart = false;
			break;

		case ',':
			if (bRegStart) {
				if (0 == vfs_read(fp, value_array, 4, &fp->f_pos))
					goto error_out;
				*camera_source = atoi16(value_array);
				bRegStart = false;
			}
			break;

		default:
			break;
		}
	}

	/* must have the following 1 statement */
	set_fs(fs);

error_out:
	if (NULL != fp)
		filp_close(fp, 0);
	return ret;
}
コード例 #5
0
int
main_v1_2( char version )
{
	char *			function = "Tspi_TPM_GetAuditDigest09";
	TSS_HCONTEXT		hContext;
	TSS_HKEY		hSRK;
	TSS_HTPM		hTPM;
	TSS_HPOLICY		hTpmPolicy;
	UINT32			auditDigestLen, ordListLen;
	BYTE *			auditDigest;
	UINT32 *		ordList;
	TSS_RESULT		result;

	print_begin_test( function );

	result = connect_load_all(&hContext, &hSRK, &hTPM);
	if ( result != TSS_SUCCESS )
	{
		print_error( "connect_load_all", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

	result = Tspi_GetPolicyObject(hTPM, TSS_POLICY_USAGE, &hTpmPolicy);
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_GetPolicyObject", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

	result = Tspi_Policy_SetSecret(hTpmPolicy, TESTSUITE_OWNER_SECRET_MODE,
					TESTSUITE_OWNER_SECRET_LEN, TESTSUITE_OWNER_SECRET);
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Policy_SetSecret", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

	/* Check if ordinal auditing is supported on this TPM */
	result = Testsuite_Is_Ordinal_Supported(hTPM, TPM_ORD_SetOrdinalAuditStatus);
	if (result != TSS_SUCCESS) {
		fprintf(stderr, "%s: TPM doesn't support auditing, returning success\n", __FILE__);
		print_success( function, TSS_SUCCESS );
		print_end_test( function );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( 0 );
	}

		// Call GetAuditDigest
	result = Tspi_TPM_GetAuditDigest(hTPM, NULL_HKEY, FALSE, &auditDigestLen, &auditDigest,
					 NULL, NULL, &ordListLen, &ordList);
	if (TSS_ERROR_CODE(result) != TSS_E_BAD_PARAMETER)
	{
		print_error( function , result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	} else 
	{
		print_success( function, result );
	}

	print_end_test( function );
	Tspi_Context_FreeMemory( hContext, NULL );
	Tspi_Context_Close( hContext );
	exit( 0 );
}
コード例 #6
0
int main_v1_2(char version)
{
	char *function = "Tspi_Hash_TickStampBlob05";
	TSS_HCONTEXT hContext;
	TSS_HKEY hSRK, hMSigningKey;
	TSS_HHASH hHash;
	TSS_HTPM hTPM;
	TSS_RESULT result;
	TSS_HPOLICY srkUsagePolicy;
	TSS_VALIDATION validationData;

	print_begin_test(function);

	// Create Context
	result = Tspi_Context_Create(&hContext);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Create", result);
		exit(result);
	}
	// Connect to Context
	result = Tspi_Context_Connect(hContext, get_server(GLOBALSERVER));
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Connect", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	result = Tspi_Context_GetTpmObject(hContext, &hTPM);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_GetTpmObject", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Load Key By UUID
	result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM,
					    SRK_UUID, &hSRK);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_LoadKeyByUUID (hSRK)", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}
#ifndef TESTSUITE_NOAUTH_SRK
	//Get Policy Object
	result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE,
				      &srkUsagePolicy);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_GetPolicyObject", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Set Secret
	result = Tspi_Policy_SetSecret(srkUsagePolicy, TESTSUITE_SRK_SECRET_MODE,
				       TESTSUITE_SRK_SECRET_LEN, TESTSUITE_SRK_SECRET);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Policy_SetSecret", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}
#endif
	//Create Signing Key
	result =
	    Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY,
				      TSS_KEY_SIZE_2048 |
				      TSS_KEY_TYPE_SIGNING |
				      TSS_KEY_NO_AUTHORIZATION,
				      &hMSigningKey);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CreateObject (signing key)",
			    result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	result = Tspi_Key_CreateKey(hMSigningKey, hSRK, 0);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Key_CreateKey (signing key)", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	result = Tspi_Key_LoadKey(hMSigningKey, hSRK);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_LoadKey (hMSigningKey)", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	// create hash
	result = Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_HASH,
					   TSS_HASH_SHA1, &hHash);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CreateObject (hash)", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	result = Tspi_Hash_SetHashValue(hHash, 20, "Je pense, danc je s");
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Hash_SetHashValue", result);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	validationData.rgbExternalData = NULL;
	validationData.ulExternalDataLength = 0;

	result = Tspi_Hash_TickStampBlob(hHash, hMSigningKey, &validationData);
	if (TSS_ERROR_CODE(result) != TSS_E_BAD_PARAMETER) {
		if (!(checkNonAPI(result))) {
			print_error(function, result);
		} else {
			print_error_nonapi(function, result);
		}

		print_end_test(function);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_Close(hContext);
		exit(TSS_E_FAIL);
	}

	print_success(function, result);
	print_end_test(function);
	Tspi_Context_FreeMemory(hContext, NULL);
	Tspi_Context_Close(hContext);
	exit(0);
}
コード例 #7
0
int
main_v1_1( void )
{
	char		*function = "Tspi_Context_GetKeyByUUID04";
	TSS_HKEY	hSRK;
	TSS_HKEY	hMSigningKey;
	TSS_UUID	SRKUUID			= {0,0,0,0,0,0,0,0,0,0,1};
	TSS_UUID	migratableSignUUID	= {1,2,3,4,5,6,7,8,9,10,2};
	TSS_UUID	wrongUUID		= {4,1,5,2,2,6,6,3,4,8,0};
	TSS_HCONTEXT	hContext;
	TSS_RESULT	result;
	TSS_HPOLICY	srkUsagePolicy;
	UINT32		exitCode = 0;

	print_begin_test( function );

		// Create Context
	result = Tspi_Context_Create( &hContext );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Context_Create", result );
		exit( result );
	}

		// Connect to Context
	result = Tspi_Context_Connect( hContext, get_server(GLOBALSERVER) );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Context_Connect", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

		// Load SRK
	result = Tspi_Context_LoadKeyByUUID( hContext, TSS_PS_TYPE_SYSTEM,
						SRK_UUID, &hSRK );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Context_LoadKeyByUUID (hSRK)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

#ifndef TESTSUITE_NOAUTH_SRK
		//Get Policy Object
	result = Tspi_GetPolicyObject( hSRK, TSS_POLICY_USAGE,
					&srkUsagePolicy );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_GetPolicyObject", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

		//Set Secret
	result = Tspi_Policy_SetSecret( srkUsagePolicy, TESTSUITE_SRK_SECRET_MODE,
					TESTSUITE_SRK_SECRET_LEN, TESTSUITE_SRK_SECRET );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Policy_SetSecret", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}
#endif

		//Create Signing Key
	result = Tspi_Context_CreateObject( hContext, TSS_OBJECT_TYPE_RSAKEY,
						TSS_KEY_SIZE_2048 |
						TSS_KEY_TYPE_SIGNING,
						&hMSigningKey );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Context_CreateObject (signing key)",
				result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

		// Create signing key
	result = Tspi_Key_CreateKey( hMSigningKey, hSRK, 0 );
	if ( result != TSS_SUCCESS )
	{
		print_error( "Tspi_Key_CreateKey (signing key)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

		// register signing key; srk is parent
	result = Tspi_Context_RegisterKey( hContext, hMSigningKey,
						TSS_PS_TYPE_SYSTEM,
						migratableSignUUID,
						TSS_PS_TYPE_SYSTEM,
						SRKUUID );
	if ( (result != TSS_SUCCESS) &&
		(TSS_ERROR_CODE(result) != TSS_E_KEY_ALREADY_REGISTERED))
	{
		print_error( "Tspi_Context_RegisterKey", result );
		Tspi_Context_UnregisterKey( hContext, TSS_PS_TYPE_SYSTEM,
						migratableSignUUID,
						&hMSigningKey );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}

		// get signing key
	result = Tspi_Context_GetKeyByUUID( hContext, TSS_PS_TYPE_SYSTEM,
						wrongUUID,
						&hMSigningKey );
	if ( TSS_ERROR_CODE(result) != TSS_E_PS_KEY_NOTFOUND )
	{
		if( !(checkNonAPI(result)) )
		{
			print_error( function, result );
			exitCode = result;
		}
		else
		{
			print_error_nonapi( function, result );
			exitCode = result;
		}
	}
	else
	{
		print_success( function, result );
	}

	print_end_test( function );
	Tspi_Context_UnregisterKey( hContext, TSS_PS_TYPE_SYSTEM,
					migratableSignUUID,
					&hMSigningKey );
	Tspi_Context_FreeMemory( hContext, NULL );
	Tspi_Context_Close( hContext );
	exit( exitCode );
}
コード例 #8
0
int
find_opaque_objects(CK_FUNCTION_LIST  *funcs,
		    CK_SESSION_HANDLE sess,
		    struct object     **objs_to_migrate)
{
	CK_RV		 rv;
	CK_OBJECT_HANDLE *handles = NULL, tmp;
	CK_ULONG	 ulObjectCount = 0, ulTotalCount = 0;
	CK_ATTRIBUTE	 attrs[] = {
		{ CKA_IBM_OPAQUE, NULL, 0 },
		{ CKA_CLASS, NULL, 0 },
		{ CKA_KEY_TYPE, NULL, 0 }
	};
	int	i, rc;

	/* Find all objects in the store */
	rv = funcs->C_FindObjectsInit(sess, NULL_PTR, 0);
	if (rv != CKR_OK) {
		p11_error("C_FindObjectsInit", rv);
		print_error("Error finding CCA key objects");
		return 1;
	}

	while (1) {
		rv = funcs->C_FindObjects(sess, &tmp, 1, &ulObjectCount);
		if (rv != CKR_OK) {
			p11_error("C_FindObjects", rv);
			print_error("Error finding CCA key objects");
			free(handles);
			return 1;
		}

		if (ulObjectCount == 0)
			break;

		handles = realloc(handles, sizeof(CK_OBJECT_HANDLE) * (++ulTotalCount));
		if (!handles) {
			print_error("Malloc of %lu bytes failed!", ulTotalCount);
			break;
		}

		handles[ulTotalCount - 1] = tmp;
	}
	if (v_flag > 1)
		printf("Found %lu PKCS#11 objects to examine\n", ulTotalCount);

	/* Don't care if this fails */
	funcs->C_FindObjectsFinal(sess);

	/* At this point we have an array with handles to every object in the store. We only care
	 * about those with a CKA_IBM_OPAQUE attribute, so whittle down the list accordingly */
	for (tmp = 0; tmp < ulTotalCount; tmp++) {
		rv = funcs->C_GetAttributeValue(sess, handles[tmp], attrs, 3);
		if (rv != CKR_OK) {
			p11_error("C_GetAttributeValue", rv);
			print_error("Error finding CCA key objects");
			free(handles);
			return 1;
		}

		/* If the opaque attr DNE for this object, move to the next one */
		if (attrs[0].ulValueLen == ((CK_ULONG)-1))
			continue;

		/* Allocate space in the template for the actual data */
		for (i = 0; i < 3; i++) {
			attrs[i].pValue = malloc(attrs[i].ulValueLen);
			if (!attrs[i].pValue) {
				print_error("Malloc of %lu bytes failed!", attrs[i].ulValueLen);
				free(handles);
				return 1;
			}
		}

		/* Pull in the actual data */
		rv = funcs->C_GetAttributeValue(sess, handles[tmp], attrs, 3);
		if (rv != CKR_OK) {
			p11_error("C_GetAttributeValue", rv);
			print_error("Error getting object attributes");
			free(handles);
			return 1;
		}

		rc = add_object(handles[tmp], attrs, objs_to_migrate);
		if (rc) {
			free(handles);
			return 1;
		}

		for (i = 0; i < 3; i++) {
			free(attrs[i].pValue);
			attrs[i].pValue = NULL_PTR;
			attrs[i].ulValueLen = 0;
		}
	}

	free(handles);

	return 0;
}
コード例 #9
0
int
main(int argc, char *argv[])
{
	int               opt, c_flag = 0;
	CK_SLOT_ID	  slot_id = 0;
	char		 *so_pin = NULL, *user_pin = NULL, *data_store = NULL;

	CK_FUNCTION_LIST *funcs;
	CK_ULONG	  slot_count;
	CK_SESSION_HANDLE sess;
	CK_RV		  rv;
	struct object    *objs_to_migrate = NULL, *tmp, *to_free;
	int		  exit_code = 0, rc;
	
	lib_csulcca = dlopen("libcsulcca.so", (RTLD_GLOBAL | RTLD_NOW));
	if (lib_csulcca == NULL) {
		print_error("Couldn't get a handle to the CCA library.");
		return NULL;
	}

	CSNDKTC = dlsym(lib_csulcca, "CSNDKTC_32");
	CSNBKTC = dlsym(lib_csulcca, "CSNBKTC_32");	

	while ((opt = getopt(argc, argv, "c:d:s:u:nvh")) != -1) {
		switch (opt) {
		case 'c':
			c_flag++;
			slot_id = atoi(optarg);
			break;

		case 'd':
			data_store = strdup(optarg);
			break;

		case 's':
			so_pin = strdup(optarg);
			break;

		case 'u':
			user_pin = strdup(optarg);
			break;

		case 'n':
			n_flag++;
			break;

		case 'v':
			v_flag++;
			break;

		case 'h':
			usage(argv[0]);
			return 0;

		default:
			usage(argv[0]);
			return 1;
		}
	}

	if (!c_flag || !data_store || !so_pin || !user_pin) {
		usage(argv[0]);
		return 1;
	}

	if (n_flag)
		printf("Dry-run of migration in progress\n");

	funcs = p11_init();
	if (!funcs) {
		return 2;
	}

	rv = funcs->C_GetSlotList(TRUE, NULL_PTR, &slot_count);
	if (rv != CKR_OK) {
		p11_error("C_GetSlotList", rv);
		exit_code = 3;
		goto finalize;
	}

	if (slot_id >= slot_count) {
		print_error("%lu is not a valid slot ID.", slot_id);
		exit_code = 4;
		goto finalize;
	}
	if (v_flag > 1)
		printf("Slot id %lu is valid\n", slot_id);

	/* Open a r/w session */
	rv = funcs->C_OpenSession(slot_id, CKF_RW_SESSION|CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &sess);
	if (rv != CKR_OK) {
		p11_error("C_OpenSession", rv);
		exit_code = 5;
		goto finalize;
	}
	if (v_flag > 1)
		printf("PKCS#11 r/w session opened\n");

	/* Login as the SO just validate the supplied pin */
	rv = funcs->C_Login(sess, CKU_SO, (CK_BYTE *)so_pin, strlen(so_pin));
	if (rv != CKR_OK) {
		p11_error("C_Login (SO)", rv);
		exit_code = 6;
		goto finalize;
	}
	if (v_flag > 1)
		printf("PKCS#11 SO login successful\n");

	/* Logout the SO */
	rv = funcs->C_Logout(sess);
	if (rv != CKR_OK) {
		p11_error("C_Logout", rv);
		exit_code = 7;
		goto finalize;
	}

	/* Login as the USER to validate the supplied pin and do the migration */
	rv = funcs->C_Login(sess, CKU_USER, (CK_BYTE *)user_pin, strlen(user_pin));
	if (rv != CKR_OK) {
		p11_error("C_Login (USER)", rv);
		exit_code = 8;
		goto finalize;
	}
	if (v_flag > 1)
		printf("PKCS#11 USER login successful\n");

	/* Find the affected PKCS#11 objects */
	rc = find_opaque_objects(funcs, sess, &objs_to_migrate);
	if (rc) {
		exit_code = 9;
		goto close;
	}

	/* XXX Print status: migrating X pub keys, X priv keys, X 3DES keys... */

	/* Use the CCA lib to migrate them to the new master key */
	rv = migrate_objects(objs_to_migrate);
	if (rv != CKR_OK) {
		exit_code = 10;
		goto close;
	}

	/* XXX Print status */

	/* Delete the old PKCS#11 objects (or just attribs if possible) and replace with the
	 * migrated data */
	rc = replace_objects(funcs, sess, objs_to_migrate);
	if (rc) {
		exit_code = 11;
		goto close;
	}

	/* XXX Print status: X objects successfully migrated */

	/* Free the list of PKCS#11 objects */
	for (to_free = objs_to_migrate; to_free; to_free = tmp) {
		tmp = to_free->next;
		free(to_free->opaque_attr);
		free(to_free);
	}

	/* Migrate the keys used to encrypt the data store */
	rc = migrate_master_keys(so_pin, user_pin, data_store);
	if (rc) {
		exit_code = 12;
		goto close;
	}

close:
	funcs->C_CloseSession(sess);
finalize:
	p11_fini(funcs);
	return exit_code;
}
コード例 #10
0
ファイル: cmdline.c プロジェクト: QuestOS/Support
/* Run an entry from the script SCRIPT. HEAP is used for the
   command-line buffer. If an error occurs, return non-zero, otherwise
   return zero.  */
int
run_script (char *script, char *heap)
{
  char *old_entry;
  char *cur_entry = script;

  /* Initialize the data.  */
  init_cmdline (0);

  while (1)
    {
      struct builtin *builtin;
      char *arg;

      print_error ();

      if (errnum)
	{
          grub_cln_recovery_shell (grub_cln_loaded_from_spi);
	}

      /* Copy the first string in CUR_ENTRY to HEAP.  */
      old_entry = cur_entry;
      while (*cur_entry++)
	;

      grub_memmove (heap, old_entry, cur_entry - old_entry);
      if (! *heap)
	{
	  /* If there is no more command in SCRIPT...  */

	  /* If any kernel is not loaded, just exit successfully.  */
	  if (kernel_type == KERNEL_TYPE_NONE)
	    return 0;

	  /* Otherwise, the command boot is run implicitly.  */
	  grub_memmove (heap, "boot", 5);
	}

      /* Find a builtin.  */
      builtin = find_command (heap);
      if (! builtin)
	{
	  grub_verbose_printf ("%s\n", old_entry);
	  continue;
	}

      if (! (builtin->flags & BUILTIN_NO_ECHO))
	grub_verbose_printf ("%s\n", old_entry);

      /* If BUILTIN cannot be run in the command-line, skip it.  */
      if (! (builtin->flags & BUILTIN_CMDLINE))
	{
	  errnum = ERR_UNRECOGNIZED;
	  continue;
	}

      /* Invalidate the cache, because the user may exchange removable
	 disks.  */
      buf_drive = -1;

      /* Run BUILTIN->FUNC.  */
      arg = skip_to (1, heap);
      (builtin->func) (arg, BUILTIN_SCRIPT);
    }
}
コード例 #11
0
ファイル: jj.c プロジェクト: paulpjryan/http-request-server
main(int argc, char *argv[]) {
    register int x,m=0;
    char *cl;
    char w[256];
    char tfile[L_tmpnam];
    int subs,slims,sides,drinks,allow;
    char name[32];
    char phone[10];
    char address[64];
    FILE *tfp,*order;

    printf("Content-type: text/html%c%c",LF,LF);

    cl=getenv("QUERY_STRING");
    if((!cl) || (!cl[0]))
        dump_form();

    tmpnam(tfile);
    if(!(tfp=fopen(tfile,"w"))) {
        printf("<TITLE>Server Error</TITLE>%c",LF);
        printf("<H1>Server Error</H1>%c",LF);
        printf("Server unable to get a temporary file. Please try again later.<P>%c",LF);
        exit(1);
    }

    subs=0;slims=0;sides=0;drinks=0;allow=0;
    name[0]='\0';
    phone[0]='\0';
    address[0]='\0';

    for(x=0;cl[0] != '\0'; x++) {
        m=x;
        getword(w,cl,'=');
        plustospace(w);
        unescape_url(w);
        if(!strcmp(w,"pwd")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            allow=(strcmp(w,PASSWORD) ? 0 : 1);
        }
        if(!strcmp(w,"sub")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            subs |= (1 << atoi(w));
        }
        else if(!strcmp(w,"slj")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            slims |= (1 << atoi(w));
        }
        else if(!strcmp(w,"sde")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            sides |= (1 << atoi(w));
        }
        else if(!strcmp(w,"pop")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            drinks |= (1 << atoi(w));
        }
        else if(!strcmp(w,"name")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(name,w);
        }
        else if(!strcmp(w,"phone")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(phone,w);
        }
        else if(!strcmp(w,"adr")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(address,w);
        }
    }

    if(!name[0]) print_error("you didn't give your name");
    if(!address[0]) print_error("you didn't give your address");
    if(!phone[0]) print_error("you didn't give your phone number");
    if((!subs) && (!slims) && (!sides) && (!drinks)) print_error("you didn't order anything");

    if(allow) {
        char t[256];
        sprintf(t,"/bin/mail %s",JJ_FAX);
        if(!(order=popen(t,"w")))
            print_error("the server was unable to open a pipe to mail");
        printf("<TITLE>Order Sent</TITLE>%c",LF);
        printf("<H1>Order Sent</H1>%c",LF);
        printf("Your order has been sent to the UIUC e-mail to FAX gateway.<P>%c",LF);
    } else {
        printf("<TITLE>Your Order</TITLE>%c",LF);
        printf("<H1>Your Order</H1>%c",LF);
        printf("This is how your order would have looked if it had been sent.<P><PLAINTEXT>%c",LF);
        order=stdout;
    }

    fprintf(order,"My name is %s, and I would like to have the following%c",
            name,LF);
    fprintf(order,"order delivered to %s:%c%c",address,LF,LF);
    for(x=0;x<12;x++)
        if(subs & (1 << x))
            fprintf(order,"\t(1) %s%c",sublist[x],LF);
    for(x=0;x<6;x++)
        if(slims & (1 << x))
            fprintf(order,"\t(1) %s Slim Jim%c",slimlist[x],LF);
    for(x=0;x<2;x++)
        if(sides & (1 << x))
            fprintf(order,"\t(1) %s%c",sidelist[x],LF);
    for(x=0;x<4;x++)
        if(drinks & (1 << x))
            fprintf(order,"\t(1) %s%c",poplist[x],LF);
    fprintf(order,"%cPlease feel free to call me at %s if there is any%c",LF,
            phone,LF);
    fprintf(order,"problem. Thank you.%c%c.%c",LF,LF,LF);
    fclose(order);
    exit(0);
}
コード例 #12
0
ファイル: cmd_pls.c プロジェクト: Reilithion/xmms2-reilithion
void
cmd_playlist_type (xmmsc_connection_t *conn, gint argc, gchar **argv)
{
	gchar *name;
	xmmsv_coll_type_t prevtype, newtype;
	xmmsc_result_t *res;
	xmmsv_t *val;
	xmmsv_coll_t *coll;

	/* Read playlist name */
	if (argc < 4) {
		print_error ("usage: type_playlist [playlistname] [type] [options]");
	}
	name = argv[3];

	/* Retrieve the playlist operator */
	res = xmmsc_coll_get (conn, name, XMMS_COLLECTION_NS_PLAYLISTS);
	xmmsc_result_wait (res);
	val = xmmsc_result_get_value (res);

	if (xmmsv_is_error (val)) {
		print_error ("%s", xmmsv_get_error_old (val));
	}

	xmmsv_get_coll (val, &coll);
	prevtype = xmmsv_coll_get_type (coll);

	/* No type argument, simply display the current type */
	if (argc < 5) {
		print_info (get_playlist_type_string (prevtype));

	/* Type argument, set the new type */
	} else {
		gint typelen;
		gint idlistsize;
		xmmsc_result_t *saveres;
		xmmsv_coll_t *newcoll;
		gint i;

		typelen = strlen (argv[4]);
		if (g_ascii_strncasecmp (argv[4], "list", typelen) == 0) {
			newtype = XMMS_COLLECTION_TYPE_IDLIST;
		} else if (g_ascii_strncasecmp (argv[4], "queue", typelen) == 0) {
			newtype = XMMS_COLLECTION_TYPE_QUEUE;
		} else if (g_ascii_strncasecmp (argv[4], "pshuffle", typelen) == 0) {
			newtype = XMMS_COLLECTION_TYPE_PARTYSHUFFLE;

			/* Setup operand for party shuffle (set operand) ! */
			if (argc < 6) {
				print_error ("Give the source collection for the party shuffle");
			}

		} else {
			print_error ("Invalid playlist type (valid types: list, queue, pshuffle)");
		}

		/* Copy collection idlist, attributes and operand (if needed) */
		newcoll = xmmsv_coll_new (newtype);

		idlistsize = xmmsv_coll_idlist_get_size (coll);
		for (i = 0; i < idlistsize; i++) {
			guint id;
			xmmsv_coll_idlist_get_index (coll, i, &id);
			xmmsv_coll_idlist_append (newcoll, id);
		}

		xmmsv_coll_attribute_foreach (coll, coll_copy_attributes, newcoll);

		if (newtype == XMMS_COLLECTION_TYPE_PARTYSHUFFLE) {
			playlist_setup_pshuffle (conn, newcoll, argv[5]);
		}

		/* Overwrite with new collection */
		saveres = xmmsc_coll_save (conn, newcoll, name, XMMS_COLLECTION_NS_PLAYLISTS);
		xmmsc_result_wait (saveres);

		if (xmmsc_result_iserror (saveres)) {
			print_error ("Couldn't save %s : %s",
			             name, xmmsc_result_get_error (saveres));
		}

		xmmsv_coll_unref (newcoll);
		xmmsc_result_unref (saveres);
	}

	xmmsc_result_unref (res);
}
コード例 #13
0
ファイル: cmd_pls.c プロジェクト: Reilithion/xmms2-reilithion
void
cmd_list (xmmsc_connection_t *conn, gint argc, gchar **argv)
{
	gchar *playlist = NULL;
	xmmsc_result_t *res;
	xmmsv_t *val;
	xmmsv_list_iter_t *it;
	gulong total_playtime = 0;
	gint p = 0;
	guint pos = 0;

	if (argc > 2) {
		playlist = argv[2];
	}

	res = xmmsc_playlist_current_pos (conn, playlist);
	xmmsc_result_wait (res);
	val = xmmsc_result_get_value (res);

	if (!xmmsv_is_error (val)) {
		if (!xmmsv_dict_entry_get_int (val, "position", &p)) {
			print_error ("Broken resultset");
		}
		xmmsc_result_unref (res);
	}

	res = xmmsc_playlist_list_entries (conn, playlist);
	xmmsc_result_wait (res);
	val = xmmsc_result_get_value (res);

	if (xmmsv_is_error (val)) {
		print_error ("%s", xmmsv_get_error_old (val));
	}

	xmmsv_get_list_iter (val, &it);
	while (xmmsv_list_iter_valid (it)) {
		xmmsc_result_t *info_res;
		xmmsv_t *val_id, *propdict, *info_val;
		gchar line[80];
		gint playtime = 0;
		guint ui;

		xmmsv_list_iter_entry (it, &val_id);
		if (!xmmsv_get_uint (val_id, &ui)) {
			print_error ("Broken resultset");
		}

		info_res = xmmsc_medialib_get_info (conn, ui);
		xmmsc_result_wait (info_res);
		propdict = xmmsc_result_get_value (info_res);
		info_val = xmmsv_propdict_to_dict (propdict, NULL);

		if (xmmsv_is_error (info_val)) {
			print_error ("%s", xmmsv_get_error_old (info_val));
		}

		if (xmmsv_dict_entry_get_int (info_val, "duration", &playtime)) {
			total_playtime += playtime;
		}

		if (val_has_key (info_val, "channel")) {
			if (val_has_key (info_val, "title")) {
				xmmsc_entry_format (line, sizeof (line),
				                    "[stream] ${title}", info_val);
			} else {
				xmmsc_entry_format (line, sizeof (line),
				                    "${channel}", info_val);
			}
		} else if (!val_has_key (info_val, "title")) {
			const gchar *url;
			gchar dur[10];

			xmmsc_entry_format (dur, sizeof (dur),
			                    "(${minutes}:${seconds})", info_val);

			if (xmmsv_dict_entry_get_string (info_val, "url", &url)) {
				gchar *filename = g_path_get_basename (url);
				if (filename) {
					g_snprintf (line, sizeof (line), "%s %s", filename, dur);
					g_free (filename);
				} else {
					g_snprintf (line, sizeof (line), "%s %s", url, dur);
				}
			}
		} else {
			xmmsc_entry_format (line, sizeof (line), listformat, info_val);
		}

		if (p == pos) {
			print_info ("->[%d/%d] %s", pos, ui, line);
		} else {
			print_info ("  [%d/%d] %s", pos, ui, line);
		}

		pos++;

		xmmsc_result_unref (info_res);
		xmmsv_unref (info_val);
		xmmsv_list_iter_next (it);
	}
	xmmsc_result_unref (res);

	/* rounding */
	total_playtime += 500;

	print_info ("\nTotal playtime: %d:%02d:%02d", total_playtime / 3600000,
	            (total_playtime / 60000) % 60, (total_playtime / 1000) % 60);
}
コード例 #14
0
ファイル: git-wrapper.c プロジェクト: DavidTongxx/git
int main(void)
{
	int r = 1, wait = 1, prefix_args_len = -1, needs_env_setup = 1,
		is_git_command = 1, full_path = 1, skip_arguments = 0,
		allocate_console = 0, show_console = 0;
	WCHAR exepath[MAX_PATH], exe[MAX_PATH], top_level_path[MAX_PATH];
	LPWSTR cmd = NULL, exep = exe, prefix_args = NULL, basename;
	LPWSTR working_directory = NULL;

	/* Determine MSys2-based Git path. */
	swprintf(msystem_bin, sizeof(msystem_bin),
		L"mingw%d\\bin", (int) sizeof(void *) * 8);
	*top_level_path = L'\0';

	/* get the installation location */
	GetModuleFileName(NULL, exepath, MAX_PATH);
	if (!PathRemoveFileSpec(exepath)) {
		fwprintf(stderr, L"Invalid executable path: %s\n", exepath);
		ExitProcess(1);
	}
	basename = exepath + wcslen(exepath) + 1;
	if (configure_via_resource(basename, exepath, exep,
			&prefix_args, &prefix_args_len,
			&is_git_command, &working_directory,
			&full_path, &skip_arguments, &allocate_console,
			&show_console)) {
		/* do nothing */
	}
	else if (!wcsicmp(basename, L"git-gui.exe")) {
		static WCHAR buffer[BUFSIZE];
		wait = 0;
		allocate_console = 1;
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			swprintf(buffer, BUFSIZE,
				L"\"%s\\%.*s\\libexec\\git-core\"",
				exepath, wcslen(msystem_bin) - 4, msystem_bin);
		else {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			swprintf(buffer, BUFSIZE,
				L"\"%s\\mingw\\libexec\\git-core\"",
				top_level_path);
		}
		PathAppend(buffer, L"git-gui");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}
	else if (!wcsnicmp(basename, L"git-", 4)) {
		needs_env_setup = 0;

		/* Call a builtin */
		prefix_args = basename + 4;
		prefix_args_len = wcslen(prefix_args);
		if (!wcsicmp(prefix_args + prefix_args_len - 4, L".exe"))
			prefix_args_len -= 4;

		/* set the default exe module */
		wcscpy(exe, exepath);
		PathAppend(exe, L"git.exe");
	}
	else if (!wcsicmp(basename, L"git.exe")) {
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"git.exe");
		if (_waccess(exe, 0) == -1) {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"bin\\git.exe");
		}
	}
	else if (!wcsicmp(basename, L"gitk.exe")) {
		static WCHAR buffer[BUFSIZE];
		allocate_console = 1;
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		swprintf(buffer, BUFSIZE, L"\"%s\"", top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			PathAppend(buffer, msystem_bin);
		else {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			PathAppend(buffer, L"mingw\\bin");
		}
		PathAppend(buffer, L"gitk");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}

	if (needs_env_setup) {
		if (!top_level_path[0])
			initialize_top_level_path(top_level_path, exepath,
					msystem_bin, -4);

		setup_environment(top_level_path, full_path);
	}
	cmd = fixup_commandline(exepath, &exep, &wait,
		prefix_args, prefix_args_len, is_git_command, skip_arguments);

	if (working_directory == (LPWSTR)1) {
		int len = GetEnvironmentVariable(L"HOME", NULL, 0);

		if (len) {
			working_directory = malloc(sizeof(WCHAR) * len);
			GetEnvironmentVariable(L"HOME", working_directory, len);
		}
	}

	{
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT;
		HANDLE console_handle;
		BOOL br = FALSE;
		ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
		ZeroMemory(&si, sizeof(STARTUPINFO));
		si.cb = sizeof(STARTUPINFO);

		if (allocate_console | show_console)
			creation_flags |= CREATE_NEW_CONSOLE;
		else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE,
				FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL)) !=
				INVALID_HANDLE_VALUE)
			CloseHandle(console_handle);
		else {
#define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE
			STD_HANDLE(Input, INPUT_HANDLE);
			STD_HANDLE(Output, OUTPUT_HANDLE);
			STD_HANDLE(Error, ERROR_HANDLE);
			si.dwFlags = STARTF_USESTDHANDLES;


			creation_flags |= CREATE_NO_WINDOW;
		}
		if (show_console) {
			si.dwFlags |= STARTF_USESHOWWINDOW;
			si.wShowWindow = SW_SHOW;
		}
		br = CreateProcess(/* module: null means use command line */
				exep,
				cmd,  /* modified command line */
				NULL, /* process handle inheritance */
				NULL, /* thread handle inheritance */
					/* handles inheritable? */
				allocate_console ? FALSE : TRUE,
				creation_flags,
				NULL, /* environment: use parent */
				working_directory, /* use parent's */
				&si, &pi);
		if (br) {
			if (wait)
				WaitForSingleObject(pi.hProcess, INFINITE);
			if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r))
				print_error(L"error reading exit code",
					GetLastError());
			CloseHandle(pi.hProcess);
		}
		else {
			print_error(L"error launching git", GetLastError());
			r = 1;
		}
	}

	free(cmd);

	ExitProcess(r);
}
コード例 #15
0
ファイル: print_aranges.c プロジェクト: bergeret/libdwarf
static void
do_checking(Dwarf_Debug dbg, Dwarf_Arange *arange_buf,Dwarf_Signed i,
    Dwarf_Off cu_die_offset,Dwarf_Bool first_cu,
    Dwarf_Off cu_die_offset_prev, Dwarf_Die cu_die )
{
    int dres = 0;
    Dwarf_Off cuhdroff = 0;
    Dwarf_Off cudieoff3 = 0;
    Dwarf_Error checking_err = 0;
    dres = dwarf_get_arange_cu_header_offset(
        arange_buf[i],&cuhdroff,&checking_err);
    if (dres == DW_DLV_OK) {
        Dwarf_Off cudieoff2 = 0;

        /* Get the CU offset for easy error reporting */
        if (first_cu || cu_die_offset != cu_die_offset_prev) {
            cu_die_offset_prev = cu_die_offset;
            dres = dwarf_die_offsets(cu_die,&DIE_overall_offset,
                &DIE_offset,&checking_err);
            DIE_CU_overall_offset = DIE_overall_offset;
            DIE_CU_offset = DIE_offset;
            if (dres != DW_DLV_OK) {
                print_error(dbg, "dwarf_die_offsets", dres, checking_err);
            }
        }
        dres = dwarf_get_cu_die_offset_given_cu_header_offset(
            dbg,cuhdroff,&cudieoff2,&checking_err);
        if (dres == DW_DLV_OK) {
            /* Get the CU offset for easy error reporting */
            dwarf_die_offsets(cu_die,&DIE_overall_offset,&DIE_offset,&checking_err);
            DIE_CU_overall_offset = DIE_overall_offset;
            DIE_CU_offset = DIE_offset;
            DWARF_CHECK_COUNT(aranges_result,1);
            if (cudieoff2 != cu_die_offset) {
                printf("Error, cu_die offsets mismatch,  0x%"
                    DW_PR_DUx
                    " != 0x%" DW_PR_DUx " from arange data",
                    cu_die_offset,cudieoff2);
                DWARF_CHECK_ERROR(aranges_result,
                    " dwarf_get_cu_die_offset_given_cu..."
                    " gets wrong offset");
            }
        } else {
            print_error(dbg, "dwarf_get_cu_die_offset_given...", dres, checking_err);
        }
    } else {
        print_error(dbg, "dwarf_get_arange_cu_header_offset", dres, checking_err);
    }
    dres = dwarf_get_cu_die_offset(arange_buf[i],&cudieoff3,
        &checking_err);
    if (dres == DW_DLV_OK) {
        DWARF_CHECK_COUNT(aranges_result,1);
        if (cudieoff3 != cu_die_offset) {
            printf(
                "Error, cu_die offsets (b) mismatch ,  0x%"
                DW_PR_DUx
                " != 0x%" DW_PR_DUx " from arange data",
                cu_die_offset,cudieoff3);
            DWARF_CHECK_ERROR(aranges_result,
                " dwarf_get_cu_die_offset "
                " gets wrong offset");
        }
    } else {
        print_error(dbg, "dwarf_get_cu_die_offset failed ",
            dres,checking_err);
    }
}
コード例 #16
0
ファイル: client.c プロジェクト: makalaaneesh/3-2
int main(){
	sfd = socket(AF_INET, SOCK_STREAM, 0);
	print_error(sfd, "error opening socket");

	//setting resuseaddr so that we don't have to constantly wait to the socket to timeout out of it's TIMEWAIT state.
	int set = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int));
コード例 #17
0
int
main_v1_2(char version)
{
	char *nameOfFunction = "Tspi_Key_CreateKey-trans01";
	TSS_HCONTEXT hContext;
	TSS_HTPM hTPM;
	TSS_FLAG initFlags;
	TSS_HKEY hKey, hWrappingKey, hSigningKey;
	TSS_HKEY hSRK;
	TSS_RESULT result;
	TSS_HPOLICY srkUsagePolicy, keyUsagePolicy;


	initFlags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 |
	    TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION |
	    TSS_KEY_NOT_MIGRATABLE;

	print_begin_test(nameOfFunction);

	result = connect_load_all(&hContext, &hSRK, &hTPM);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Create ", result);
		exit(result);
	}

	result = Testsuite_Transport_Init(hContext, hSRK, hTPM, TRUE, FALSE, &hWrappingKey,
					  &hSigningKey);
	if (result != TSS_SUCCESS) {
		print_error("Testsuite_Transport_Init", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Create Object
	result =
	    Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY,
				      initFlags, &hKey);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CreateObject", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Create Policy Object
	result =
	    Tspi_Context_CreateObject(hContext, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE,
				      &keyUsagePolicy);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_CreateObject", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Set Secret
	result =
	    Tspi_Policy_SetSecret(keyUsagePolicy,
				  TESTSUITE_KEY_SECRET_MODE,
				  TESTSUITE_KEY_SECRET_LEN,
				  TESTSUITE_KEY_SECRET);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Policy_SetSecret", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Assign policy to key
	result = Tspi_Policy_AssignToObject(keyUsagePolicy, hKey);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Policy_AssignToObject", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}
	//Create Key
	result = Tspi_Key_CreateKey(hKey, hSRK, 0);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Policy_AssignToObject", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	result = Testsuite_Transport_Final(hContext, hSigningKey);
	if (result != TSS_SUCCESS) {
		if (!checkNonAPI(result)) {
			print_error(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		} else {
			print_error_nonapi(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	} else {
		print_success(nameOfFunction, result);
		print_end_test(nameOfFunction);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(0);
	}
}
コード例 #18
0
ファイル: barber.c プロジェクト: WiktorJ/Operating-Systems
int main(int argc, char **argv){
    if(argc != 4){
        printf("usage: ./barber <number of clients> <number of waiting room seats> <number of hair cuts per client>");
        exit(EXIT_FAILURE);
    }

    number_of_clients = atoi(argv[1]);
    number_of_seats = atoi(argv[2]);
    number_of_cuts = atoi(argv[3]);
    number_of_free_seats = number_of_seats;
    number_of_out_of_salon_seats = number_of_clients;

    if( (pthread_mutex_init(&draw_out, NULL)) !=0 )
        print_error_exit(errno, "error in pthread_mutex_init");

    sem_init(&barber_ready, 0, 0);
    sem_init(&access_waiting_room_seats, 0, 1);
    sem_init(&customer_ready, 0, 0);

    int i;
    int r_id[number_of_clients];
    for(i = 0; i < number_of_clients; i++){
        r_id[i]=i;
    }

    haircut_salon= malloc(sizeof(struct bench));
    haircut_chairs = malloc(sizeof(struct coordinates) * 2);
    haircut_colors = malloc(sizeof(int) * 2);
    haircut_labels = malloc(sizeof(struct label) * 2);

    barber_room= malloc(sizeof(struct bench));
    barber_chairs = malloc(sizeof(struct coordinates));
    barber_colors = malloc(sizeof(int));
    barber_labels = malloc(sizeof(struct label));

    waiting_room= malloc(sizeof(struct bench));
    waiting_chairs = malloc(sizeof(struct coordinates) * number_of_seats);
    waiting_colors = malloc(sizeof(int) * number_of_seats);
    waiting_labels = malloc(sizeof(struct label) * number_of_seats);

    out_of_salon_room= malloc(sizeof(struct bench));
    out_of_salon_chairs = malloc(sizeof(struct coordinates) * number_of_out_of_salon_seats);
    out_of_salon_colors = malloc(sizeof(int) * number_of_out_of_salon_seats);
    out_of_salon_labels = malloc(sizeof(struct label) * number_of_out_of_salon_seats);

    for(i = 0; i < 2; i++){
        haircut_colors[i] = 6;
        haircut_labels[i].label = malloc(sizeof(char)* MAX_LABEL_SIZE);
        haircut_labels[i].label = " ";
    }

        barber_colors[0] = 6;
        barber_labels[0].label = malloc(sizeof(char)* MAX_LABEL_SIZE);
        barber_labels[0].label = " ";


    for(i = 0; i < number_of_seats; i++){
        waiting_colors[i] = 6;
        waiting_labels[i].label = malloc(sizeof(char)* MAX_LABEL_SIZE);
        waiting_labels[i].label = " ";
    }

    for(i = 0; i < number_of_out_of_salon_seats; i++){
        out_of_salon_colors[i] = 6;
        out_of_salon_labels[i].label = malloc(sizeof(char)* MAX_LABEL_SIZE);
        out_of_salon_labels[i].label = " ";
    }

    draw_bench(haircut_salon, LEFT, MIDDLE, HORIZONTAL, 2, haircut_chairs, "HAIRCUT SALON", haircut_labels);
    draw_bench(barber_room, LEFT, UP, HORIZONTAL, 1, barber_chairs, "BARBER CHAIR", barber_labels);
    draw_bench(waiting_room, LEFT, BOTTOM, HORIZONTAL, number_of_seats, waiting_chairs, "WAITING ROOM", waiting_labels);
    draw_bench(out_of_salon_room, RIGHT, UP, VERTICAL, number_of_out_of_salon_seats, out_of_salon_chairs, "OUT OF SALON", out_of_salon_labels);

    clients = malloc(sizeof(pthread_t) *number_of_clients);

    for(i = 0; i < number_of_clients; i++){
        if(pthread_create(&clients[i], NULL, client_thread, r_id + i) == -1)
            print_error(errno, "pthread_create error");
    }

    if(pthread_create(&barber, NULL, barber_thread, r_id) == -1)
        print_error(errno, "pthread_create error");


    for(i = 0; i < number_of_clients; i++){
        if(pthread_join(clients[i], NULL) == -1)
            print_error(errno, "error in pthread_join");
    }
    if(pthread_join(barber, NULL) == -1)
        print_error(errno, "error in pthread_join");

    return 0;
}
コード例 #19
0
int
main_v1_1(void){

	char		*nameOfFunction = "Tspi_Context_CloseObject04";
	TSS_HCONTEXT	hContext;
	TSS_HKEY	hSignatureKey;
	TSS_HTPM	hTPM;
	TSS_RESULT	connectResult;
	TSS_RESULT	result;
	TSS_HCONTEXT	hWrongContext;
	TSS_HKEY	hWrongSignatureKey;

	print_begin_test(nameOfFunction);
	
		//Create Wrong Context
	result = Tspi_Context_Create(&hWrongContext);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Create ", result);
		exit(result);
	}
		//Connect Wrong Context
	result = Tspi_Context_Connect(hWrongContext, get_server(GLOBALSERVER));
	if(result != TSS_SUCCESS){
		print_error("Tspi_Context_Connect ", result);
		Tspi_Context_Close(hWrongContext);
		exit(result);
	}
		//Create Context
	result = Tspi_Context_Create(&hContext);
	if (result != TSS_SUCCESS) {
		print_error("Tspi_Context_Create ", result);
		Tspi_Context_Close(hWrongContext);
		exit(result);
	}
		//Connect Context
	result = Tspi_Context_Connect(hContext, get_server(GLOBALSERVER));
	if(result != TSS_SUCCESS){
		print_error("Tspi_Context_Connect ", result);
		Tspi_Context_Close(hContext);
		Tspi_Context_Close(hWrongContext);
		exit(result);
	}
		//Create Wrong Object
	result = Tspi_Context_CreateObject(hWrongContext,
			TSS_OBJECT_TYPE_RSAKEY,TSS_KEY_SIZE_2048 
			| TSS_KEY_TYPE_SIGNING | TSS_KEY_MIGRATABLE,
			&hWrongSignatureKey);
	if(result != TSS_SUCCESS){
		print_error("Tspi_Context_CreateObject ", result);
		Tspi_Context_Close(hContext);
		Tspi_Context_Close(hWrongContext);
		exit(result);
	}
		//Create Correct Object
	result = Tspi_Context_CreateObject(hContext, 
			TSS_OBJECT_TYPE_RSAKEY,TSS_KEY_SIZE_2048 
			| TSS_KEY_TYPE_SIGNING | TSS_KEY_MIGRATABLE,
			&hSignatureKey);
	if(result != TSS_SUCCESS){
		print_error("Tspi_Context_CreateObject ", result);
		Tspi_Context_Close(hContext);
		Tspi_Context_Close(hWrongContext);
		result = Tspi_Context_CloseObject(hWrongContext, hWrongSignatureKey);
		exit(result);
	}
		//Close Object
	result = Tspi_Context_CloseObject(hContext, hWrongSignatureKey);
	if (TSS_ERROR_CODE(result) != TSS_E_INVALID_HANDLE) {
		if(!checkNonAPI(result)){
			print_error(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_FreeMemory(hContext, NULL);
			Tspi_Context_CloseObject(hContext, hSignatureKey);
			Tspi_Context_CloseObject(hWrongContext, hWrongSignatureKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
		else{
			print_error_nonapi(nameOfFunction, result);
			print_end_test(nameOfFunction);
			Tspi_Context_FreeMemory(hContext, NULL);
			Tspi_Context_CloseObject(hWrongContext, hWrongSignatureKey);
			Tspi_Context_CloseObject(hContext, hSignatureKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	}
	else{
		print_success(nameOfFunction, result);
		print_end_test(nameOfFunction);
		Tspi_Context_FreeMemory(hContext, NULL);
		Tspi_Context_CloseObject(hWrongContext, hWrongSignatureKey);
		Tspi_Context_CloseObject(hContext, hSignatureKey);
		Tspi_Context_Close(hContext);
		exit(0);
	}
}
コード例 #20
0
ファイル: dsa.c プロジェクト: skrieder/oops
ErrorCode init_dsa(const char* cfg)
{
    ErrorCode error = NO_ERROR;
    char *linehead = NULL;
    char *energyname = NULL;
    char *energycfg = NULL;
    char *rbasinsname = NULL;
    char *rbasinscfg = NULL;

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

    if (open_input_text_file(cfg) == NO_ERROR)
    {
        while (read_input_line())
        {
            get_input_strval(&linehead, "=", 0);
            if (strcmp(linehead, "ENERGY FUNCTION") == 0)
            {
                get_input_strval(&energyname, "=", 1);
            }
            else if (strcmp(linehead, "ENERGY CONFIG") == 0)
            {
                get_input_strval(&energycfg, "=", 1);
            }
            else if (strcmp(linehead, "RB CALCULATOR") == 0)
            {
                get_input_strval(&rbasinsname, "=", 1);
            }
            else if (strcmp(linehead, "RB CONFIG") == 0)
            {
                get_input_strval(&rbasinscfg, "=", 1);
            }
            else
            {
                print_error(UNKNOWN_PARAMETER_ERROR, "init_oops", 2, "header ", linehead);
            }
            free(linehead); 
            linehead = NULL; // Make sure of set this string pointer to NULL, beacause it will be used again when reading the next line. 
        }
        close_input_file();    
    }

    error = get_energy_module(&energymod, energyname);
    if (error != NO_ERROR)
    {
        print_error(error, "init_dsa", 1, " when getting energy module");
    }
    free(energyname);

    error = get_custom_module(&rbasinsmod, rbasinsname);
    if (error != NO_ERROR)
    {
        print_error(error, "init_dsa", 1, " when getting rbasins module");
    }
    free(rbasinsname);

    // Initializing energy module.
    execute_init_func_energy_module(energymod, energycfg);
    free(energycfg);

    // Initializing rbasins module.
    execute_init_func_custom_module(rbasinsmod, rbasinscfg);
    free(rbasinscfg);

    // Calculating initial assignement of torsional angles for the whole system.
    update_all_torsional_angles(residues, chains, nchains, coords);

    // Initializing global variables..
    T = 350.0;
    create_bool_array(&flags, nres);

    printf("    Done.\n");

    return error;
}
コード例 #21
0
int ispv1_get_resource(void)
{
	struct clk *clk = NULL;
	struct resource *res = NULL;
	int ret = 0;
    struct device *dev = NULL;
    struct device_node *np = NULL;
    struct platform_device *pdev =NULL;
     
	print_debug("%s", __func__);

    
    np = of_find_compatible_node(NULL, NULL, "hisi,hisi_csi");
	if (np ==NULL)
	{
		print_error("the device node hisi_csi is null\n");
		return -1;
	}
	pdev=of_find_device_by_node(np);
	if (pdev ==NULL)
	{
		print_error("the device  hisi_csi is null\n");
		return -1;
	}
    dev=  &pdev->dev;
	/* get reg base */

    /* Modified  by w00199382 for isp 2.2 , 2012/11/22, begin */

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (res == NULL) {
		print_error("failed to get io men resource");
		ret = -ENXIO;
		goto fail;
	}


    /*FIXME: BSP has not support the interface IO_ADDRESS*/

	ispv1_io.csi0_base = ioremap(res->start, resource_size(res));
	if (!ispv1_io.csi0_base) {
               print_error("failed to get ispv1_io.csi0_base)");
		return -ENOMEM;
	}
    ispv1_io.csi1_base = ispv1_io.csi0_base + CSI1_REG_OFFSET;
    /* Modified  by w00199382 for isp 2.2 , 2012/11/22, end */

	register_cam_dbg_info(DBG_INFO_CSI0_BASE, (void *)ispv1_io.csi0_base);
	register_cam_dbg_info(DBG_INFO_CSI1_BASE, (void *)ispv1_io.csi1_base);

	/* get irq resource */
#ifdef REG_CSI_IRQ
	res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);

	if (res == NULL) {
		print_error("failed to get irq: csi0_irq");
		ret = -ENXIO;
		goto fail;
	}

	ispv1_io.csi0_irq = res->start;

	res = platform_get_resource(pdev, IORESOURCE_IRQ, 1);

	if (res == NULL) {
		print_error("failed to get irq: csi1_irq");
		ret = -ENXIO;
		goto fail;
	}

	ispv1_io.csi1_irq = res->start;
#endif
	/* get clk
	clk = clk_get(dev, "clk_ispmipi");
	if (IS_ERR_OR_NULL(clk)) {
		print_error("failed to get isp clock");
		ret = -ENXIO;
		goto fail;

	}
	ispv1_io.csi_clk = clk;*/

	clk = clk_get(dev, "CLK_CFG_CSI4PHY");
	if (IS_ERR_OR_NULL(clk)) {
		print_error("failed to get csi0 controller clock");
		ret = -ENXIO;
		goto fail;
	}
	ispv1_io.csi0_clk= clk;

	clk = clk_get(dev, "CLK_CFG_CSI2PHY");
	if (IS_ERR_OR_NULL(clk)) {
		print_error("failed to get csi2 controller clock");
		ret = -ENXIO;
		goto fail;
	}
	ispv1_io.csi2_clk= clk;



#ifdef REG_CSI_IRQ
	print_info("request csi0 & csi1 irq");
	ret = request_irq(ispv1_io.csi0_irq, k3_csi0_isr, 0, "csi0_irq", 0);

	if (ret != 0) {
		print_error("fail to request irq [%d]", res->start);
		goto fail;
	}

	ret = request_irq(ispv1_io.csi1_irq, k3_csi1_isr, 0, "csi1_irq", 0);

	if (ret != 0) {
		print_error("fail to request irq [%d]", res->start);
		goto fail;
	}
#endif

	print_debug("exit %s, csi0_base[%#x]", __func__, ispv1_io.csi0_base);

	return 0;

fail:
#ifdef REG_CSI_IRQ
	if (ispv1_io.csi0_irq) {
		free_irq(ispv1_io.csi0_irq, 0);
	}

	if (ispv1_io.csi1_irq) {
		free_irq(ispv1_io.csi1_irq, 0);
	}
#endif

	/*if (ispv1_io.csi_clk) {
		clk_put(ispv1_io.csi_clk);
		ispv1_io.csi_clk = NULL;
	}*/

	if (ispv1_io.csi0_clk) {
		clk_put(ispv1_io.csi0_clk);
		ispv1_io.csi0_clk = NULL;
	}

	if (ispv1_io.csi2_clk) {
		clk_put(ispv1_io.csi2_clk);
		ispv1_io.csi2_clk = NULL;
	}



	return ret;
}
コード例 #22
0
ファイル: print_abbrevs.c プロジェクト: finik/libdwarf
/* Calculate the number of abbreviations for the
   current CU and set up basic abbreviations array info,
   storing the number of attributes per abbreviation
*/
void
get_abbrev_array_info(Dwarf_Debug dbg, Dwarf_Unsigned offset_in)
{
    Dwarf_Unsigned offset = offset_in;
    if (check_abbreviations) {
        Dwarf_Abbrev ab = 0;
        Dwarf_Unsigned length = 0;
        Dwarf_Unsigned abbrev_entry_count = 0;
        Dwarf_Unsigned abbrev_code;
        int abres = DW_DLV_OK;
        Dwarf_Error aberr = 0;
        Dwarf_Unsigned last_abbrev_code = 0;

        Dwarf_Bool bMore = TRUE;
        Dwarf_Unsigned CU_abbrev_count = 0;

        if (abbrev_array == NULL) {
            /* Allocate initial abbreviation array info */
            abbrev_array_size = ABBREV_ARRAY_INITIAL_SIZE;
            abbrev_array = (Dwarf_Unsigned *)
                calloc(abbrev_array_size,sizeof(Dwarf_Unsigned));
        } else {
            /* Clear out values from previous CU */
            memset((void *)abbrev_array,0,
                (abbrev_array_size) * sizeof(Dwarf_Unsigned));
        }

        while (bMore && (abres = dwarf_get_abbrev(dbg, offset, &ab,
            &length, &abbrev_entry_count,
            &aberr)) == DW_DLV_OK) {
            dwarf_get_abbrev_code(ab,&abbrev_code,&aberr);
            if (abbrev_code == 0) {
                /* End of abbreviation table for this CU */
                ++offset; /* Skip abbreviation code */
                bMore = FALSE;
            } else {
                /* Valid abbreviation code. We hope. */
                if (abbrev_code > 0) {
                    check_abbrev_num_sequence(abbrev_code,last_abbrev_code,
                        abbrev_array_size,abbrev_entry_count,CU_abbrev_count);
                    while (abbrev_code >= abbrev_array_size) {
                        Dwarf_Unsigned old_size = abbrev_array_size;
                        size_t addl_size_bytes = old_size *
                            sizeof(Dwarf_Unsigned);

                        /*  Resize abbreviation array.
                            Only a bogus abbreviation number will iterate
                            more than once, and it will be caught later.
                            Or we will run out of memory! */
                        abbrev_array_size *= 2;
                        abbrev_array = (Dwarf_Unsigned *)
                            realloc(abbrev_array,
                            abbrev_array_size * sizeof(Dwarf_Unsigned));
                        /* Zero out the new bytes. */
                        memset(abbrev_array + old_size,0,addl_size_bytes);
                    }
                    check_reused_code(abbrev_code, abbrev_entry_count);
                    abbrev_array[abbrev_code] = abbrev_entry_count;
                    ++CU_abbrev_count;
                    offset += length;
                } else {
                    /* Invalid abbreviation code */
                    print_error(dbg, "get_abbrev_array_info", abres, aberr);
                }
                last_abbrev_code = abbrev_code;
            }
            dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
        }
    }
}
コード例 #23
0
/*
 **************************************************************************
 * FunctionName: ispv1_init_csi;
 * Description : csi init;
 * Input       : mipi_lane_count: lane count 1~8
 * Output      : NA;
 * ReturnValue : NA;
 * Other       : NA;
 **************************************************************************
 */
int ispv1_init_csi(csi_index_t index, csi_lane_t mipi_lane_count, u8 lane_clk)
{
	int ret = 0;
	u32 phy_state1;
	u8 __iomem * reg_base;
	u8 settle_time, value, camera_source;

	ret = ispv1_get_resource();
	if (ret)
		return ret;

	print_info("Enter %s, index[%d], mipi_lane_count[%d]", __func__,
		   index, mipi_lane_count);

    ret = ispv1_csi_poweron(index);

#ifdef DUMP_SCCTRL_ISP_REG
    dump_scctrl_isp_reg();
#endif
    if (ret) {
		print_error("%s: csi power on fail.", __func__);
        return ret;
    }

    if (index == CSI_INDEX_0) {
        reg_base = ispv1_io.csi0_base;
    } else {
        reg_base = ispv1_io.csi1_base;
    }

	CSI_SETREG32(reg_base + CSI_REG_PHY_SHUTDOWNZ, 0);
	CSI_SETREG32(reg_base + CSI_REG_DPHY_RSTZ, 0);
	CSI_SETREG32(reg_base + CSI_REG_RESETN, 0);

	CSI_SETREG32(reg_base + PHY_TST_CONTRL0, 1);
	CSI_SETREG32(reg_base + PHY_TST_CONTRL0, 0);

	msleep(1);
	
	CSI_SETREG32(reg_base + CSI_REG_PHY_SHUTDOWNZ, 1);
	CSI_SETREG32(reg_base + CSI_REG_N_LANES, (u32) mipi_lane_count);

	/*msleep(10); */

	settle_time = lane_clk;
	camera_source = 1;

	CSI_SETREG32(reg_base + CSI_REG_DPHY_RSTZ, 1);
	CSI_SETREG32(reg_base + CSI_REG_RESETN, 1);

	CSI_SETPHYREG8(reg_base, 0x10, settle_time);
	CSI_GETPHYREG8(reg_base, 0x10, value);
	
	print_info("reg 0x10 = %d", value);
	
	CSI_SETPHYREG8(reg_base, 0x11, camera_source);
	CSI_GETPHYREG8(reg_base, 0x11, value);

	print_info("reg 0x11 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x20, settle_time);
	CSI_GETPHYREG8(reg_base, 0x20, value);

	print_info("reg 0x20 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x21, camera_source);
	CSI_GETPHYREG8(reg_base, 0x21, value);

	print_info("reg 0x21 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x30, settle_time);
	CSI_GETPHYREG8(reg_base, 0x30, value);

	print_info("reg 0x30 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x31, camera_source);
	CSI_GETPHYREG8(reg_base, 0x31, value);

	print_info("reg 0x31 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x40, settle_time);
	CSI_GETPHYREG8(reg_base, 0x40, value);

	print_info("reg 0x40 = %d", value);

	CSI_SETPHYREG8(reg_base, 0x41, camera_source);
	CSI_GETPHYREG8(reg_base, 0x41, value);

	print_info("reg 0x41 = %d", value);

	/*
	   csi-2 Controller programming - Read the PHY status register (PHY_STATE) to confirm that all data
	   and clock lanes of the D-PHY are in Stop State (that is, ready to receive data).
	 */

	/*
	   Configure the MIPI Camera Sensor - Access Camera Sensor using CCI interface to initialize and
	   configure the Camera Sensor to start transmitting a clock on the D-PHY clock lane.
	 */

	/*
	   csi-2 Controller programming - Read the PHY status register (PHY_STATE) to confirm that the
	   D-PHY is receiving a clock on the D-PHY clock lane.
	 */
	phy_state1 = CSI_GETREG32(reg_base + CSI_REG_PHY_STATE);

	if (0 == (phy_state1 & PHY_STATE_STOPSTATE0)
	    && 0 == (phy_state1 & PHY_STATE_STOPSTATECLK)) {
		print_info("Not all data and clock lanes of the D-PHY are in Stop State, "
			"phy_state1 : %#x ", phy_state1);
	}

	if (0 == (phy_state1 & PHY_STATE_RXCLKACTIVEHS))
		print_info("D-PHY was not receive a clock \n");

	/*enable all interrupt */
	CSI_SETREG32(reg_base + CSI_REG_MASK1, CSI_INT_EN);	/* TBD 0x0f00f000 except err_l_seq_di err_frame_data_vc */
	CSI_SETREG32(reg_base + CSI_REG_MASK2, CSI_INT_EN);

	return 0;
}
コード例 #24
0
ファイル: print_abbrevs.c プロジェクト: finik/libdwarf
/* Print data in .debug_abbrev
   This is inherently unsafe as it assumes there
   are no byte sequences in .debug_abbrev other than
   legal abbrev sequences.  But the Dwarf spec
   does not promise that. The spec only promises
   that any bytes at an offset referred to from
   .debug_info are legal sequences.
*/
extern void
print_abbrevs(Dwarf_Debug dbg)
{
    Dwarf_Abbrev ab;
    Dwarf_Unsigned offset = 0;
    Dwarf_Unsigned length = 0;
    Dwarf_Unsigned abbrev_entry_count = 0;
    /* Maximum defined tag is 0xffff, DW_TAG_hi_user. */
    Dwarf_Half tag = 0;
    Dwarf_Half attr = 0;
    Dwarf_Signed form = 0;
    Dwarf_Off off = 0;
    Dwarf_Unsigned i = 0;
    Dwarf_Unsigned abbrev_num = 1;
    Dwarf_Signed child_flag = 0;
    int abres = 0;
    int tres = 0;
    int acres = 0;
    Dwarf_Unsigned abbrev_code = 0;
    Dwarf_Error paerr = 0;

    current_section_id = DEBUG_ABBREV;

    if (do_print_dwarf) {
        printf("\n.debug_abbrev\n");
    }
    while ((abres = dwarf_get_abbrev(dbg, offset, &ab,
        &length, &abbrev_entry_count, &paerr)) == DW_DLV_OK) {
        const char *tagname = "";

        /*  Here offset is the global offset in .debug_abbrev.
            The abbrev_num is a relatively worthless counter
            of all abbreviations.  */
        tres = dwarf_get_abbrev_tag(ab, &tag, &paerr);
        if (tres != DW_DLV_OK) {
            dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
            print_error(dbg, "dwarf_get_abbrev_tag", tres, paerr);
        }
        tres = dwarf_get_abbrev_code(ab, &abbrev_code, &paerr);
        if (tres != DW_DLV_OK) {
            dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
            print_error(dbg, "dwarf_get_abbrev_code", tres, paerr);
        }
        tagname = get_TAG_name(tag,dwarf_names_print_on_error);
        if (!tag) {
            tagname = "Abbrev 0: null abbrev entry";
        }
        if (dense) {
            printf("<%" DW_PR_DUu "><0x%" DW_PR_XZEROS  DW_PR_DUx
                "><code: %" DW_PR_DUu ">",
                abbrev_num, offset,abbrev_code);
            if (verbose) {
                printf("<length: 0x%" DW_PR_XZEROS  DW_PR_DUx ">",
                    length);
            }
            printf(" %s", tagname);
        }
        else {
            printf("<%5" DW_PR_DUu "><0x%" DW_PR_XZEROS DW_PR_DUx
                "><code: %3" DW_PR_DUu ">",
                abbrev_num, offset, abbrev_code);
            if (verbose) {
                printf("<length: 0x%" DW_PR_XZEROS  DW_PR_DUx ">",
                    length);
            }
            printf(" %-27s", tagname);
        }
        /* Process specific TAGs specially. */
        tag_specific_checks_setup(tag,0);
        ++abbrev_num;
        acres = dwarf_get_abbrev_children_flag(ab, &child_flag, &paerr);
        if (acres == DW_DLV_ERROR) {
            dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
            print_error(dbg, "dwarf_get_abbrev_children_flag", acres,
                paerr);
        }
        if (acres == DW_DLV_NO_ENTRY) {
            child_flag = 0;
        }
        /*  If tag is zero, it is a null byte, not a real abbreviation,
            so there is no 'children' flag to print.  */
        if (tag) {
            const char * child_name = 0;

            child_name = get_children_name(child_flag,
                dwarf_names_print_on_error);
            printf(" %s", child_name);
        }
        if(!dense) {
            printf("\n");
        }
        /*  Abbrev just contains the format of a die, which debug_info
            then points to with the real data. So here we just print the
            given format. */
        for (i = 0; i < abbrev_entry_count; i++) {
            int aeres = 0;

            aeres =
                dwarf_get_abbrev_entry(ab, i, &attr, &form, &off, &paerr);
            if (aeres == DW_DLV_ERROR) {
                dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
                print_error(dbg, "dwarf_get_abbrev_entry", aeres, paerr);
            }
            if (aeres == DW_DLV_NO_ENTRY) {
                attr = -1LL;
                form = -1LL;
            }
            if (dense) {
                printf(" <%ld>%s<%s>", (unsigned long) off,
                    get_AT_name(attr,dwarf_names_print_on_error),
                    get_FORM_name((Dwarf_Half) form,
                        dwarf_names_print_on_error));
            } else {
                printf("       <0x%08lx>              %-28s%s\n",
                    (unsigned long) off,
                    get_AT_name(attr,
                        dwarf_names_print_on_error),
                    get_FORM_name((Dwarf_Half) form,
                        dwarf_names_print_on_error));
            }
        }
        dwarf_dealloc(dbg, ab, DW_DLA_ABBREV);
        offset += length;
        if (dense) {
            printf("\n");
        }
    }
    if (abres == DW_DLV_ERROR) {
        print_error(dbg, "dwarf_get_abbrev", abres, paerr);
    }
}
コード例 #25
0
ParseNode gen_paramtable(ParseNode & paramtable_elem, ParseNode & paramtable) {
	ParseNode newnode = ParseNode(gen_flex(Term{ TokenMeta::NT_PARAMTABLE, "" }), nullptr);
	bool dimen1 = false, dimen2 = false, arg1 = false, arg2 = false, va1 = false, va2 = false;;
	if (paramtable_elem.fs.CurrentTerm.token == TokenMeta::NT_DIMENSLICE) {
		dimen1 = true;
	}
	if (paramtable_elem.fs.CurrentTerm.token == TokenMeta::NT_ARGTABLE_PURE) {
		arg1 = true;
	}
	if (TokenMeta::iselement(paramtable_elem.fs.CurrentTerm.token)) {
		va1 = true;
	}
	if (paramtable.fs.CurrentTerm.token == TokenMeta::NT_PARAMTABLE_DIMENSLICE) {
		dimen2 = true;
	}
	if (paramtable.fs.CurrentTerm.token == TokenMeta::NT_ARGTABLE_PURE) {
		arg2 = true;
	}
	if (TokenMeta::iselement(paramtable.fs.CurrentTerm.token)) {
		va2 = true;
	}
	if (paramtable_elem.fs.CurrentTerm.token == TokenMeta::NT_KEYVALUE && paramtable.fs.CurrentTerm.token == TokenMeta::NT_PARAMTABLE) {
		// all keyvalue pair 
		newnode = gen_flattern(paramtable_elem, paramtable, "%s, %s", TokenMeta::NT_PARAMTABLE);
	}
	else if(paramtable.fs.CurrentTerm.token == TokenMeta::NT_PARAMTABLE){
		// there is keyvalue pair
		// this is possible because of rule `dimen_slice : exp ',' paramtable `
		// there is keyvalue
		if (dimen1) {
			// promote dimen_slice to paramtable
			for (int i = 0; i < paramtable_elem.child.size(); i++)
			{
				newnode.addchild(new ParseNode(*paramtable_elem.child[i]));
			}
		}
		else {
			// do not promote exp to keyvalue
			// TODO
			newnode.addchild(new ParseNode(paramtable_elem));
		}
		// assume paramtable is flatterned
		for (int i = 0; i < paramtable.child.size(); i++)
		{
			newnode.addchild(new ParseNode(*paramtable.child[i]));
		}
		sprintf(codegen_buf, "%s, %s", paramtable_elem.fs.CurrentTerm.what.c_str(), paramtable.fs.CurrentTerm.what.c_str());
		newnode.fs.CurrentTerm.what = string(codegen_buf);
	}
	else if ((dimen1 || arg1 || va1) && (dimen2 || arg2 || va2)) {
		// all dimen_slice or argument_pure or variable
		newnode = ParseNode(gen_flex(Term{ (dimen1 || dimen2) ? TokenMeta::NT_PARAMTABLE_DIMENSLICE : TokenMeta::NT_ARGTABLE_PURE, "" }), nullptr);
		if (dimen1 || arg1) {
			for (int i = 0; i < paramtable_elem.child.size(); i++)
			{
				newnode.addchild(new ParseNode(*paramtable_elem.child[i]));
			}
		}
		else {
			newnode.addchild(new ParseNode(paramtable_elem));
		}
		// assume paramtable is flatterned
		if (dimen2 || arg2) {
			for (int i = 0; i < paramtable.child.size(); i++)
			{
				newnode.addchild(new ParseNode(*paramtable.child[i]));
			}
		}
		else {
			newnode.addchild(new ParseNode(paramtable));
		}
		sprintf(codegen_buf, "%s, %s", paramtable_elem.fs.CurrentTerm.what.c_str(), paramtable.fs.CurrentTerm.what.c_str());
		newnode.fs.CurrentTerm.what = string(codegen_buf);
	}
	else {
		print_error("bad param table");
	}
	return newnode;
}
コード例 #26
0
ファイル: check.c プロジェクト: bygreencn/flvmeta
/* check FLV file validity */
int check_flv_file(const flvmeta_opts * opts) {
    flv_stream * flv_in;
    flv_header header;
    int errors, warnings;
    int result;
    char message[256];
    uint32 prev_tag_size, tag_number;
    uint32 last_timestamp, last_video_timestamp, last_audio_timestamp;
    struct stat file_stats;
    int have_audio, have_video;
    flvmeta_opts opts_loc;
    flv_info info;
    int have_desync;
    int have_on_metadata;
    file_offset_t on_metadata_offset;
    amf_data * on_metadata;
    int have_on_last_second;
    uint32 on_last_second_timestamp;

    int have_prev_audio_tag;
    flv_audio_tag prev_audio_tag;
    int have_prev_video_tag;
    flv_video_tag prev_video_tag;

    int video_frames_number, keyframes_number;

    prev_audio_tag = 0;
    prev_video_tag = 0;
    
    have_audio = have_video = 0;
    tag_number = 0;
    last_timestamp = last_video_timestamp = last_audio_timestamp = 0;
    have_desync = 0;
    have_prev_audio_tag = have_prev_video_tag = 0;
    video_frames_number = keyframes_number = 0;
    have_on_metadata = 0;
    on_metadata_offset = 0;
    on_metadata = NULL;
    have_on_last_second = 0;
    on_last_second_timestamp = 0;

    /* file stats */
    if (stat(opts->input_file, &file_stats) != 0) {
        return ERROR_OPEN_READ;
    }

    /* open file for reading */
    flv_in = flv_open(opts->input_file);
    if (flv_in == NULL) {
        return ERROR_OPEN_READ;
    }
    
    errors = warnings = 0;

    report_start(opts);

    /** check header **/

    /* check signature */
    result = flv_read_header(flv_in, &header);
    if (result == FLV_ERROR_EOF) {
        print_fatal("F11001", 0, "unexpected end of file in header");
        goto end;
    }
    else if (result == FLV_ERROR_NO_FLV) {
        print_fatal("F11002", 0, "FLV signature not found in header");
        goto end;
    }

    /* version */
    if (header.version != FLV_VERSION) {
        sprintf(message, "header version should be 1, %d found instead", header.version);
        print_error("E11003", 3, message);
    }

    /* video and audio flags */
    if (!flv_header_has_audio(header) && !flv_header_has_video(header)) {
        print_error("E11004", 4, "header signals the file does not contain video tags or audio tags");
    }
    else if (!flv_header_has_audio(header)) {
        print_info("I11005", 4, "header signals the file does not contain audio tags");
    }
    else if (!flv_header_has_video(header)) {
        print_warning("W11006", 4, "header signals the file does not contain video tags");
    }

    /* reserved flags */
    if (header.flags & 0xFA) {
        print_error("E11007", 4, "header reserved flags are not zero");
    }

    /* offset */
    if (flv_header_get_offset(header) != 9) {
        sprintf(message, "header offset should be 9, %d found instead", flv_header_get_offset(header));
        print_error("E11008", 5, message);
    }

    /** check first previous tag size **/

    result = flv_read_prev_tag_size(flv_in, &prev_tag_size);
    if (result == FLV_ERROR_EOF) {
        print_fatal("F12009", 9, "unexpected end of file in previous tag size");
        goto end;
    }
    else if (prev_tag_size != 0) {
        sprintf(message, "first previous tag size should be 0, %d found instead", prev_tag_size);
        print_error("E12010", 9, message);
    }

    /* we reached the end of file: no tags in file */
    if (flv_get_offset(flv_in) == file_stats.st_size) {
        print_fatal("F10011", 13, "file does not contain tags");
        goto end;
    }

    /** read tags **/
    while (flv_get_offset(flv_in) < file_stats.st_size) {
        flv_tag tag;
        file_offset_t offset;
        uint32 body_length, timestamp, stream_id;
        int decr_timestamp_signaled;

        result = flv_read_tag(flv_in, &tag);
        if (result != FLV_OK) {
            print_fatal("F20012", flv_get_offset(flv_in), "unexpected end of file in tag");
            goto end;
        }

        ++tag_number;

        offset = flv_get_current_tag_offset(flv_in);
        body_length = flv_tag_get_body_length(tag);
        timestamp = flv_tag_get_timestamp(tag);
        stream_id = flv_tag_get_stream_id(tag);

        /* check tag type */
        if (tag.type != FLV_TAG_TYPE_AUDIO
            && tag.type != FLV_TAG_TYPE_VIDEO
            && tag.type != FLV_TAG_TYPE_META
        ) {
            sprintf(message, "unknown tag type %hhd", tag.type);
            print_error("E30013", offset, message);
        }

        /* check consistency with global header */
        if (!have_video && tag.type == FLV_TAG_TYPE_VIDEO) {
            if (!flv_header_has_video(header)) {
                print_warning("W11014", offset, "video tag found despite header signaling the file contains no video");
            }
            have_video = 1;
        }
        if (!have_audio && tag.type == FLV_TAG_TYPE_AUDIO) {
            if (!flv_header_has_audio(header)) {
                print_warning("W11015", offset, "audio tag found despite header signaling the file contains no audio");
            }
            have_audio = 1;
        }

        /* check body length */
        if (body_length > (file_stats.st_size - flv_get_offset(flv_in))) {
            sprintf(message, "tag body length (%d bytes) exceeds file size", body_length);
            print_fatal("F20016", offset + 1, message);
            goto end;
        }
        else if (body_length > MAX_ACCEPTABLE_TAG_BODY_LENGTH) {
            sprintf(message, "tag body length (%d bytes) is abnormally large", body_length);
            print_warning("W20017", offset + 1, message);
        }
        else if (body_length == 0) {
            print_warning("W20018", offset + 1, "tag body length is zero");
        }

        /** check timestamp **/
        decr_timestamp_signaled = 0;

        /* check whether first timestamp is zero */
        if (tag_number == 1 && timestamp != 0) {
            sprintf(message, "first timestamp should be zero, %d found instead", timestamp);
            print_error("E40019", offset + 4, message);
        }

        /* check whether timestamps decrease in a given stream */
        if (tag.type == FLV_TAG_TYPE_AUDIO) {
            if (last_audio_timestamp > timestamp) {
                sprintf(message, "audio tag timestamps are decreasing from %d to %d", last_audio_timestamp, timestamp);
                print_error("E40020", offset + 4, message);
            }
            last_audio_timestamp = timestamp;
            decr_timestamp_signaled = 1;
        }
        if (tag.type == FLV_TAG_TYPE_VIDEO) {
            if (last_video_timestamp > timestamp) {
                sprintf(message, "video tag timestamps are decreasing from %d to %d", last_video_timestamp, timestamp);
                print_error("E40021", offset + 4, message);
            }
            last_video_timestamp = timestamp;
            decr_timestamp_signaled = 1;
        }

        /* check for overflow error */
        if (last_timestamp > timestamp && last_timestamp - timestamp > 0xF00000) {
            print_error("E40022", offset + 4, "extended bits not used after timestamp overflow");
        }

        /* check whether timestamps decrease globally */
        else if (!decr_timestamp_signaled && last_timestamp > timestamp && last_timestamp - timestamp >= 1000) {
            sprintf(message, "timestamps are decreasing from %d to %d", last_timestamp, timestamp);
            print_error("E40023", offset + 4, message);
        }

        last_timestamp = timestamp;

        /* check for desyncs between audio and video: one second or more is suspicious */
        if (have_video && have_audio && !have_desync && labs(last_video_timestamp - last_audio_timestamp) >= 1000) {
            sprintf(message, "audio and video streams are desynchronized by %ld ms",
                labs(last_video_timestamp - last_audio_timestamp));
            print_warning("W40024", offset + 4, message);
            have_desync = 1; /* do not repeat */
        }

        /** stream id must be zero **/
        if (stream_id != 0) {
            sprintf(message, "tag stream id must be zero, %d found instead", stream_id);
            print_error("E20025", offset + 8, message);
        }

        /* check tag body contents only if not empty */
        if (body_length > 0) {

            /** check audio info **/
            if (tag.type == FLV_TAG_TYPE_AUDIO) {
                flv_audio_tag at;
                uint8_bitmask audio_format;

                result = flv_read_audio_tag(flv_in, &at);
                if (result == FLV_ERROR_EOF) {
                    print_fatal("F20012", offset + 11, "unexpected end of file in tag");
                    goto end;
                }

                /* check whether the format varies between tags */
                if (have_prev_audio_tag && prev_audio_tag != at) {
                    print_warning("W51026", offset + 11, "audio format changed since last tag");
                }

                /* check format */
                audio_format = flv_audio_tag_sound_format(at);
                if (audio_format == 12 || audio_format == 13) {
                    sprintf(message, "unknown audio format %d", audio_format);
                    print_warning("W51027", offset + 11, message);
                }
                else if (audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_G711_A
                    || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_G711_MU
                    || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_RESERVED
                    || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_MP3_8
                    || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_DEVICE_SPECIFIC
                ) {
                    sprintf(message, "audio format %d is reserved for internal use", audio_format);
                    print_warning("W51028", offset + 11, message);
                }

                /* check consistency, see flash video spec */
                if (flv_audio_tag_sound_rate(at) != FLV_AUDIO_TAG_SOUND_RATE_44
                    && audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_AAC
                ) {
                    print_warning("W51029", offset + 11, "audio data in AAC format should have a 44KHz rate, field will be ignored");
                }

                if (flv_audio_tag_sound_type(at) == FLV_AUDIO_TAG_SOUND_TYPE_STEREO
                    && (audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_NELLYMOSER
                        || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_NELLYMOSER_16_MONO
                        || audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_NELLYMOSER_8_MONO)
                ) {
                    print_warning("W51030", offset + 11, "audio data in Nellymoser format cannot be stereo, field will be ignored");
                }

                else if (flv_audio_tag_sound_type(at) == FLV_AUDIO_TAG_SOUND_TYPE_MONO
                    && audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_AAC
                ) {
                    print_warning("W51031", offset + 11, "audio data in AAC format should be stereo, field will be ignored");
                }

                else if (audio_format == FLV_AUDIO_TAG_SOUND_FORMAT_LINEAR_PCM) {
                    print_warning("W51032", offset + 11, "audio data in Linear PCM, platform endian format should not be used because of non-portability");
                }

                prev_audio_tag = at;
                have_prev_audio_tag = 1;
            }
            /** check video info **/
            else if (tag.type == FLV_TAG_TYPE_VIDEO) {
                flv_video_tag vt;
                uint8_bitmask video_frame_type, video_codec;

                video_frames_number++;

                result = flv_read_video_tag(flv_in, &vt);
                if (result == FLV_ERROR_EOF) {
                    print_fatal("F20012", offset + 11, "unexpected end of file in tag");
                    goto end;
                }

                /* check whether the format varies between tags */
                if (have_prev_video_tag && flv_video_tag_codec_id(prev_video_tag) != flv_video_tag_codec_id(vt)) {
                    print_warning("W60033", offset + 11, "video format changed since last tag");
                }

                /* check video frame type */
                video_frame_type = flv_video_tag_frame_type(vt);
                if (video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_KEYFRAME
                    && video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_INTERFRAME
                    && video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_DISPOSABLE_INTERFRAME
                    && video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_GENERATED_KEYFRAME
                    && video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_COMMAND_FRAME
                ) {
                    sprintf(message, "unknown video frame type %d", video_frame_type);
                    print_error("E60034", offset + 11, message);
                }

                if (video_frame_type == FLV_VIDEO_TAG_FRAME_TYPE_KEYFRAME) {
                    keyframes_number++;
                }

                /* check whether first frame is a keyframe */
                if (!have_prev_video_tag && video_frame_type != FLV_VIDEO_TAG_FRAME_TYPE_KEYFRAME) {
                    print_warning("W60035", offset + 11, "first video frame is not a keyframe, playback will suffer");
                }

                /* check video codec */
                video_codec = flv_video_tag_codec_id(vt);
                if (video_codec != FLV_VIDEO_TAG_CODEC_JPEG
                    && video_codec != FLV_VIDEO_TAG_CODEC_SORENSEN_H263
                    && video_codec != FLV_VIDEO_TAG_CODEC_SCREEN_VIDEO
                    && video_codec != FLV_VIDEO_TAG_CODEC_ON2_VP6
                    && video_codec != FLV_VIDEO_TAG_CODEC_ON2_VP6_ALPHA
                    && video_codec != FLV_VIDEO_TAG_CODEC_SCREEN_VIDEO_V2
                    && video_codec != FLV_VIDEO_TAG_CODEC_AVC
                ) {
                    sprintf(message, "unknown video codec id %d", video_codec);
                    print_error("E61034", offset + 11, message);
                }

                /* according to spec, JPEG codec is not currently used */
                if (video_codec == FLV_VIDEO_TAG_CODEC_JPEG) {
                    print_warning("W61035", offset + 11, "JPEG codec not currently used");
                }

                prev_video_tag = vt;
                have_prev_video_tag = 1;
            }
            /** check script data info **/
            else if (tag.type == FLV_TAG_TYPE_META) {
                amf_data * name;
                amf_data * data;

                result = flv_read_metadata(flv_in, &name, &data);

                if (result == FLV_ERROR_EOF) {
                    print_fatal("F20012", offset + 11, "unexpected end of file in tag");
                    amf_data_free(name);
                    amf_data_free(data);
                    goto end;
                }
                else if (result == FLV_ERROR_EMPTY_TAG) {
                    print_warning("W70038", offset + 11, "empty metadata tag");
                }
                else if (result == FLV_ERROR_INVALID_METADATA_NAME) {
                    print_error("E70039", offset + 11, "invalid metadata name");
                }
                else if (result == FLV_ERROR_INVALID_METADATA) {
                    print_error("E70039", offset + 11, "invalid metadata");
                }
                else if (amf_data_get_type(name) != AMF_TYPE_STRING) {
                    /* name type checking */
                    sprintf(message, "invalid metadata name type: %d, should be a string (2)", amf_data_get_type(name));
                    print_error("E70038", offset, message);
                }
                else {
                    /* empty name checking */
                    if (amf_string_get_size(name) == 0) {
                        print_warning("W70038", offset, "empty metadata name");
                    }

                    /* check whether all body size has been read */
                    if (flv_in->current_tag_body_length > 0) {
                        sprintf(message, "%d bytes not read in tag body after metadata end", body_length - flv_in->current_tag_body_length);
                        print_warning("W70040", flv_get_offset(flv_in), message);
                    }
                    else if (flv_in->current_tag_body_length < 0) {
                        sprintf(message, "%d bytes missing from tag body after metadata end", flv_in->current_tag_body_length - body_length);
                        print_warning("W70041", flv_get_offset(flv_in), message);
                    }

                    /* onLastSecond checking */
                    if (!strcmp((char*)amf_string_get_bytes(name), "onLastSecond")) {
                        if (have_on_last_second == 0) {
                            have_on_last_second = 1;
                            on_last_second_timestamp = timestamp;
                        }
                        else {
                            print_warning("W70038", offset, "duplicate onLastSecond event");
                        }
                    }

                    /* onMetaData checking */
                    if (!strcmp((char*)amf_string_get_bytes(name), "onMetaData")) {
                        if (have_on_metadata == 0) {
                            have_on_metadata = 1;
                            on_metadata_offset = offset;
                            on_metadata = amf_data_clone(data);

                            /* check onMetadata type */
                            if (amf_data_get_type(on_metadata) != AMF_TYPE_ASSOCIATIVE_ARRAY) {
                                sprintf(message, "invalid onMetaData data type: %d, should be an associative array (8)", amf_data_get_type(on_metadata));
                                print_error("E70038", offset, message);
                            }

                            /* onMetaData must be the first tag at 0 timestamp */
                            if (tag_number != 1) {
                                print_warning("W70038", offset, "onMetadata event found after the first tag");
                            }
                            if (timestamp != 0) {
                                print_warning("W70038", offset, "onMetadata event found after timestamp zero");
                            }
                        }
                        else {
                            print_warning("W70038", offset, "duplicate onMetaData event");
                        }
                    }

                    /* unknown metadata name */
                    if (strcmp((char*)amf_string_get_bytes(name), "onMetaData")
                    && strcmp((char*)amf_string_get_bytes(name), "onCuePoint")
                    && strcmp((char*)amf_string_get_bytes(name), "onLastSecond")) {
                        sprintf(message, "unknown metadata event name: '%s'", (char*)amf_string_get_bytes(name));
                        print_info("I70039", flv_get_offset(flv_in), message);
                    }
                }

                amf_data_free(name);
                amf_data_free(data);
            }
        }

        /* check body length against previous tag size */
        result = flv_read_prev_tag_size(flv_in, &prev_tag_size);
        if (result != FLV_OK) {
            print_fatal("F12036", flv_get_offset(flv_in), "unexpected end of file after tag");
            goto end;
        }

        if (prev_tag_size != FLV_TAG_SIZE + body_length) {
            sprintf(message, "previous tag size should be %d, %d found instead", FLV_TAG_SIZE + body_length, prev_tag_size);
            print_error("E12037", flv_get_offset(flv_in), message);
            goto end;
        }
    }

    /** final checks */

    /* check consistency with global header */
    if (!have_video && flv_header_has_video(header)) {
        print_warning("W11038", 4, "no video tag found despite header signaling the file contains video");
    }
    if (!have_audio && flv_header_has_audio(header)) {
        print_warning("W11039", 4, "no audio tag found despite header signaling the file contains audio");
    }

    /* check last timestamps */
    if (have_video && have_audio && labs(last_audio_timestamp - last_video_timestamp) >= 1000) {
        if (last_audio_timestamp > last_video_timestamp) {
            sprintf(message, "video stops %d ms before audio", last_audio_timestamp - last_video_timestamp);
            print_warning("W40040", file_stats.st_size, message);
        }
        else {
            sprintf(message, "audio stops %d ms before video", last_video_timestamp - last_audio_timestamp);
            print_warning("W40041", file_stats.st_size, message);
        }
    }

    /* check video keyframes */
    if (have_video && keyframes_number == 0) {
        print_warning("W60042", file_stats.st_size, "no keyframe detected, file is probably broken or incomplete");
    }
    if (have_video && keyframes_number == video_frames_number) {
        print_warning("W60043", file_stats.st_size, "only keyframes detected, probably inefficient compression scheme used");
    }

    /* only keyframes + onLastSecond bug */
    if (have_video && have_on_last_second && keyframes_number == video_frames_number) {
        print_warning("W60044", file_stats.st_size, "only keyframes detected and onLastSecond event present, file is probably not playable");
    }

    /* check onLastSecond timestamp */
    if (have_on_last_second && (last_timestamp - on_last_second_timestamp) >= 2000) {
        sprintf(message, "onLastSecond event located %d ms before the last tag", last_timestamp - on_last_second_timestamp);
        print_warning("W70050", file_stats.st_size, message);
    }

    /* check onMetaData presence */
    if (!have_on_metadata) {
        print_warning("W70044", file_stats.st_size, "onMetaData event not found, file might not be playable");
    }
    else {
        amf_node * n;
        int have_width, have_height;

        have_width = 0;
        have_height = 0;

        /* compute metadata */
        opts_loc.verbose = 0;
        opts_loc.reset_timestamps = 0;
        opts_loc.preserve_metadata = 0;
        opts_loc.all_keyframes = 0;
        opts_loc.error_handling = FLVMETA_IGNORE_ERRORS;

        flv_reset(flv_in);
        if (get_flv_info(flv_in, &info, &opts_loc) != OK) {
            print_fatal("F10042", 0, "unable to compute metadata");
            goto end;
        }

        /* more metadata checks */
        for (n = amf_associative_array_first(on_metadata); n != NULL; n = amf_associative_array_next(n)) {
            byte * name;
            amf_data * data;
            byte type;

            name = amf_string_get_bytes(amf_associative_array_get_name(n));
            data = amf_associative_array_get_data(n);
            type = amf_data_get_type(data);

            /* hasMetadata (bool): true */
            if (!strcmp((char*)name, "hasMetadata")) {
                if (type == AMF_TYPE_BOOLEAN) {
                    if (amf_boolean_get_value(data) == 0) {
                        print_warning("W70045", on_metadata_offset, "hasMetadata should be set to true");
                    }
                }
                else {
                    sprintf(message, "Invalid type for hasMetadata: expected %s, got %s",
                        get_amf_type_string(AMF_TYPE_BOOLEAN),
                        get_amf_type_string(type));
                    print_warning("W70046", on_metadata_offset, message);
                }
            }

            /* hasVideo (bool) */
            if (!strcmp((char*)name, "hasVideo")) {
                if (type == AMF_TYPE_BOOLEAN) {
                    if (amf_boolean_get_value(data) != info.have_video) {
                        sprintf(message, "hasVideo should be set to %s", info.have_video ? "true" : "false");
                        print_warning("W70045", on_metadata_offset, message);
                    }
                }
                else {
                    sprintf(message, "Invalid type for hasVideo: expected %s, got %s",
                        get_amf_type_string(AMF_TYPE_BOOLEAN),
                        get_amf_type_string(type));
                    print_warning("W70046", on_metadata_offset, message);
                }
            }

            /* hasAudio (bool) */
            if (!strcmp((char*)name, "hasAudio")) {
                if (type == AMF_TYPE_BOOLEAN) {
                    if (amf_boolean_get_value(data) != info.have_audio) {
                        sprintf(message, "hasAudio should be set to %s", info.have_audio ? "true" : "false");
                        print_warning("W70045", on_metadata_offset, message);
                    }
                }
                else {
                    sprintf(message, "Invalid type for hasAudio: expected %s, got %s",
                        get_amf_type_string(AMF_TYPE_BOOLEAN),
                        get_amf_type_string(type));
                    print_warning("W70046", on_metadata_offset, message);
                }
            }

            /* duration (number) */
            if (!strcmp((char*)name, "duration")) {
                if (type == AMF_TYPE_NUMBER) {
                    number64 duration, file_duration;
                    if (info.have_audio) {
                        duration = (info.last_timestamp - info.first_timestamp + info.audio_frame_duration) / 1000.0;
                    }
                    else {
                        duration = (info.last_timestamp - info.first_timestamp + info.video_frame_duration) / 1000.0;
                    }
                    file_duration = amf_number_get_value(data);

                    if (fabs(file_duration - duration) > 1.0) {
                        sprintf(message, "duration should be %.12g, got %.12g", duration, file_duration);
                        print_warning("W70045", on_metadata_offset, message);
                    }
                }
                else {
                    sprintf(message, "Invalid type for duration: expected %s, got %s",
                        get_amf_type_string(AMF_TYPE_NUMBER),
                        get_amf_type_string(type));
                    print_warning("W70046", on_metadata_offset, message);
                }
            }

            /* lasttimestamp: (number) */
            /* lastkeyframetimestamp: (number) */
            /* width: (number) */
            /* height: (number) */
            /* videodatarate: (number)*/
            /* framerate: (number) */
            /* audiodatarate: (number) */
            /* audiosamplerate: (number) */
            /* audiosamplesize: (number) */
            /* stereo: (boolean) */
            /* filesize: (number) */
            /* videosize: (number) */
            /* audiosize: (number) */
            /* datasize: (number) */
            /* audiocodecid: (number) */
            /* videocodecid: (number) */
            /* audiodelay: (number) */
            /* canSeekToEnd: (boolean) */
            /* hasKeyframes: (boolean) */
            /* keyframes: (object) */
        }

        /* missing width or height can cause size problem in various players */
        if (!have_width) {
            print_error("E60047", on_metadata_offset, "width information not found in metadata, problems might occur in some players");
        }
        if (!have_height) {
            print_error("E60047", on_metadata_offset, "height information not found in metadata, problems might occur in some players");
        }
    }

    /* could we compute video resolution ? */
    if (info.video_width == 0 && info.video_height == 0) {
        print_warning("W60044", file_stats.st_size, "unable to determine video resolution");
    }

end:
    report_end(opts, errors, warnings);
    
    amf_data_free(on_metadata);
    flv_close(flv_in);
    
    return (errors > 0) ? ERROR_INVALID_FLV_FILE : OK;
}
コード例 #27
0
ファイル: db_db2_result.c プロジェクト: unizeto/bmd
long db2_bmd_db_result_get_row(void *hDB,void *hRes,long which_row,long max_columns,db_row_strings_t **rowstruct,
						   EnumDbFetchMode_t fetch_mode,long *successfully_fetched)
{
	long err = 0;
	SQLRETURN     rc;


		DB_bmd_db_conn_t *db_conn=NULL;
		//DB_bmd_db_result_t *db_res=NULL;
		//SQLUINTEGER   rowsFetchedNb		= 0;

		SQLSMALLINT   nResultCols=0;
		long colsprocess		= 0;
		long i				= 0;

		/******************************/
		/*	walidacja parametrow	*/
		/******************************/
		if(hDB==NULL)			{	BMD_FOK(BMD_DB_INVALID_CONNECTION_HANDLE);	}

		if(which_row < 0)				{	BMD_FOK(BMD_ERR_PARAM3);			}
		if(max_columns < 0)				{	BMD_FOK(BMD_ERR_PARAM4);			}
		if(rowstruct == NULL)				{       BMD_FOK(BMD_ERR_PARAM5);       			}
		if(*rowstruct != NULL)				{       BMD_FOK(BMD_ERR_PARAM5);                        }
		if( (*((long *)(hDB)) != BMD_DBCONN_MAGIC ) )
			return BMD_ERR_INVALID_PTR;

		db_conn=(DB_bmd_db_conn_t *)hDB;

		if( fetch_mode == FETCH_ABSOLUTE )
			return BMD_ERR_FORMAT;
		else
			if( fetch_mode == FETCH_NEXT )
				;
			else
			{
				return BMD_ERR_FORMAT;
			}


		*rowstruct = (db_row_strings_t *) malloc ( sizeof(db_row_strings_t) );
		if(*rowstruct == NULL)
		{
			PRINT_ERROR("LIBBMDPGERR Memory error. Error=%i\n",NO_MEMORY);
			return NO_MEMORY;
		}
		memset(*rowstruct, 0, sizeof(db_row_strings_t));



		/* identify the output columns */
		rc = SQLNumResultCols( *(db_conn->hstmt), &nResultCols);
		if(rc != SQL_SUCCESS)
		{
			extract_error("SQLNumResultCols", *(db_conn->hstmt), SQL_HANDLE_STMT);
			return BMD_DB_EXECUTION_ERROR;

		}

		if(max_columns <= 0)
		{
			colsprocess = nResultCols;
		}
		else
		{
			colsprocess = (nResultCols < max_columns)? nResultCols:max_columns;
		}

		/* przetwarzam mniejsza wartosc z colsreturned i max_columns */
		(*rowstruct)->size = colsprocess;

		(*rowstruct)->colvals = (char **) malloc (sizeof(char *) * colsprocess);
		if((*rowstruct)->colvals == NULL)
		{
			PRINT_ERROR("LIBBMDPGERR Memory error. Error=%i\n",NO_MEMORY);
			return NO_MEMORY;
		}
		memset((*rowstruct)->colvals, 0, sizeof(char *) * colsprocess);



		/*
		 * set up the values to return fetch information into
		 */

		rc = SQLFetch(*(db_conn->hstmt));
			long ret = print_error(rc, "SQLFetch");
		    if(ret!=BMD_OK)
		    {
			    if(ret == 5)
				{
					PRINT_INFO("No Data Found\n");
			   		return BMD_ERR_NODATA;
				}
			   	else{
			   		extract_error("SQLAllocHandle", *(db_conn->hstmt), SQL_HANDLE_STMT);
			   		return BMD_DB_EXECUTION_ERROR;
			   	}
		    }

		int colNum = 0;
		SQLINTEGER sql_ub;
		rc = SQLGetStmtAttr( *(db_conn->hstmt), SQL_ATTR_USE_BOOKMARKS, &sql_ub, 0, NULL ) ;

		if(print_error(rc, "SQLGetStmtAttr") != BMD_OK)
		{
			extract_error("SQLGetStmtAttr,SQL_ATTR_USE_BOOKMARKS ", *(db_conn->hstmt), SQL_HANDLE_STMT);
			return BMD_DB_EXECUTION_ERROR;
		}

		if ( sql_ub == SQL_UB_OFF )
		  	colNum = 1;
		else
		  	colNum = 0;



		/* Wypelnij wszystkie stringi z wiersza */
		for(i=0; i<colsprocess; i++)
		{
			/* retrieve column data as a string */
			SQLINTEGER indicator;
			//TODO - koniecznie zrobiæ bufor dynamiczny!!!
			SQLCHAR buf[32000];
			rc = SQLGetData(*(db_conn->hstmt), i+colNum, SQL_C_CHAR, buf, sizeof(buf), &indicator);
			if (print_error(rc, "SQLGetData") != BMD_OK)
			{
				extract_error("SQLGetData", *(db_conn->hstmt), SQL_HANDLE_STMT);
				return BMD_DB_EXECUTION_ERROR;
			}
			if(indicator > 0)
				asprintf(&((*rowstruct)->colvals[i]),"%s",buf);
			else
				asprintf(&((*rowstruct)->colvals[i]),"%s","");
		}

		return err;
}
コード例 #28
0
ファイル: print_aranges.c プロジェクト: bergeret/libdwarf
/* get all the data in .debug_aranges */
extern void
print_aranges(Dwarf_Debug dbg)
{
    Dwarf_Signed count = 0;
    Dwarf_Signed i = 0;
    Dwarf_Arange *arange_buf = NULL;
    int ares = 0;
    int aires = 0;
    Dwarf_Off prev_off = 0; /* Holds previous CU offset */
    Dwarf_Bool first_cu = TRUE;
    Dwarf_Off cu_die_offset_prev = 0;
    Dwarf_Error pa_error = 0;

    /* Reset the global state, so we can traverse the debug_info */
    seen_CU = FALSE;
    need_CU_name = TRUE;
    need_CU_base_address = TRUE;
    need_CU_high_address = TRUE;

    current_section_id = DEBUG_ARANGES;
    if (do_print_dwarf) {
        const char *sec_name = 0;
        ares = dwarf_get_aranges_section_name(dbg,
            &sec_name,&pa_error);
        if (ares != DW_DLV_OK || !sec_name || !strlen(sec_name)) {
            sec_name = ".debug_aranges";
        }
        printf("\n%s\n",sec_name);
    }
    ares = dwarf_get_aranges(dbg, &arange_buf, &count, &pa_error);
    if (ares == DW_DLV_ERROR) {
        print_error(dbg, "dwarf_get_aranges", ares, pa_error);
    } else if (ares == DW_DLV_NO_ENTRY) {
        /* no arange is included */
    } else {
        for (i = 0; i < count; i++) {
            Dwarf_Unsigned segment = 0;
            Dwarf_Unsigned segment_entry_size = 0;
            Dwarf_Addr start = 0;
            Dwarf_Unsigned length = 0;
            Dwarf_Off cu_die_offset = 0;
            Dwarf_Die cu_die = NULL;
            aires = dwarf_get_arange_info_b(arange_buf[i],
                &segment,
                &segment_entry_size,
                &start, &length,
                &cu_die_offset, &pa_error);
            if (aires != DW_DLV_OK) {
                print_error(dbg, "dwarf_get_arange_info", aires, pa_error);
            } else {
                int dres;
                struct esb_s producer_name;
                esb_constructor(&producer_name);
                /*  Get basic locations for error reporting */
                dres = dwarf_offdie(dbg, cu_die_offset, &cu_die, &pa_error);
                if (dres != DW_DLV_OK) {
                    print_error(dbg, "dwarf_offdie", dres, pa_error);
                }

                if (cu_name_flag) {
                    if (should_skip_this_cu(dbg,cu_die)) {
                        continue;
                    }
                }
                /* Get producer name for this CU and update compiler list */
                get_producer_name(dbg,cu_die,cu_die_offset,&producer_name);
                update_compiler_target(esb_get_string(&producer_name));
                esb_destructor(&producer_name);
                if (!checking_this_compiler()) {
                    continue;
                }

                if (check_aranges) {
                    do_checking(dbg,arange_buf,i,cu_die_offset,first_cu,
                        cu_die_offset_prev,cu_die);
                }
                /*  Get the offset of the cu header itself in the
                    section, but not for end-entries. */
                if (start || length) {
                    Dwarf_Off off = 0;
                    int cures3 = dwarf_get_arange_cu_header_offset(
                        arange_buf[i], &off, &pa_error);
                    if (cures3 != DW_DLV_OK) {
                        print_error(dbg, "dwarf_get_cu_hdr_offset",
                            cures3, pa_error);
                    }

                    /* Print the CU information if different.  */
                    if (prev_off != off || first_cu) {
                        first_cu = FALSE;
                        prev_off = off;
                        /*  We are faking the indent level. We do not know
                            what level it is, really.

                            If do_check_dwarf we do not want to do
                            the die print call as it will do
                            check/print we may not have asked for.
                            And if we did ask for debug_info checks
                            this will do the checks a second time!
                            So only call print_one_die if printing.
                        */
                        if (do_print_dwarf){
                            /* There is no die if its a set-end entry */
                            print_one_die(dbg, cu_die,
                                cu_die_offset,
                                /* print_information= */ (boolean) TRUE,
                                /* indent_level = */0,
                                /* srcfiles= */ 0,
                                /* cnt= */ 0,
                                /* ignore_die_stack= */TRUE);
                        }
                        /* Reset the state, so we can traverse the debug_info */
                        seen_CU = FALSE;
                        need_CU_name = TRUE;
                        if (do_print_dwarf) {
                            printf("\n");
                        }
                    }

                    if (do_print_dwarf) {
                        /* Print current aranges record */
                        if (segment_entry_size) {
                            printf(
                                "\narange starts at seg,off 0x%"
                                DW_PR_XZEROS DW_PR_DUx
                                ",0x%" DW_PR_XZEROS DW_PR_DUx
                                ", ",
                                segment,
                                (Dwarf_Unsigned)start);
                        } else {
                            printf("\narange starts at 0x%"
                                DW_PR_XZEROS DW_PR_DUx ", ",
                                (Dwarf_Unsigned)start);
                        }
                        printf("length of 0x%" DW_PR_XZEROS DW_PR_DUx
                            ", cu_die_offset = 0x%" DW_PR_XZEROS DW_PR_DUx,
                            length,
                            (Dwarf_Unsigned)cu_die_offset);

                    }
                    if (verbose && do_print_dwarf) {
                        printf(" cuhdr 0x%" DW_PR_XZEROS DW_PR_DUx "\n",
                            (Dwarf_Unsigned)off);
                    }
                    dwarf_dealloc(dbg, cu_die, DW_DLA_DIE);
                    cu_die = 0;
                } else {
                    /*  Must be a range end. We really do want to print
                        this as there is a real record here, an
                        'arange end' record. */
                    if (do_print_dwarf) {
                        printf("\narange end\n");
                    }
                }/* end start||length test */
            }  /* end aires DW_DLV_OK test */

            /* print associated die too? */
            dwarf_dealloc(dbg, arange_buf[i], DW_DLA_ARANGE);
        }
        dwarf_dealloc(dbg, arange_buf, DW_DLA_LIST);
    }
}
コード例 #29
0
ファイル: funcs.c プロジェクト: wazlid/Calculator
ListElmts*
construct_input_list(char *expression)
{
   ListElmts *head = NULL;
   int i = 0,
       unary_sgn = FALSE,
       lenghtExp = strlen(expression),
       type
   ;
   double value;
   while(i < lenghtExp)
   {
      if (expression[i] == '.' || expression[i] == ',' || isdigit(expression[i]))
      {
         if(!isdigit(expression[i-1]))
         {
            value = read_number(expression, &i);
            i--;
            if (unary_sgn)
            {
               if (value != 0)
               {
                  value = type*value;  
               }
               unary_sgn = FALSE;
            }
            type = 0;  
         }
         else
         {
            print_error("Expression mal formée");
            exit(0);
         }
      }
      else if(expression[i] == '-' && (expression[i+1] == '+' || expression[i+1] == '-') && (i == 0 || expression[i-1] =='(') && isdigit(expression[i+2]))
      {
         slist_append(&head, -1, 0);
         slist_append(&head, '*', 1);
         type = -1;
      }
      else if((expression[i] == '+' || expression[i] == '-') && !isdigit(expression[i-1]) && expression[i-1]!=')' && (isdigit(expression[i+1]) || expression[i+1]=='.' || expression[i+1]==','))
      {
         if (expression[i] == '-')
         {
            unary_sgn = TRUE; 
         }
         type = -1;
      }
      else if((expression[i] == '/' || expression[i] =='%') && ((expression[i+1] == '-' || expression[i+1] =='+')) && expression[i+2] =='(')
      {
         type = -1;
      }
      else if((expression[i] == '+' || expression[i] == '-') && expression[i+1] == '(' && expression[i-1]!=')' && !isdigit(expression[i-1]))
      {
         if (expression[i] == '+')
         {
            print_error("Expression mal formée ");
            exit(0);
         }
         else
         {
            type = -1;
         }
      }
      else if(expression[i] == '(')
      {
         if(i > 1)
         {
            if(isdigit(expression[i-1]) || expression[i-1] == ')')
            {
               slist_append(&head, '*', 1);
            }
            else if (expression[i-1] == '-')
            {
               if (expression[i-2] == '/' || expression[i-2] == '%')
               {
                  slist_append(&head, '*', 1);
                  slist_append(&head, -1, 0);
                  slist_append(&head, expression[i-2], 1);
               }
               else if (expression[i-2] == '-' || expression[i-2] =='+' || expression[i-2] == '*' || expression[i-2] =='(')
               {
                  slist_append(&head, -1, 0);
                  slist_append(&head, '*', 1);
               }
            }
         }
         else
         {            
            if(expression[i-1] == '-')
            {
               slist_append(&head, -1, 0);
               slist_append(&head, '*', 1); 
            }
            else if(isdigit(expression[i-1]))
            {
               slist_append(&head, '*', 1);
            }
         }
         value = '(';
         type = 2;
      }
      else
      {
         value = expression[i];
         if (expression[i] == ')')
         {
            if(isdigit(expression[i+1]))
            {
               print_error("Expression mal formée ");
               exit(0);
            }
            type = 2;
         }
         else
         {
            type = 1;
         }
      }
      if(type >= 0)
      {
         slist_append(&head, value, type);
      }
      i++;
   }
   return head;
}
コード例 #30
0
int
main_v1_2(char version)
{
	char		*function = "Tspi_Key_UnloadKey-trans03";
	TSS_HCONTEXT	hContext;
	TSS_HKEY	hSRK;
	TSS_HKEY	hKey, hWrappingKey;
	TSS_RESULT	result;
	TSS_HTPM	hTPM;
	TSS_HPOLICY	srkUsagePolicy;
	TSS_FLAG	initFlags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048  |
				TSS_KEY_VOLATILE | TSS_KEY_NO_AUTHORIZATION |
				TSS_KEY_NOT_MIGRATABLE;

	print_begin_test( function );

	result = connect_load_all(&hContext, &hSRK, &hTPM);
	if (result != TSS_SUCCESS) {
		print_error("connect_load_all", result);
		exit(result);
	}

	result = Testsuite_Transport_Init(hContext, hSRK, hTPM, TRUE, TRUE, &hWrappingKey,
					  NULL);
	if (result != TSS_SUCCESS) {
		print_error("Testsuite_Transport_Init", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}

		//Create Signing Key
	result = Tspi_Context_CreateObject( hContext, TSS_OBJECT_TYPE_RSAKEY, initFlags, &hKey );
        if ( result != TSS_SUCCESS )
        {
                print_error( "Tspi_CreateObject (hKey)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
                exit( result );
        }

	result = Tspi_Key_CreateKey( hKey, hSRK, 0 );
        if ( result != TSS_SUCCESS )
        {
                print_error( "Tspi_Key_CreateKey (hKey)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
                exit( result );
        }

	result = Tspi_Key_LoadKey( hKey, hSRK );
	if ( result != TSS_SUCCESS )
        {
                print_error( "Tspi_Key_LoadKey (hKey)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
                exit( result );
        }

		//Load Key
	result = Tspi_Key_UnloadKey( hKey );
	if ( result != TSS_SUCCESS )
        {
                print_error( "Tspi_Key_UnloadKey (hKey)", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
                exit( result );
        }

	result = Testsuite_Transport_Final(hContext, 0);
	if ( result != TSS_SUCCESS )
	{
		if( !(checkNonAPI(result)) )
			print_error( function, result );
		else
			print_error_nonapi( function, result );

		print_end_test( function );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}
	else
	{
		print_success( function, result );
		print_end_test( function );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( 0 );
	}
}