ComponentResult compressAudio(GenericStreamPtr as)
{
  ComponentResult err = noErr;

  if (as->source.eos)
    return noErr;  //shouldn't be called here.

  UInt32 ioPackets = 1; //I want to get only one packet at a put it in a simple block
  AudioStreamPacketDescription *packetDesc = NULL;

  packetDesc = (AudioStreamPacketDescription *)calloc(ioPackets, sizeof(AudioStreamPacketDescription));

  AudioBufferList *audioBufferList = NULL;
  _initAudioBufferList(as, &audioBufferList, ioPackets);  //allocates memory
  dbg_printf("[WebM] call SCAudioFillBuffer(%x,%x,%x,%x,%x, %x)\n", as->aud.vorbisComponentInstance, _fillBuffer_callBack,
             (void *) as, &ioPackets,
             audioBufferList, packetDesc);

  err = SCAudioFillBuffer(as->aud.vorbisComponentInstance, _fillBuffer_callBack,
                          (void *) as, &ioPackets,
                          audioBufferList, packetDesc);
  dbg_printf("[WebM] exit SCAudioFillBuffer %d packets, err = %d\n", ioPackets, err);

  if (err == eofErr)
  {
    dbg_printf("[WebM] Total Frames in = %lld, Total Frames Out = %lld\n",
               as->framesIn, as->framesOut);
    if (ioPackets == 0)
      as->source.eos = true;
    err= noErr;
  }

  if (err) goto bail;

  if (ioPackets > 0)
  {
    as->aud.buf.offset = 0;
    int i = 0;

    for (i = 0; i < ioPackets; i++)
    {
      dbg_printf("[WebM] packet is %ld bytes, %ld frames\n", packetDesc[i].mDataByteSize,  packetDesc[i].mVariableFramesInPacket);
      as->framesOut += packetDesc[i].mVariableFramesInPacket;
      as->aud.buf.offset += packetDesc[i].mDataByteSize;
    }
    //add a Frame Buffer to the queue
    if (as->aud.buf.offset >0)
    {
      UInt8* buf = malloc(as->aud.buf.offset);
      UInt32 timeMs = as->framesOut * 1000 / as->aud.asbd.mSampleRate;
      memcpy(buf, as->aud.buf.data, as->aud.buf.offset);
      UInt16 frameType = KEY_FRAME + AUDIO_FRAME;
      dbg_printf("[WebM] Output audio packet size %ld, time %lu\n", as->aud.buf.offset, timeMs);
      addFrameToQueue(&as->frameQueue, buf,as->aud.buf.offset, timeMs, frameType, as->framesOut);
      as->aud.buf.offset =0; //reset the buffer for writing
    }
  }

  if (as->frameQueue.size == 0 && as->source.eos)
  {
    as->complete = true;
  }

bail:

  if (audioBufferList != NULL)
    free(audioBufferList);

  if (packetDesc != NULL)
    free(packetDesc);



  return err;
}
Example #2
0
void search_embedfront_inmemory_init() {
	char *buffer;
	long long buffer_max_size, i;

	//
	// (1) open the dict
	//
	dict_file = fopen(DICT_EMBEDFRONT_FILENAME, "rb");
	if (!dict_file) {
		fprintf(stderr, "ERROR open file %s\n", DICT_EMBEDFRONT_FILENAME);
		exit(2);
	}


	//
	// (2) read node_count
	//
	fread(&node_count, sizeof(node_count), 1, dict_file);
	dbg_printf("node_count: %d\n", node_count);
	// header term has a maximum length of MAX_WORD_LENGTH + 1
	buffer_max_size = node_count * (MAX_WORD_LENGTH + 1 + sizeof(node_ptr_t));
	buffer = (char *)malloc(buffer_max_size);
	fread(buffer, buffer_max_size, 1, dict_file);

	//
	// (3) convert into proper header structures
	//
	headers_array = (dict_embedfront_t *) malloc(node_count * sizeof(dict_embedfront_t));
	char *buffer_ptr = buffer;
	for (i = 0; i < node_count; i++) {
		strncpy(headers_array[i].term, buffer_ptr, strlen(buffer_ptr) + 1);
		buffer_ptr += strlen(buffer_ptr) + 1;
		memcpy(&headers_array[i].node_ptr, buffer_ptr, sizeof(node_ptr_t));
		buffer_ptr += sizeof(node_ptr_t);
	}
	free(buffer);

#if 0
	for (i = 0; i < node_count; i++) {
		printf("(%lld): %s\n", i, headers_array[i].term);
	}
#endif

	//
	// (4) read all nodes in memory
	//
	node_max_size = hd_sector_size * num_of_sectors;
	all_nodes = (char *)malloc(node_max_size * node_count);
	if (!all_nodes) {
		perror("ERROR: malloc for all_nodes\n");
		exit(2);
	}
	// reset the fd to the first node in the file
	fseek(dict_file, headers_array[0].node_ptr, SEEK_SET);
	fread(all_nodes, node_max_size, node_count, dict_file);

	stats.io_time = 0;
	stats.search_time = 0;
	stats.bytes_read = 0;

}
Example #3
0
void StartProg( char *cmd, char *prog, char *full_args, char *dos_args )
{
    char            exe_name[PATH_MAX];
    pid_t           save_pgrp;
    pid_t           pid;
    int             status;

    MaxThread = 0;
    GrowArrays( 1 );
    HaveRdebug = false;
    DbgDyn = NULL;
    OrigPGrp = getpgrp();
    Attached = true;
    pid = Pid = SamplePid;

    /* allow attaching to existing process by pid */
    if( pid == 0 || ptrace( PTRACE_ATTACH, pid, NULL, NULL ) == -1 ) {
        int         num_args;
        size_t      len;
        const char  **argv;

        Attached = false;

        /* massage 'full_args' into argv format */
        len = strlen( full_args );
        num_args = SplitParms( full_args, NULL, len );
        argv = alloca( ( num_args + 2 ) * sizeof( *argv ) );
        argv[SplitParms( full_args, argv + 1, len ) + 1] = NULL;
        argv[0] = prog;

        Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] );
        Output( prog );
        Output( "\n" );

        save_pgrp = getpgrp();
        setpgid( 0, OrigPGrp );
        pid = fork();
        if( pid == -1 )
            InternalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
        if( pid == 0 ) {
            int     rc;

            if( ptrace( PTRACE_TRACEME, 0, NULL, NULL ) < 0 ) {
                InternalError( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] );
            }
            dbg_printf( "executing '%s'\n", prog );
            for( rc = 0; argv[rc] != NULL; ++rc )
                dbg_printf( "argv[%d] = '%s'\n", rc, argv[rc] );

            rc = execve( prog, (char const * const *)argv, (char const * const *)environ );
            dbg_printf( "execve() failed, returned %d\n", rc );
            InternalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );  // failsafe
        }
        setpgid( 0, save_pgrp );
        strcpy( exe_name, prog );
    } else if( pid ) {
        GetExeNameFromPid( pid, exe_name, PATH_MAX );
        Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] );
        Output( exe_name );
        Output( "\n" );
    }

    if( (pid != -1) && (pid != 0) ) {
        /* wait until it hits _start (upon execve) or
           gives us a SIGSTOP (if attached) */
        if( waitpid( pid, &status, 0 ) < 0 )
            goto fail;
        if( !WIFSTOPPED( status ) )
            goto fail;
        if( Attached ) {
            if( WSTOPSIG( status ) != SIGSTOP ) {
                goto fail;
            }
        } else {
            if( WSTOPSIG( status ) != SIGTRAP ) {
                goto fail;
            }
        }

        DbgDyn = GetDebuggeeDynSection( exe_name );
        errno = 0;
    }
    if( errno != 0 ) {
        pid = 0;
    } else {
        /* record information about main executable and initialize shared
         * library tracking
         */
        InitLibMap();
        CodeLoad( exe_name, 0, SAMP_MAIN_LOAD );
        SampleLoop( pid );
        FiniLibMap();
    }
    return;

fail:
    if( pid != 0 && pid != -1 ) {
        if( Attached ) {
            ptrace( PTRACE_DETACH, pid, NULL, NULL );
            Attached = false;
        } else {
            ptrace( PTRACE_KILL, pid, NULL, NULL );
            waitpid( pid, &status, 0 );
        }
    }
    InternalError( MsgArray[MSG_SAMPLE_5 - ERR_FIRST_MESSAGE] );
}
Example #4
0
UInt32 CAOggFLACDecoder::ProduceOutputPackets(void* outOutputData, UInt32& ioOutputDataByteSize, UInt32& ioNumberPackets,
                                                AudioStreamPacketDescription* outPacketDescription)
{
    dbg_printf("[ oFD]  >> [%08lx] ProduceOutputPackets(%ld [%ld])\n", (UInt32) this, ioNumberPackets, ioOutputDataByteSize);
    UInt32 ret = kAudioCodecProduceOutputPacketSuccess;

    if (mFramesBufferedList.empty()) {
        ioOutputDataByteSize = 0;
        ioNumberPackets = 0;
        ret = kAudioCodecProduceOutputPacketNeedsMoreInputData;
        dbg_printf("<!E [%08lx] CAOggFLACDecoder :: ProduceOutputPackets(%ld [%ld]) = %ld [%ld]\n", (UInt32) this,
                   ioNumberPackets, ioOutputDataByteSize, ret, FramesReady());
        return ret;
    }

    OggPagePacket &opp = mFramesBufferedList.front();
    UInt32 flac_frames = opp.packets;
    UInt32 flac_bytes = opp.frames * mOutputFormat.mBytesPerFrame;
    UInt32 ogg_packets = 0;
    UInt32 flac_returned_data = ioOutputDataByteSize;
    UInt32 flac_total_returned_data = 0;
    Byte *the_data = static_cast<Byte*> (outOutputData);
    Boolean empty_packet = false;

    while (true) {
        UInt32 flac_return = kAudioCodecProduceOutputPacketSuccess;
        empty_packet = false;
        if (complete_pages < 1) {
            flac_return = kAudioCodecProduceOutputPacketNeedsMoreInputData;
            flac_frames = 0;
            flac_returned_data = 0;
        } else if (flac_frames == 0) {
            UInt32 one_flac_frame = 1;
            empty_packet = true;
            if (flac_bytes < flac_returned_data) {
                flac_returned_data = flac_bytes;
            }
            flac_return = CAFLACDecoder::ProduceOutputPackets(the_data, flac_returned_data, one_flac_frame, NULL);
        } else {
            flac_return = CAFLACDecoder::ProduceOutputPackets(the_data, flac_returned_data, flac_frames, NULL);
        }

        if (flac_return == kAudioCodecProduceOutputPacketSuccess || flac_return == kAudioCodecProduceOutputPacketSuccessHasMore) {
            if (flac_frames > 0)
                opp.packets -= flac_frames;

            if (flac_returned_data > 0)
                opp.frames -= flac_returned_data / mOutputFormat.mBytesPerFrame;

            dbg_printf("[ oFD]     [%08lx] ProduceOutputPackets() p:%ld, f:%ld, c:%ld\n", (UInt32) this, opp.packets, opp.frames, complete_pages);
            if (opp.packets <= 0 && opp.frames <= 0) {
                ogg_packets++;
                if (!empty_packet)
                    complete_pages--;
                mFramesBufferedList.erase(mFramesBufferedList.begin());
                opp = mFramesBufferedList.front();
            }

            flac_total_returned_data += flac_returned_data;

            if (ogg_packets == ioNumberPackets || flac_total_returned_data == ioOutputDataByteSize ||
                flac_return == kAudioCodecProduceOutputPacketSuccess)
            {
                ioNumberPackets = ogg_packets;
                ioOutputDataByteSize = flac_total_returned_data;

                if (!mFramesBufferedList.empty())
                    ret = kAudioCodecProduceOutputPacketSuccessHasMore;
                else
                    ret = kAudioCodecProduceOutputPacketSuccess;

                break;
            } else {
                the_data += flac_returned_data;
                flac_returned_data = ioOutputDataByteSize - flac_total_returned_data;
                flac_frames = opp.packets;
                flac_bytes = opp.frames * mOutputFormat.mBytesPerFrame;
            }
        } else if (flac_return == kAudioCodecProduceOutputPacketNeedsMoreInputData) {
            if (flac_frames > 0)
                opp.packets -= flac_frames;

            if (flac_returned_data > 0)
                opp.frames -= flac_returned_data / mOutputFormat.mBytesPerFrame;

            if (opp.packets <= 0 && opp.frames <= 0) {
                ogg_packets++;
                if (!empty_packet)
                    complete_pages--;
                mFramesBufferedList.erase(mFramesBufferedList.begin());
                //opp = mFramesBufferedList.front();
            }

            ret = kAudioCodecProduceOutputPacketNeedsMoreInputData;
            ioOutputDataByteSize = flac_total_returned_data + flac_returned_data;
            ioNumberPackets = ogg_packets;
            break;
        } else {
            ret = kAudioCodecProduceOutputPacketFailure;
            ioOutputDataByteSize = flac_total_returned_data;
            ioNumberPackets = ogg_packets;
            break;
        }
    }

    dbg_printf("[ oFD] <.. [%08lx] ProduceOutputPackets(%ld [%ld]) = %ld [%ld]\n",
               (UInt32) this, ioNumberPackets, ioOutputDataByteSize, ret, FramesReady());
    return ret;
}
Example #5
0
void build_embedfront() {
	char one_byte = '\0';
	char previous_term[MAX_WORD_LENGTH+1];
	long long i;
	dict_embedfront_t *one_header;
	char *node_buffer = NULL, *postings_buffer = NULL, *term_buffer = NULL;
	char *node_ptr = NULL, *postings_ptr = NULL, *term_ptr = NULL;
	long long node_max_size;
	long long needed_size, used_size;

	if (block_size <= 0) {
		fprintf(stderr, "ERROR: block size cannot be zero or less\n");
		exit(2);
	}

	//
	// (1) find the maximum size for the node and create temporary buffers
	//
	node_max_size = hd_sector_size * num_of_sectors;
	printf("    node_max_size: %lld\n", node_max_size);

	postings_buffer = (char *)malloc(node_max_size);
	memset(postings_buffer, 0, node_max_size);
	term_buffer = (char *)malloc(node_max_size);

	printf("building embedfront......\n");

	//
	// (2) create lists for headers and nodes
	//
	headers_list = new Linked_list<dict_embedfront_t *>();
	nodes_list = new Linked_list<char *> ();

	//
	// (3) read term_count
	//
	vocab_file = fopen(VOCAB_FILENAME, "rb");
	dict_file = fopen(DICT_EMBEDFRONT_FILENAME, "wb");
	fread(&term_count, sizeof(term_count), 1, vocab_file);
	dbg_printf("term_count: %lld\n", term_count);

	//
	// (4) reall all terms, build up the headers and nodes
	//
	i = 0;
	char filled_previously = TRUE;
	char new_node = TRUE;
	char node_is_full = FALSE, the_end = FALSE;
	node_count = 0;
	long long total_wasted = 0;
	long long terms_start_at = 0;
	term[0] = previous_term[0] = '\0';
	while (true) {
		//
		// (4-1) make sure the previous term is filled in properly before read the next term from file
		//
		if (filled_previously) {
			strcpy(previous_term, term);
			fread(term, MAX_WORD_LENGTH+1, 1, vocab_file);
			i++;
			if (i == term_count) {
				the_end = TRUE;
			}
		}

		//
		// (4-2) create a new header and the new associated node
		//
		if (new_node) {
			//one_header = (dict_embed_t *) malloc(sizeof(*one_header));
			one_header = new dict_embedfront_t;
			strncpy(one_header->term, term, strlen(term) + 1);
			headers_list->append(one_header);
			node_count++;

			//node_buffer =  (char *)malloc(sizeof(*node_buffer)*max_node_size*512);
			node_buffer = new char[node_max_size];
			nodes_list ->append(node_buffer);
			node_ptr = node_buffer;
			postings_ptr = postings_buffer;
			term_ptr = term_buffer;
			node_length = 0;

			new_node = FALSE;
			node_is_full = FALSE;
			previous_term[0] = '\0';
		}

		//
		// (4-3) fill as many terms as possible in the node
		//
		// only need to store the prefix_count for the first term in the node
		if (previous_term[0] == '\0') {
			suffix_count = strlen(term);
			needed_size = (long long)POSTING_PTR_SIZE + sizeof(suffix_count) + (sizeof(char) * suffix_count);
		} else {
			find_common_prefix(previous_term, term, &common_prefix_count);
			suffix_count = strlen(term) - common_prefix_count;
			needed_size = (long long)POSTING_PTR_SIZE + sizeof(common_prefix_count) + sizeof(suffix_count) + (sizeof(char) * suffix_count);
		}
		// the node length is stored at the last, so need to consider there is enough space left for it
		needed_size += sizeof(node_length_t);
		// find out how much space is already used in the node
		used_size = (postings_ptr - postings_buffer) + (term_ptr - term_buffer);
		if ((used_size + needed_size) < node_max_size) {
			// fill the postings buffer
			postings_ptr += POSTING_PTR_SIZE;

			// fill the term buffer
			if (previous_term[0] == '\0') {
				*term_ptr = suffix_count;
				term_ptr++;
				memcpy(term_ptr, term, suffix_count);
				term_ptr += suffix_count;
			} else {
				*term_ptr = common_prefix_count;
				term_ptr++;
				*term_ptr = suffix_count;
				term_ptr++;
				memcpy(term_ptr, &term[common_prefix_count], suffix_count);
				term_ptr += suffix_count;
			}

			node_length++;
			filled_previously = TRUE;
		} else {
			node_is_full = TRUE;
			filled_previously = FALSE;
			// the current block is full, need to create a new one
			new_node = TRUE;
		}

		//
		// (4-4) the current node is full or no more term to be processed
		//
		// if node_is_full and the_end happen at the same time, then the last block will not be handled.
		// need to take one more iteration to create a new node and full the buffer and then exit.
		if (node_is_full || the_end) {

			// store the postings in the node
			memcpy(node_ptr, postings_buffer, postings_ptr - postings_buffer);
			node_ptr += postings_ptr - postings_buffer;

			// store the terms in the node
			terms_start_at = node_ptr - node_buffer;
			memcpy(node_ptr, term_buffer, term_ptr - term_buffer);
			node_ptr += term_ptr - term_buffer;

			// find out how much space wasted
			total_wasted = node_max_size - (node_ptr - node_buffer) - sizeof (node_length_t);

			// store node length at the very end of the node
			node_ptr = node_buffer + node_max_size - sizeof(node_length_t);
			memcpy(node_ptr, &node_length, sizeof(node_length_t));
		}

#if 0
		if (node_is_full || the_end) {
			char term[MAX_WORD_LENGTH+1];
			char *node_ptr = node_buffer, *term_ptr;
			node_length_t node_length_02;
			long long i, j;
			uint8_t size;
			node_length_02 = *(node_length_t *) (node_buffer + node_max_size - sizeof(node_length_t));
			printf("node_legnth: %d, node_legnth_02: %d\n", node_length, node_length_02);
			term_ptr = node_buffer + node_length_02 * POSTING_PTR_SIZE;
			for (i = 0; i < node_length_02; i++) {
				if (i == 0) {
					suffix_count = *(uint8_t *)term_ptr;
					term_ptr++;
					memcpy(term, term_ptr, suffix_count);
					term[suffix_count] = '\0';
					term_ptr += suffix_count;
				} else {
					common_prefix_count = *(uint8_t *)term_ptr;
					term_ptr++;
					suffix_count = *(uint8_t *)term_ptr;
					term_ptr++;
					memcpy(&term[common_prefix_count], term_ptr, suffix_count);
					term[common_prefix_count+suffix_count] = '\0';
					term_ptr += suffix_count;
				}
				printf("term: %s\n", term);
			}
		}
#endif

		if ((the_end) && (filled_previously)) {
			break;
		}

	} //end of while (true)

	//
	// (5) write node_count and headers to disk
	//
	dbg_printf("node_count: %u\n", node_count);
	dict_embedfront_t *h = NULL;
	fwrite(&node_count, sizeof(node_count), 1, dict_file);
	for (h = headers_list->first(); h != NULL; h = headers_list->next()) {
		fwrite(h->term, strlen(h->term)+1, 1, dict_file);
		fwrite(&(h->node_ptr), sizeof(h->node_ptr), 1, dict_file);
	}

	//
	// (6) fill in the gap to make sure nodes starting at the beginning of a sector
	//
	//long long padding = hd_sector_size - ftell(dict_file) % hd_sector_size;
	long long padding = node_max_size - ftell(dict_file) % node_max_size;
	total_wasted += padding;
	for (i = 0; i < padding; i++) {
		fwrite(&one_byte, 1, 1, dict_file);
	}

	//
	// (7) write nodes to disk and update node pointer in headers
	//
	char *n = NULL;
	for (n = nodes_list->first(), h = headers_list->first(); n != NULL; n = nodes_list->next(), h = headers_list->next()) {
		h->node_ptr = ftell(dict_file);
		fwrite(n, node_max_size, 1, dict_file);
	}

	//
	// (8) re-write node_count and headers to disk
	//
	fseek(dict_file, 0, SEEK_SET);
	fwrite(&node_count, sizeof(node_count), 1, dict_file);
	for (h = headers_list->first(); h != NULL; h = headers_list->next()) {
		fwrite(h->term, strlen(h->term) + 1, 1, dict_file);
		fwrite(&(h->node_ptr), sizeof(h->node_ptr), 1, dict_file);
	}

	//
	// (9) finished
	//
	printf("     total_wasted: %lld bytes\n", total_wasted);
	fseek(dict_file, 0, SEEK_END);
	printf("  total file size: %ld\n", ftell(dict_file));
	fclose(dict_file);
	free(postings_buffer);
	free(term_buffer);
	delete headers_list;
	delete nodes_list;
	printf("FINISHED\n\n");
}
Example #6
0
/** \brief parse option from configuration file.
*
* \param[in,out] as Pointer to session handle
* \param[in] opt name of option to set (left of =)
* \param[in] param name of value for option (right of =)
* \param type type for param, currently unused
* \return 0 if parsing was successful, -1 if an error occured.  currently
* always returns 0
*/
PRIVATE int set_option(auto_handle *as, const char *opt, const char *param, option_type type) {
  int32_t numval;
  int32_t result = SUCCESS;

  dbg_printf(P_INFO2, "[config] %s=%s (type: %d)", opt, param, type);

  assert(as != NULL);
  if(!strcmp(opt, "url")) {
    dbg_printf(P_ERROR, "the 'url' option is not supported any more, please use the 'feed' option instead!");
    result = FAILURE;
  } else if(!strcmp(opt, "feed")) {
    result = parseFeed(&as->feeds, param);
  } else if(!strcmp(opt, "transmission-home")) {
    set_path(param, &as->transmission_path);
  } else if(!strcmp(opt, "prowl-apikey")) {
    as->prowl_key = am_strdup(param);
  } else if(!strcmp(opt, "toasty-deviceid")) {
    as->toasty_key = am_strdup(param);
  } else if(!strcmp(opt, "pushalot-token")) {
    as->pushalot_key = am_strdup(param);
  } else if(!strcmp(opt, "transmission-version")) {
    if (!strcmp(param, "external")) {
      /* we should probably only set this when transmission-external is set */
      as->transmission_version = AM_TRANSMISSION_EXTERNAL;
    } else if(param[0] == '1' && param[1] == '.' && param[2] == '2') {
      as->transmission_version = AM_TRANSMISSION_1_2;
    } else if(param[0] == '1' && param[1] == '.' && param[2] == '3') {
      as->transmission_version = AM_TRANSMISSION_1_3;
    } else {
      dbg_printf(P_ERROR, "Unknown parameter: %s=%s", opt, param);
    }
  } else if (!strcmp(opt, "transmission-external")) {
    set_path(param, &as->transmission_external);
    as->transmission_version = AM_TRANSMISSION_EXTERNAL;
  } else if(!strcmp(opt, "torrent-folder")) {
    set_path(param, &as->torrent_folder);
  } else if(!strcmp(opt, "statefile")) {
    set_path(param, &as->statefile);
  } else if(!strcmp(opt, "rpc-host")) {
    as->host = am_strdup(param);
  } else if(!strcmp(opt, "rpc-auth")) {
    as->auth = am_strdup(param);
  } else if(!strcmp(opt, "upload-limit")) {
    numval = parseUInt(param);
    if(numval > 0) {
      as->upspeed = (uint16_t)numval;
    } else {
      dbg_printf(P_ERROR, "Unknown parameter: %s=%s", opt, param);
    }
  } else if(!strcmp(opt, "rpc-port")) {
    numval = parseUInt(param);
    if (numval > 1024 && numval < 65535) {
      as->rpc_port = numval;
    } else if(numval != -1) {
      dbg_printf(P_ERROR, "RPC port must be an integer between 1025 and 65535, reverting to default (%d)\n\t%s=%s", AM_DEFAULT_RPCPORT, opt, param);
    } else {
      dbg_printf(P_ERROR, "Unknown parameter: %s=%s", opt, param);
    }
  } else if(!strcmp(opt, "interval")) {
    numval = parseUInt(param);
    if(numval > 0) {
      as->check_interval = numval;
    } else if(numval != -1) {
      dbg_printf(P_ERROR, "Interval must be 1 minute or more, reverting to default (%dmin)\n\t%s=%s", AM_DEFAULT_INTERVAL, opt, param);
    } else {
      dbg_printf(P_ERROR, "Unknown parameter: %s=%s", opt, param);
    }
  } else if(!strcmp(opt, "use-transmission")) {
    if(!strncmp(param, "0", 1) || !strncmp(param, "no", 2)) {
      as->use_transmission = 0;
    } else if(!strncmp(param, "1", 1) || !strncmp(param, "yes", 3)) {
      as->use_transmission = 1;
    } else {
      dbg_printf(P_ERROR, "Unknown parameter: %s=%s", opt, param);
    }
  } else if(!strcmp(opt, "start-torrents")) {
    if(!strncmp(param, "0", 1) || !strncmp(param, "no", 2)) {
      as->start_torrent = 0;
    } else if(!strncmp(param, "1", 1) || !strncmp(param, "yes", 3)) {
      as->start_torrent = 1;
    } else {
      dbg_printf(P_ERROR, "Unknown parameter for option '%s': '%s'", opt, param);
    }
  } else if(!strcmp(opt, "patterns")) {
    dbg_printf(P_ERROR, "the 'patterns' option is not supported any more, please use the 'filter' option instead!");
    result = FAILURE;
  } else if(!strcmp(opt, "filter")) {
    result = parseFilter(&as->filters, param);
  } else {
    dbg_printf(P_ERROR, "Unknown option: %s", opt);
  }

  return result;
}
Example #7
0
extern bool extract_archive_file(const char *archname, const char *archpath, const char *dest, t_copy_cb cb, t_copy_overwritecb ocb, void *data)
{
	t_fs_filetype ft;
	SceUID fd;
	bool result = false;
	buffer *archdata = NULL;
	int buffer_cache;
	char *ptr;

	if (archname == NULL || archpath == NULL || dest == NULL)
		return false;

	ft = get_archive_type(archname);

	if (ft == fs_filetype_unknown)
		return false;

	if (ocb != NULL) {
		SceUID fd;

		fd = sceIoOpen(dest, PSP_O_RDONLY, 0777);
		if (fd >= 0) {
			if (!ocb(dest, data)) {
				sceIoClose(fd);
				return false;
			}
			sceIoClose(fd);
		}
	}

	dbg_printf(d, "extract_archive_file: %s %s %s, ft = %d", archname, archpath, dest, ft);

	fd = sceIoOpen(dest, PSP_O_CREAT | PSP_O_RDWR, 0777);

	if (fd < 0)
		return false;

	extract_archive_file_into_buffer(&archdata, archname, archpath, ft);

	if (archdata == NULL || archdata->ptr == NULL)
		goto exit;

	buffer_cache = archdata->used >= 1024 * 1024 ? 1024 * 1024 : archdata->used;

	ptr = archdata->ptr;

	while (buffer_cache > 0) {
		int bytes = sceIoWrite(fd, ptr, buffer_cache);

		if (bytes < 0) {
			goto exit;
		}
		buffer_cache = archdata->used - bytes >= 1024 * 1024 ? 1024 * 1024 : archdata->used - bytes;
		ptr += bytes;
	}

	result = true;

  exit:
	sceIoClose(fd);
	if (archdata != NULL) {
		buffer_free(archdata);
	}

	return result;
}
Example #8
0
static int be_ppc_fetch_integer(const struct dbg_lvalue* lvalue, unsigned size,
                                unsigned ext_sign, LONGLONG* ret)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #9
0
static int be_ppc_fetch_float(const struct dbg_lvalue* lvalue, unsigned size, 
                              long double* ret)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #10
0
static void be_ppc_clear_watchpoint(CONTEXT* ctx, unsigned idx)
{
    dbg_printf("not done\n");
}
Example #11
0
static int be_ppc_adjust_pc_for_break(CONTEXT* ctx, BOOL way)
{
    dbg_printf("not done\n");
    return 0;
}
Example #12
0
static unsigned be_ppc_is_watchpoint_set(const CONTEXT* ctx, unsigned idx)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #13
0
void CASpeexDecoder::GetProperty(AudioCodecPropertyID inPropertyID, UInt32& ioPropertyDataSize, void* outPropertyData)
{
    dbg_printf(" >> [%08lx] CASpeexDecoder :: GetProperty('%4.4s')\n", (UInt32) this, reinterpret_cast<char*> (&inPropertyID));
    switch(inPropertyID)
    {
    case kAudioCodecPropertyRequiresPacketDescription:
        if(ioPropertyDataSize == sizeof(UInt32))
        {
            *reinterpret_cast<UInt32*>(outPropertyData) = 1;
        }
        else
        {
            CODEC_THROW(kAudioCodecBadPropertySizeError);
        }
        break;
    case kAudioCodecPropertyHasVariablePacketByteSizes:
        if(ioPropertyDataSize == sizeof(UInt32))
        {
            *reinterpret_cast<UInt32*>(outPropertyData) = 1;
        }
        else
        {
            CODEC_THROW(kAudioCodecBadPropertySizeError);
        }
        break;
    case kAudioCodecPropertyPacketFrameSize:
        if(ioPropertyDataSize == sizeof(UInt32))
        {
            UInt32 *outProp = reinterpret_cast<UInt32*>(outPropertyData);
            if (!mCompressionInitialized)
                *outProp = kSpeexFramesPerPacket;
            else if (mSpeexHeader.frame_size != 0 * mSpeexHeader.frames_per_packet != 0)
                *outProp = mSpeexHeader.frame_size * mSpeexHeader.frames_per_packet;
            else
                *outProp = 8192;
            if (*outProp < 8192 && mInputFormat.mFormatID == kAudioFormatXiphOggFramedSpeex)
                *outProp = 8192;
            dbg_printf("  = [%08lx] CASpeexDecoder :: GetProperty('pakf'): %ld\n",
                       (UInt32) this, *outProp);
        }
        else
        {
            CODEC_THROW(kAudioCodecBadPropertySizeError);
        }
        break;

        //case kAudioCodecPropertyQualitySetting: ???
#if TARGET_OS_MAC
    case kAudioCodecPropertyNameCFString:
        {
            if (ioPropertyDataSize != sizeof(CFStringRef)) CODEC_THROW(kAudioCodecBadPropertySizeError);

            CABundleLocker lock;
            CFStringRef name = CFCopyLocalizedStringFromTableInBundle(CFSTR("Xiph Speex decoder"), CFSTR("CodecNames"), GetCodecBundle(), CFSTR(""));
            *(CFStringRef*)outPropertyData = name;
            break;
        }

        //case kAudioCodecPropertyManufacturerCFString:
#endif
    default:
        ACBaseCodec::GetProperty(inPropertyID, ioPropertyDataSize, outPropertyData);
    }
    dbg_printf("<.. [%08lx] CASpeexDecoder :: GetProperty('%4.4s')\n", (UInt32) this, reinterpret_cast<char*> (&inPropertyID));
}
ComponentResult write_vorbisPrivateData(GenericStreamPtr as, UInt8 **buf, UInt32 *bufSize)
{
  ComponentResult err = noErr;
  void *magicCookie = NULL;
  UInt32 cookieSize = 0;
  dbg_printf("[WebM] Get Vorbis Private Data\n");

  err = QTGetComponentPropertyInfo(as->aud.vorbisComponentInstance,
                                   kQTPropertyClass_SCAudio,
                                   kQTSCAudioPropertyID_MagicCookie,
                                   NULL, &cookieSize, NULL);

  if (err) return err;

  dbg_printf("[WebM] Cookie Size %d\n", cookieSize);

  magicCookie = calloc(1, cookieSize);
  err = QTGetComponentProperty(as->aud.vorbisComponentInstance,
                               kQTPropertyClass_SCAudio,
                               kQTSCAudioPropertyID_MagicCookie,
                               cookieSize, magicCookie, NULL);

  if (err) goto bail;

  UInt8 *ptrheader = (UInt8 *) magicCookie;
  UInt8 *cend = ptrheader + cookieSize;
  CookieAtomHeader *aheader = (CookieAtomHeader *) ptrheader;
  WebMBuffer header, header_vc, header_cb;
  header.size = header_vc.size = header_cb.size = 0;

  while (ptrheader < cend)
  {
    aheader = (CookieAtomHeader *) ptrheader;
    ptrheader += EndianU32_BtoN(aheader->size);

    if (ptrheader > cend || EndianU32_BtoN(aheader->size) <= 0)
      break;

    switch (EndianS32_BtoN(aheader->type))
    {
      case kCookieTypeVorbisHeader:
        header.size = EndianS32_BtoN(aheader->size) - 2 * sizeof(long);
        header.data = aheader->data;
        break;

      case kCookieTypeVorbisComments:
        header_vc.size = EndianS32_BtoN(aheader->size) - 2 * sizeof(long);
        header_vc.data = aheader->data;
        break;

      case kCookieTypeVorbisCodebooks:
        header_cb.size = EndianS32_BtoN(aheader->size) - 2 * sizeof(long);
        header_cb.data = aheader->data;
        break;

      default:
        break;
    }
  }

  if (header.size == 0 || header_vc.size == 0 || header_cb.size == 0)
  {
    err = paramErr;
    goto bail;
  }

  //1 + header1 /255 + header2 /255 + idheader.len +
  *bufSize = 1;  //the first byte which is always 0x02
  *bufSize += (header.size - 1) / 255 + 1; //the header size lacing
  *bufSize += (header_vc.size - 1) / 255 + 1; //the comment size lacing
  *bufSize += header.size + header_vc.size + header_cb.size; //the packets
  dbg_printf("[WebM]Packet headers  %d %d %d -- total buffer %d\n",
             header.size, header_vc.size , header_cb.size, *bufSize);
  *buf = malloc(*bufSize);
  UInt8 *ptr = *buf;

  *ptr = 0x02;
  ptr ++;
  //using ogg lacing write out the size of the first two packets
  _oggLacing(&ptr, header.size);
  _oggLacing(&ptr, header_vc.size);

  _dbg_printVorbisHeader(header.data);

  memcpy(ptr, header.data, header.size);
  ptr += header.size;
  memcpy(ptr, header_vc.data, header_vc.size);
  ptr += header_vc.size;
  memcpy(ptr, header_cb.data, header_cb.size);

bail:

  if (magicCookie != NULL)
  {
    free(magicCookie);
    magicCookie = NULL;
  }

  return err;
}
Example #15
0
static errcode_t undo_write_tdb(io_channel channel,
				unsigned long long block, int count)

{
	int size, sz;
	unsigned long long block_num, backing_blk_num;
	errcode_t retval = 0;
	ext2_loff_t offset;
	struct undo_private_data *data;
	unsigned char *read_ptr;
	unsigned long long end_block;
	unsigned long long data_size;
	struct undo_key *key;
	__u32 blk_crc;

	data = (struct undo_private_data *) channel->private_data;

	if (data->undo_file == NULL) {
		/*
		 * Transaction database not initialized
		 */
		return 0;
	}

	if (count == 1)
		size = channel->block_size;
	else {
		if (count < 0)
			size = -count;
		else
			size = count * channel->block_size;
	}

	retval = undo_setup_tdb(data);
	if (retval)
		return retval;
	/*
	 * Data is stored in tdb database as blocks of tdb_data_size size
	 * This helps in efficient lookup further.
	 *
	 * We divide the disk to blocks of tdb_data_size.
	 */
	offset = (block * channel->block_size) + data->offset ;
	block_num = offset / data->tdb_data_size;
	end_block = (offset + size - 1) / data->tdb_data_size;

	while (block_num <= end_block) {
		__u32 keysz;

		/*
		 * Check if we have the record already
		 */
		if (ext2fs_test_block_bitmap2(data->written_block_map,
						   block_num)) {
			/* Try the next block */
			block_num++;
			continue;
		}
		ext2fs_mark_block_bitmap2(data->written_block_map, block_num);

		/*
		 * Read one block using the backing I/O manager
		 * The backing I/O manager block size may be
		 * different from the tdb_data_size.
		 * Also we need to recalcuate the block number with respect
		 * to the backing I/O manager.
		 */
		offset = block_num * data->tdb_data_size +
				(data->offset % data->tdb_data_size);
		backing_blk_num = (offset - data->offset) / channel->block_size;

		retval = ext2fs_get_mem(data->tdb_data_size, &read_ptr);
		if (retval) {
			return retval;
		}

		memset(read_ptr, 0, data->tdb_data_size);
		actual_size = 0;
		if ((data->tdb_data_size % channel->block_size) == 0)
			sz = data->tdb_data_size / channel->block_size;
		else
			sz = -data->tdb_data_size;
		retval = io_channel_read_blk64(data->real, backing_blk_num,
					     sz, read_ptr);
		if (retval) {
			if (retval != EXT2_ET_SHORT_READ) {
				free(read_ptr);
				return retval;
			}
			/*
			 * short read so update the record size
			 * accordingly
			 */
			data_size = actual_size;
		} else {
			data_size = data->tdb_data_size;
		}
		if (data_size == 0) {
			free(read_ptr);
			block_num++;
			continue;
		}
		dbg_printf("Read %llu bytes from FS block %llu (blk=%llu cnt=%llu)\n",
		       data_size, backing_blk_num, block, data->tdb_data_size);
		if ((data_size % data->undo_file->block_size) == 0)
			sz = data_size / data->undo_file->block_size;
		else
			sz = -data_size;;
		/* extend this key? */
		if (data->keys_in_block) {
			key = data->keyb->keys + data->keys_in_block - 1;
			keysz = ext2fs_le32_to_cpu(key->size);
		} else {
			key = NULL;
			keysz = 0;
		}
		if (key != NULL &&
		    (ext2fs_le64_to_cpu(key->fsblk) * channel->block_size +
		     channel->block_size - 1 +
		     keysz) / channel->block_size == backing_blk_num &&
		    E2UNDO_MAX_EXTENT_BLOCKS * data->tdb_data_size >
		    keysz + data_size) {
			blk_crc = ext2fs_le32_to_cpu(key->blk_crc);
			blk_crc = ext2fs_crc32c_le(blk_crc, read_ptr, data_size);
			key->blk_crc = ext2fs_cpu_to_le32(blk_crc);
			key->size = ext2fs_cpu_to_le32(keysz + data_size);
		} else {
			data->num_keys++;
			key = data->keyb->keys + data->keys_in_block;
			data->keys_in_block++;
			key->fsblk = ext2fs_cpu_to_le64(backing_blk_num);
			blk_crc = ext2fs_crc32c_le(~0, read_ptr, data_size);
			key->blk_crc = ext2fs_cpu_to_le32(blk_crc);
			key->size = ext2fs_cpu_to_le32(data_size);
		}
		dbg_printf("Writing block %llu to offset %llu size %d key %zu\n",
		       block_num,
		       data->undo_blk_num,
		       sz, data->num_keys - 1);
		retval = io_channel_write_blk64(data->undo_file,
					data->undo_blk_num, sz, read_ptr);
		if (retval) {
			free(read_ptr);
			return retval;
		}
		data->undo_blk_num++;
		free(read_ptr);

		/* Write out the key block */
		retval = write_undo_indexes(data, 0);
		if (retval)
			return retval;

		/* Next block */
		block_num++;
	}

	return retval;
}
Example #16
0
static int be_ppc_store_integer(const struct dbg_lvalue* lvalue, unsigned size,
                                unsigned is_signed, LONGLONG val)
{
    dbg_printf("be_ppc_store_integer: not done\n");
    return FALSE;
}
Example #17
0
PRIVATE simple_list parseMultiOption(const char *str) {
  int tmp_pos;
  uint32_t line_pos = 0;
  uint32_t len = strlen(str);
  simple_list options = NULL;
  char tmp[MAX_PARAM_LEN];
  int last_dbl_quote_pos;
  int8_t parse_error = 0;
  int32_t current_line_pos = 0;

  if(len == 0) {
    dbg_printf(P_ERROR, "[parseMultiOption] empty input string!");
    return NULL;
  }

   while(line_pos < len) {
    memset(&tmp, 0, sizeof(tmp));
    // Skip any initial whitespace
    while (line_pos < len && isspace(str[line_pos])) {
      ++line_pos;
    }

    tmp_pos = 0;
    parse_error = 0;
    last_dbl_quote_pos = -1;

    while(line_pos < len && str[line_pos] != '\0') {
      if(str[line_pos] == '\"') {
        last_dbl_quote_pos = tmp_pos;
      } else if(str[line_pos] == '\n') {
        // Text is broken over multiple lines
        if(str[line_pos - 1] == '\\' || str[line_pos - 1] == '+') {
          // skip newline
          line_pos++;
          // skip whitespace at the beginning of the next line
          while (line_pos < len && isspace(str[line_pos])) {
            ++line_pos;
          }

          if(str[line_pos] == '\"' && last_dbl_quote_pos != -1) {
            // Reset the string index to the position of the last double-quote, and properly null-terminate it
            tmp_pos = last_dbl_quote_pos;
            tmp[tmp_pos] = '\0';

            // Skip the double-quote on the new line as well
            line_pos++;
          } else {
            tmp[tmp_pos] = '\0';
            dbg_printf(P_ERROR, "[parseMultiOption] Parsing error at line '%s'", &tmp[current_line_pos]);
            parse_error = 1;
            break;
          }
        } else {
          // If the character before the newline is not a backslash ('\'), consider this suboption complete
          break;
        }

        current_line_pos = tmp_pos;
      }

      tmp[tmp_pos++] = str[line_pos++];
    }

    if(parse_error) {
      break;
    }

    /* A suboption is finished, end it with a null terminator */
    tmp[tmp_pos] = '\0';

    /* store the line in our list */
    if(tmp_pos != 0) {
      suboption_t* i = parseSubOption(tmp);

      if(i != NULL) {
        addItem(i, &options);
      } else {
        dbg_printf(P_ERROR, "Invalid suboption string: '%s'", tmp);
      }
    }
  }

  return options;
}
Example #18
0
static unsigned be_ppc_get_register_info(int regno, enum be_cpu_addr* kind)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #19
0
/** \brief parse configuration file.
*
* \param[in,out] as Pointer to session handle
* \param[in] filename Path to the configuration file
* \return 0 if parsing was successful, -1 if an error occured.
*/
int parse_config_file(struct auto_handle *as, const char *filename) {
  FILE *fp = NULL;
  char *line = NULL;
  char opt[MAX_OPT_LEN + 1];
  char param[MAX_PARAM_LEN + 1];
  char c; /* for the "" and '' check */
  int line_num = 0;
  int line_pos = 0;
  int opt_pos;
  int param_pos;
  int parse_error = 0;
  struct stat fs;
  option_type type;

  if ((fp = fopen(filename, "rb")) == NULL) {
    perror("fopen");
    return -1;
  }

  if(stat(filename, &fs) == -1) {
    fclose(fp);
    return -1;
  }

  if ((line = am_malloc(fs.st_size + 1)) == NULL) {
    dbg_printf(P_ERROR, "Can't allocate memory for 'line': %s (%ldb)", strerror(errno), fs.st_size + 1);
    fclose(fp);
    return -1;
  }

  if(fread(line, fs.st_size, 1, fp) != 1) {
    perror("fread");
    fclose(fp);
    am_free(line);
    return -1;
  }

  /* NULL-terminate the result */
  line[fs.st_size] = '\0';

  if(fp) {
    fclose(fp);
  }

  while(line_pos != fs.st_size) {
    line_pos = SkipWhitespace(line, line_pos, &line_num);

    if(line_pos < 0) {
      parse_error = 1;
      break;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* comment */
    if (line[line_pos] == '#') {
      ////dbg_printf(P_INFO2, "skipping comment (line %d)", line_num);
      while (line[line_pos] != '\n') {
        ++line_pos;
      }

      ++line_num;
      ++line_pos;  /* skip the newline as well */
      continue;
    }

    /* read option */
    for (opt_pos = 0; isprint(line[line_pos]) && line[line_pos] != ' ' &&
         line[line_pos] != '#' && line[line_pos] != '='; /* NOTHING */) {
      opt[opt_pos++] = line[line_pos++];
      if (opt_pos >= MAX_OPT_LEN) {
        dbg_printf(P_ERROR, "too long option at line %d", line_num);
        parse_error = 1;
      }
    }

    if (opt_pos == 0 || parse_error == 1) {
      dbg_printf(P_ERROR, "parse error at line %d (pos: %d)", line_num, line_pos);
      parse_error = 1;
      break;
    } else {
      opt[opt_pos] = '\0';
    }

    line_pos = SkipWhitespace(line, line_pos, &line_num);

    if(line_pos < 0) {
      parse_error = 1;
      break;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* check for '=' */
    if (line[line_pos++] != '=') {
         dbg_printf(P_ERROR, "Option '%s' needs a parameter (line %d)", opt, line_num);
      parse_error = 1;
      break;
    }

    line_pos = SkipWhitespace(line, line_pos, &line_num);

    if(line_pos < 0) {
      parse_error = 1;
      break;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* read the parameter */

    /* case 1: single string, no linebreaks allowed */
    if (line[line_pos] == '"' || line[line_pos] == '\'') {
      c = line[line_pos]; /* single or double quote */
      ++line_pos;  /* skip quote */
      parse_error = 1;
      for (param_pos = 0; (param_pos < MAX_PARAM_LEN) && (line_pos < fs.st_size) && (line[line_pos] != '\n'); /* NOTHING */) {
        if( line[line_pos] == c) {
          parse_error = 0;
          break;
        }
        param[param_pos++] = line[line_pos++];
      }

      if(parse_error == 0) {
        line_pos++;  /* skip the closing single or double quote */
        type = CONF_TYPE_STRING;
      } else {
        dbg_printf(P_ERROR, "Option '%s' has a too long parameter (line %d). Closing quote missing?", opt, line_num);
        break;
      }
    } else if (line[line_pos] == '{') { /* case 2: multiple items, linebreaks allowed */
      dbg_printf(P_DBG, "reading multiline param", line_num);
      ++line_pos;
      parse_error = 1;

      for (param_pos = 0; (line_pos < fs.st_size) && (param_pos < MAX_PARAM_LEN); /* NOTHING */) {
        if(line[line_pos] == '}') {
          parse_error = 0;
          break;
        }
        param[param_pos++] = line[line_pos++];
        if(line[line_pos] == '\n') {
          line_num++;
        }
      }

      if(parse_error == 0) {
        line_pos++;  /* skip the closing '}' */
        type = CONF_TYPE_STRINGLIST;
      } else {
        dbg_printf(P_ERROR, "Option %s has a too long parameter (line %d). Closing bracket missing?", opt, line_num);
        parse_error = 1;
        break;
      }
    } else { /* Case 3: integers */
      parse_error = 0;
      for (param_pos = 0; isprint(line[line_pos]) && !isspace(line[line_pos]) && line[line_pos] != '#'; /* NOTHING */) {
          param[param_pos++] = line[line_pos++];
          if (param_pos >= MAX_PARAM_LEN) {
            dbg_printf(P_ERROR, "Option %s has a too long parameter (line %d)", opt, line_num);
            parse_error = 1;
            break;
          }
      }

      if(parse_error == 0) {
        type = CONF_TYPE_INT;
      } else {
        break;
      }
    }

    param[param_pos] = '\0';
    dbg_printf(P_DBG, "[parse_config_file] option: %s", opt);
    dbg_printf(P_DBG, "[parse_config_file] param: %s (%d byte)", param, strlen(param));
    dbg_printf(P_DBG, "[parse_config_file] -----------------");

    if(set_option(as, opt, param, type) == FAILURE) {
      parse_error = 1;
      break;
    }

    line_pos = SkipWhitespace(line, line_pos, &line_num);

    if(line_pos < 0) {
      parse_error = 1;
      break;
    }

    if(line_pos >= fs.st_size) {
      break;
    }
  }

  am_free(line);

  return (parse_error == 1) ? -1 : 0;
}
Example #20
0
static void be_ppc_print_context(HANDLE hThread, const CONTEXT* ctx, int all_regs)
{
    dbg_printf("Context printing for PPC not done yet\n");
}
Example #21
0
void flashfile_sectorDump()
{
	dbg_printf(DBGMODE_DEBUG, "flashfile_sectorDump\r\n");

	uint32_t magic = FLASHFILE_MAGIC;
	//magic ^= version_crc();

	dbg_printf(DBGMODE_DEBUG, "magic 0x%08X, start 0x%08X, size 0x%08X, end 0x%08X, sect 0x%08X\r\n\r\n", magic, FLASHFILE_PAGE_START, FLASHFILE_PAGE_SIZE, FLASHFILE_PAGE_END, FLASHFILE_SECTOR);

	int i, j;
	uint32_t last = 0;

	// look for first instance of blank
	// we don't want to dump too much blank data
	for (i = FLASHFILE_PAGE_END; i >= FLASHFILE_PAGE_START; i--) {
		uint8_t* p = (uint8_t*)i;
		uint8_t v = *p;
		if (v != 0xFF) {
			last = i + 1;
			break;
		}
	}

	// but at least have some output
	if (last < FLASHFILE_PAGE_START + 64) {
		last = FLASHFILE_PAGE_START + 64;
	}

	i = FLASHFILE_PAGE_START;
	int old_j = 0;
	uint8_t chksum = 0;

	// we write out the dump in Intel HEX format

	for (; i <= last;)
	{
		j = i >> 16;

		if (old_j != j && j > 0)
		{
			// if the address is really high, we need to use extended addressing
			chksum = 0;
			dbg_printf(DBGMODE_DEBUG, ":02"); // byte cnt
			chksum += 0x02;
			dbg_printf(DBGMODE_DEBUG, "0000"); // empty address
			dbg_printf(DBGMODE_DEBUG, "04"); // extended address field
			dbg_printf(DBGMODE_DEBUG, "%04X", j); // upper memory
			chksum += j & 0xFF;
			chksum += j >> 8;
			dbg_printf(DBGMODE_DEBUG, "%02X\r\n", chksum ^ 0xFF);
			old_j = j;
		}

		uint32_t cnt = FLASHFILE_PAGE_END - i + 1;
		if (cnt > 16) {
			cnt = 16;
		}

		chksum = 0;
		dbg_printf(DBGMODE_DEBUG, ":%02X", cnt); // byte cnt
		chksum += cnt;
		dbg_printf(DBGMODE_DEBUG, "%04X", i & 0xFFFF); // address
		chksum += i & 0xFF;
		chksum += (i >> 8) & 0xFF;
		dbg_printf(DBGMODE_DEBUG, "00"); // record type is data

		for (int k = 0; k < cnt; k++, i++) {
			uint8_t* p = (uint8_t*)i;
			uint8_t v = *p;
			dbg_printf(DBGMODE_DEBUG, "%02X", v);
			chksum += v;
		}
		dbg_printf(DBGMODE_DEBUG, "%02X\r\n", chksum ^ 0xFF);
	}
Example #22
0
static unsigned be_ppc_is_function_return(const void* insn)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #23
0
void serialise_embedfront() {
	FILE *serialised_file = NULL;
	char *buffer;
	long long i, j, buffer_max_size;
	char term[MAX_WORD_LENGTH+1];

	printf("\nserialising embed......");

	//
	// (1) open files
	//
	dict_file = fopen(DICT_EMBEDFRONT_FILENAME, "rb");
	if (!dict_file) { fprintf(stderr, "ERROR open file %s\n", DICT_EMBEDFRONT_FILENAME); exit(2); }
	serialised_file = fopen(SERIALISE_EMBEDFRONT_FILENAME, "wb");
	if (!serialised_file) { fprintf(stderr, "ERROR open file %s\n", SERIALISE_EMBEDFRONT_FILENAME); exit(2); }

	//
	// (2) read header terms from file
	//
	fread(&node_count, sizeof(node_count), 1, dict_file);
	dbg_printf("node_count: %d\n", node_count);
	// header term has a maximum length of MAX_WORD_LENGTH + 1
	buffer_max_size = node_count * (MAX_WORD_LENGTH + 1 + sizeof(node_ptr_t));
	buffer = (char *)malloc(buffer_max_size);
	fread(buffer, buffer_max_size, 1, dict_file);

	//
	// (3) convert into proper header structures
	//
	headers_array = (dict_embedfront_t *)malloc(node_count * sizeof(dict_embedfront_t));
	char *buffer_ptr = buffer;
	for (i = 0; i < node_count; i++) {
		strncpy(headers_array[i].term, buffer_ptr, strlen(buffer_ptr)+1);
		buffer_ptr += strlen(buffer_ptr)+1;
		memcpy(&headers_array[i].node_ptr, buffer_ptr, sizeof(node_ptr_t));
		buffer_ptr += sizeof(node_ptr_t);
	}
	free(buffer);

#if 0
	for (i = 0; i < node_count; i++) {
		printf("header[%lld]: %s\n", i, headers_array[i].term);
	}
	exit(2);
#endif

	//
	// (4) read one node at a time, and serialise the terms in the node
	//
	buffer_max_size = hd_sector_size * num_of_sectors;
	buffer = (char *)malloc(buffer_max_size);
	char *term_ptr;
	for (i = 0; i < node_count; i++) {
		fseek(dict_file, headers_array[i].node_ptr, SEEK_SET);
		fread(buffer, buffer_max_size, 1, dict_file);

		// find out the node length which is stored at the very end of the node
		buffer_ptr = buffer + buffer_max_size - sizeof(node_length_t);
		memcpy(&node_length, buffer_ptr, sizeof(node_length_t));

		term_ptr = buffer + node_length * POSTING_PTR_SIZE;
		for (j = 0; j < node_length; j++) {
			if (j == 0) {
				suffix_count = *(uint8_t *)term_ptr;
				term_ptr++;
				memcpy(term, term_ptr, suffix_count);
				term[suffix_count] = '\0';
				term_ptr += suffix_count;
			} else {
				common_prefix_count = *(uint8_t *)term_ptr;
				term_ptr++;
				suffix_count = *(uint8_t *)term_ptr;
				term_ptr++;
				memcpy(&term[common_prefix_count], term_ptr, suffix_count);
				term[common_prefix_count+suffix_count] = '\0';
				term_ptr += suffix_count;
			}
			fwrite(term, strlen(term), 1, serialised_file);
			fwrite("\n", 1, 1, serialised_file);
		}
	}
	free(buffer);

	//
	// (5) finished
	//
	fclose(dict_file);
	fclose(serialised_file);
	printf("\n");
}
Example #24
0
static unsigned be_ppc_is_break_insn(const void* insn)
{
    dbg_printf("not done\n");
    return FALSE;
}
Example #25
0
void search_embedfront_ondisk_init() {
	char *buffer;
	long long buffer_max_size, i;

	//
	// (1) open the dict
	//
	dict_file = fopen(DICT_EMBEDFRONT_FILENAME, "rb");
	if (!dict_file) {
		fprintf(stderr, "ERROR open file %s\n", DICT_EMBEDFRONT_FILENAME);
		exit(2);
	}


	//
	// (2) read node_count
	//
	fread(&node_count, sizeof(node_count), 1, dict_file);
	dbg_printf("node_count: %d\n", node_count);
	// header term has a maximum length of MAX_WORD_LENGTH + 1
	buffer_max_size = node_count * (MAX_WORD_LENGTH + 1 + sizeof(node_ptr_t));
	buffer = (char *)malloc(buffer_max_size);
	fread(buffer, buffer_max_size, 1, dict_file);

	//
	// (3) convert into proper header structures
	//
	headers_array = (dict_embedfront_t *) malloc(node_count * sizeof(dict_embedfront_t));
	char *buffer_ptr = buffer;
	for (i = 0; i < node_count; i++) {
		strncpy(headers_array[i].term, buffer_ptr, strlen(buffer_ptr) + 1);
		buffer_ptr += strlen(buffer_ptr) + 1;
		memcpy(&headers_array[i].node_ptr, buffer_ptr, sizeof(node_ptr_t));
		buffer_ptr += sizeof(node_ptr_t);
	}
	free(buffer);

	//
	// (4) pre-allocate a node for use
	//
	node_max_size = hd_sector_size * num_of_sectors;
	node_buffer = (char *)malloc(node_max_size);

	stats.io_time = 0;
	stats.search_time = 0;
	stats.bytes_read = 0;

#if 0
	for (i = 0; i < node_count; i++) {
		printf("(%lld): %s\n", i, headers_array[i].term);
	}
#endif

#if (USE_O_DIRECT == 1)
	fclose(dict_file);
	free(node_buffer);
	int page_size = sysconf(_SC_PAGESIZE);

	if (posix_memalign(&aligned_buffer, page_size, node_max_size) != 0) {
		perror("posix_memalign for node_buffer\n");
		exit(2);
	}

	if ((dict_file_odirect = open(DICT_EMBEDFRONT_FILENAME, O_RDONLY | O_DIRECT)) , 0) {
		fprintf(stderr, "open with O_DIRECT for %s\n", DICT_EMBEDFRONT_FILENAME);
		exit(2);
	}
#endif
}
Example #26
0
static void be_ppc_disasm_one_insn(ADDRESS64* addr, int display)

{
    dbg_printf("Disasm NIY\n");
}
Example #27
0
/* Handle breakpoints - we expect to see breakpoints in the dynamic linker
 * (which we set ourselves) as well as profiler marks (embedded in the
 * profiled application's code).
 */
static bool ProcessBreakpoint( pid_t pid, u_long ip )
{
    static int  ld_state = RT_CONSISTENT;   // This ought to be per-pid
    int         ptrace_sig = 0;

#if defined( MD_x86 )
    user_regs_struct    regs;

    // on x86, when breakpoint was hit the EIP points to the next
    // instruction, so we must be careful
    ptrace( PTRACE_GETREGS, pid, NULL, &regs );

    if( ip == Rdebug.r_brk + sizeof( opcode_type ) ) {
#elif defined( MD_ppc )
    if( ip == Rdebug.r_brk ) {
#endif
        opcode_type         brk_opcode = BRKPOINT;
        int                 status;
        int                 ret;

        /* The dynamic linker breakpoint was hit, meaning that
         * libraries are being loaded or unloaded. This gets a bit
         * tricky because we must restore the original code that was
         * at the breakpoint and execute it, but we still want to
         * keep the breakpoint.
         */
        if( WriteMem( pid, &saved_opcode, Rdebug.r_brk, sizeof( saved_opcode ) ) != sizeof( saved_opcode ) )
            printf( "WriteMem() #1 failed\n" );
        ReadMem( pid, &Rdebug, (addr_off)DbgRdebug, sizeof( Rdebug ) );
        dbg_printf( "ld breakpoint hit, state is " );
        switch( Rdebug.r_state ) {
        case RT_ADD:
            dbg_printf( "RT_ADD\n" );
            AddLibrary( pid, Rdebug.r_map );
            ld_state = RT_ADD;
            break;
        case RT_DELETE:
            dbg_printf( "RT_DELETE\n" );
            ld_state = RT_DELETE;
            break;
        case RT_CONSISTENT:
            dbg_printf( "RT_CONSISTENT\n" );
            if( ld_state == RT_DELETE )
                RemoveLibrary( pid, Rdebug.r_map );
            ld_state = RT_CONSISTENT;
            break;
        default:
            dbg_printf( "error!\n" );
            break;
        }
#if defined( MD_x86 )
        regs.eip--;
        ptrace( PTRACE_SETREGS, pid, NULL, &regs );
#endif
        // unset breakpoint, single step, re-set breakpoint
        if( ptrace( PTRACE_SINGLESTEP, pid, NULL, (void *)ptrace_sig ) < 0 )
            perror( "ptrace()" );
        do {    // have to loop since SIGALRM can interrupt us here
            ret = waitpid( pid, &status, 0 );
        } while( (ret < 0) && (errno == EINTR) );
        if( ret == -1)
            perror( "waitpid()" );
        if( WriteMem( pid, &brk_opcode, Rdebug.r_brk, sizeof( brk_opcode ) ) != sizeof( brk_opcode ) )
            dbg_printf( "WriteMem() #2 failed with errno %d for pid %d, %d bytes (at %p)!\n", errno, pid, sizeof( brk_opcode ), Rdebug.r_brk );
        return( true ); // indicate this was our breakpoint
    } else {
        dbg_printf( "Not an ld breakpoint, assuming mark\n" );
#if defined( MD_x86 )
        return( ProcessMark( pid, &regs ) );
#endif
    }
    return( false );
}


/*
 * Real time signal (SIGALRM) handler. All we really need to do is wake up
 * periodically to interrupt waitpid(), the signal handler need not do much
 * at all.
 */
static void alarm_handler( int signo )
{
    TimerTicked = true;
}


/* Install periodic real time alarm signal */
static void InstSigHandler( int msec_period )
{
    struct sigaction    sigalrm;
    struct itimerval    timer;

    sigalrm.sa_handler = (void *)alarm_handler;
    sigemptyset( &sigalrm.sa_mask );
    sigalrm.sa_flags = 0;

    sigaction( SIGALRM, &sigalrm, NULL );

    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = msec_period * 1000;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = msec_period * 1000;

    if( setitimer( ITIMER_REAL, &timer, NULL ) ) {
        InternalError( MsgArray[MSG_SAMPLE_6 - ERR_FIRST_MESSAGE] );
    }
}


/*
 * Main sampler loop. We run the profiled application under the control of
 * ptrace(). The sampler installs a SIGALRM handler which ticks at the desired
 * rate. Whenever the SIGALRM interrupts our own waitpid(), we send a SIGSTOP
 * to the profiled app and when the child app notifies us of the SIGSTOP, we
 * remember the current execution point and continue the profiled app. Note
 * that we may miss some ticks but this is not a problem - the ticks don't
 * even need to be regular to provide usable results.
 */
static void SampleLoop( pid_t pid )
{
    static int          ptrace_sig = 0;
    static bool         do_cont = true;
    int                 status;
    user_regs_struct    regs;
    bool                sample_continue = true;
    int                 ret;
    opcode_type         brk_opcode = BRKPOINT;

    TimerTicked = false;
    InstSigHandler( SleepTime );

    do {
        if( do_cont && ptrace( PTRACE_CONT, pid, NULL, (void *)ptrace_sig ) == -1)
            perror( "ptrace()" );
        ret = waitpid( pid, &status, 0 );
        if( (ret < 0) && (errno == EINTR) ) {
            /* did we get woken up by SIGALRM? */
            if( TimerTicked ) {
                TimerTicked = false;
                /* interrupt child process - next waitpid() will see this */
                kill( pid, SIGSTOP );
            } else {
                dbg_printf( "who the hell interrupted waitpid()?\n" );
            }
            do_cont = false;
            continue;
        }
        if( ret < 0 )
            perror( "waitpid()" );
        do_cont = true;

        /* record current execution point */
#if defined( MD_x86 )
        ptrace( PTRACE_GETREGS, pid, NULL, &regs );
#elif defined( MD_ppc )
        regs.eip = ptrace( PTRACE_PEEKUSER, pid, REGSIZE * PT_NIP, NULL );
#endif
        if( WIFSTOPPED( status ) ) {
            /* If debuggee has dynamic section, try getting the r_debug struct
             * every time the child process stops. The r_debug data may not be
             * available immediately after the child process first loads.
             */
            if( !HaveRdebug && (DbgDyn != NULL) ) {
                if( Get_ld_info( pid, DbgDyn, &Rdebug, &DbgRdebug ) ) {

                    AddLibrary( pid, Rdebug.r_map );
                    HaveRdebug = true;

                    /* Set a breakpoint in dynamic linker. That way we can be
                     * informed on dynamic library load/unload events.
                     */
                    ReadMem( pid, &saved_opcode, Rdebug.r_brk, sizeof( saved_opcode ) );
                    dbg_printf( "setting ld breakpoint at %p, old opcode was %X\n", Rdebug.r_brk, saved_opcode );
                    WriteMem( pid, &brk_opcode, Rdebug.r_brk, sizeof( brk_opcode ) );
                }
            }

            sample_continue = false;
            switch( (ptrace_sig = WSTOPSIG( status )) ) {
            case SIGSEGV:
                dbg_printf( "SIGSEGV at %p\n", regs.eip );
                sample_continue = true;
                break;
            case SIGILL:
                dbg_printf( "SIGILL at %p\n", regs.eip );
                sample_continue = true;
                break;
            case SIGABRT:
                dbg_printf( "SIGABRT at %p\n", regs.eip );
                sample_continue = true;
                break;
            case SIGINT:
                dbg_printf( "SIGINT at %p\n", regs.eip );
                sample_continue = true;
                break;
            case SIGTRAP:
                dbg_printf( "SIGTRAP at %p\n", regs.eip );
                if( ProcessBreakpoint( pid, regs.eip ) ) {
                    // don't pass on SIGTRAP if we expected this breakpoint
                    ptrace_sig = 0;
                }
                sample_continue = true;
                break;
            case SIGSTOP:
                /* presumably we were behind this SIGSTOP */
                RecordSample( regs.eip, 1 );
                ptrace_sig = 0;
                sample_continue = true;
                break;
            default:
                /* all other signals get passed down to the child and we let
                 * the child handle them (or not handle and die)
                 */
                sample_continue = true;
                break;
            }
        } else if( WIFEXITED( status ) ) {
            dbg_printf( "WIFEXITED pid %d\n", pid );
            report();
            sample_continue = false;
        } else if( WIFSIGNALED( status ) ) {
            dbg_printf( "WIFSIGNALED pid %d\n", pid );
            report();
            sample_continue = false;
        }
    } while( sample_continue );
}


static int GetExeNameFromPid( pid_t pid, char *buffer, int max_len )
{
    char        procfile[24];
    int         len;

    sprintf( procfile, "/proc/%d/exe", pid );
    len = readlink( procfile, buffer, max_len );
    if( len < 0 )
        len = 0;
    buffer[len] = '\0';
    return( len );
}
Example #28
0
static errcode_t write_undo_indexes(struct undo_private_data *data, int flush)
{
	errcode_t retval;
	struct ext2_super_block super;
	io_channel channel;
	int block_size;
	__u32 sb_crc, hdr_crc;

	/* Spit out a key block, if there's any data */
	if (data->keys_in_block) {
		data->keyb->magic = ext2fs_cpu_to_le32(KEYBLOCK_MAGIC);
		data->keyb->crc = 0;
		data->keyb->crc = ext2fs_cpu_to_le32(
					 ext2fs_crc32c_le(~0,
					 (unsigned char *)data->keyb,
					 data->tdb_data_size));
		dbg_printf("Writing keyblock to blk %llu\n", data->key_blk_num);
		retval = io_channel_write_blk64(data->undo_file,
						data->key_blk_num,
						1, data->keyb);
		if (retval)
			return retval;
		/* Move on to the next key block if it's full. */
		if (data->keys_in_block == KEYS_PER_BLOCK(data)) {
			memset(data->keyb, 0, data->tdb_data_size);
			data->keys_in_block = 0;
			data->key_blk_num = data->undo_blk_num;
			data->undo_blk_num++;
		}
	}

	/* Prepare superblock for write */
	channel = data->real;
	block_size = channel->block_size;

	io_channel_set_blksize(channel, SUPERBLOCK_OFFSET);
	retval = io_channel_read_blk64(channel, 1, -SUPERBLOCK_SIZE, &super);
	if (retval)
		goto err_out;
	sb_crc = ext2fs_crc32c_le(~0, (unsigned char *)&super, SUPERBLOCK_SIZE);
	super.s_magic = ~super.s_magic;

	/* Write the undo header to disk. */
	memcpy(data->hdr.magic, E2UNDO_MAGIC, sizeof(data->hdr.magic));
	data->hdr.num_keys = ext2fs_cpu_to_le64(data->num_keys);
	data->hdr.super_offset = ext2fs_cpu_to_le64(data->super_blk_num);
	data->hdr.key_offset = ext2fs_cpu_to_le64(data->first_key_blk);
	data->hdr.fs_block_size = ext2fs_cpu_to_le32(block_size);
	data->hdr.sb_crc = ext2fs_cpu_to_le32(sb_crc);
	data->hdr.fs_offset = ext2fs_cpu_to_le64(data->offset);
	if (data->offset)
		e2undo_set_feature_fs_offset(&data->hdr);
	else
		e2undo_clear_feature_fs_offset(&data->hdr);
	hdr_crc = ext2fs_crc32c_le(~0, (unsigned char *)&data->hdr,
				   sizeof(data->hdr) -
				   sizeof(data->hdr.header_crc));
	data->hdr.header_crc = ext2fs_cpu_to_le32(hdr_crc);
	retval = io_channel_write_blk64(data->undo_file, 0,
					-(int)sizeof(data->hdr),
					&data->hdr);
	if (retval)
		goto err_out;

	/*
	 * Record the entire superblock (in FS byte order) so that we can't
	 * apply e2undo files to the wrong FS or out of order.
	 */
	dbg_printf("Writing superblock to block %llu\n", data->super_blk_num);
	retval = io_channel_write_blk64(data->undo_file, data->super_blk_num,
					-SUPERBLOCK_SIZE, &super);
	if (retval)
		goto err_out;

	if (flush)
		retval = io_channel_flush(data->undo_file);
err_out:
	io_channel_set_blksize(channel, block_size);
	return retval;
}
Example #29
0
File: out.c Project: alphaKAI/dmd
void outdata(symbol *s)
{
#if HTOD
    return;
#endif
    targ_size_t datasize,a;
    int seg;
    targ_size_t offset;
    int flags;
    tym_t ty;

    symbol_debug(s);
#ifdef DEBUG
    debugy && dbg_printf("outdata('%s')\n",s->Sident);
#endif
    //printf("outdata('%s', ty=x%x)\n",s->Sident,s->Stype->Tty);
    //symbol_print(s);

    // Data segment variables are always live on exit from a function
    s->Sflags |= SFLlivexit;

    dt_t *dtstart = s->Sdt;
    s->Sdt = NULL;                      // it will be free'd
#if SCPP && TARGET_WINDOS
    if (eecontext.EEcompile)
    {   s->Sfl = (s->ty() & mTYfar) ? FLfardata : FLextern;
        s->Sseg = UNKNOWN;
        goto Lret;                      // don't output any data
    }
#endif
    datasize = 0;
    ty = s->ty();
    if (ty & mTYexport && config.wflags & WFexpdef && s->Sclass != SCstatic)
        objmod->export_symbol(s,0);        // export data definition
    for (dt_t *dt = dtstart; dt; dt = dt->DTnext)
    {
        //printf("\tdt = %p, dt = %d\n",dt,dt->dt);
        switch (dt->dt)
        {
        case DT_abytes:
        {   // Put out the data for the string, and
            // reserve a spot for a pointer to that string
            datasize += size(dt->Dty);      // reserve spot for pointer to string
#if TARGET_SEGMENTED
            if (tybasic(dt->Dty) == TYcptr)
            {   dt->DTseg = cseg;
                dt->DTabytes += Coffset;
                goto L1;
            }
            else if (tybasic(dt->Dty) == TYfptr &&
                     dt->DTnbytes > config.threshold)
            {
                targ_size_t foffset;
                dt->DTseg = objmod->fardata(s->Sident,dt->DTnbytes,&foffset);
                dt->DTabytes += foffset;
L1:
                objmod->write_bytes(SegData[dt->DTseg],dt->DTnbytes,dt->DTpbytes);
                break;
            }
            else
#endif
            {
                dt->DTabytes += objmod->data_readonly(dt->DTpbytes,dt->DTnbytes,&dt->DTseg);
            }
            break;
        }
        case DT_ibytes:
            datasize += dt->DTn;
            break;
        case DT_nbytes:
            //printf("DT_nbytes %d\n", dt->DTnbytes);
            datasize += dt->DTnbytes;
            break;
        case DT_symsize:
#if MARS
            assert(0);
#else
            dt->DTazeros = type_size(s->Stype);
#endif
            goto case_azeros;
        case DT_azeros:
            /* A block of zeros
             */
            //printf("DT_azeros %d\n", dt->DTazeros);
case_azeros:
            datasize += dt->DTazeros;
            if (dt == dtstart && !dt->DTnext && s->Sclass != SCcomdat)
            {   /* first and only, so put in BSS segment
                 */
                switch (ty & mTYLINK)
                {
#if TARGET_SEGMENTED
                case mTYfar:                    // if far data
                    s->Sseg = objmod->fardata(s->Sident,datasize,&s->Soffset);
                    s->Sfl = FLfardata;
                    break;

                case mTYcs:
                    s->Sseg = cseg;
                    Coffset = align(datasize,Coffset);
                    s->Soffset = Coffset;
                    Coffset += datasize;
                    s->Sfl = FLcsdata;
                    break;
#endif
                case mTYthread:
                {   seg_data *pseg = objmod->tlsseg_bss();
                    s->Sseg = pseg->SDseg;
                    objmod->data_start(s, datasize, pseg->SDseg);
                    if (config.objfmt == OBJ_OMF)
                        pseg->SDoffset += datasize;
                    else
                        objmod->lidata(pseg->SDseg, pseg->SDoffset, datasize);
                    s->Sfl = FLtlsdata;
                    break;
                }
                default:
                    s->Sseg = UDATA;
                    objmod->data_start(s,datasize,UDATA);
                    objmod->lidata(s->Sseg,s->Soffset,datasize);
                    s->Sfl = FLudata;           // uninitialized data
                    break;
                }
                assert(s->Sseg && s->Sseg != UNKNOWN);
                if (s->Sclass == SCglobal || (s->Sclass == SCstatic && config.objfmt != OBJ_OMF)) // if a pubdef to be done
                    objmod->pubdefsize(s->Sseg,s,s->Soffset,datasize);   // do the definition
                searchfixlist(s);
                if (config.fulltypes &&
                        !(s->Sclass == SCstatic && funcsym_p)) // not local static
                    cv_outsym(s);
#if SCPP
                out_extdef(s);
#endif
                goto Lret;
            }
            break;
        case DT_common:
            assert(!dt->DTnext);
            outcommon(s,dt->DTazeros);
            goto Lret;

        case DT_xoff:
        {   symbol *sb = dt->DTsym;

            if (tyfunc(sb->ty()))
#if SCPP
                nwc_mustwrite(sb);
#else
                ;
#endif
            else if (sb->Sdt)               // if initializer for symbol
            {   if (!s->Sseg) s->Sseg = DATA;
                outdata(sb);                // write out data for symbol
            }
        }
        case DT_coff:
            datasize += size(dt->Dty);
            break;
        default:
#ifdef DEBUG
            dbg_printf("dt = %p, dt = %d\n",dt,dt->dt);
#endif
            assert(0);
        }
    }
static ComponentResult
_fillBuffer_callBack(ComponentInstance ci, UInt32 *ioNumberDataPackets, AudioBufferList *ioData,
                     AudioStreamPacketDescription **outDataPacketDescription, void *inRefCon)
{
    GenericStreamPtr as = (GenericStreamPtr) inRefCon;
    StreamSource *source = &as->source;
    MovieExportGetDataParams *params = &source->params;

    ComponentResult err = noErr;

    dbg_printf("[WebM] _fillBuffer_callBack(%ld), current samples = %d\n",
               *ioNumberDataPackets, params->actualSampleCount);

    const UInt32 packetsRequested = *ioNumberDataPackets;

    *ioNumberDataPackets = 0;

    if (source->eos)
        return err;

    if (params->actualSampleCount > packetsRequested)
    {
        //we already have samples
        dbg_printDataParams(source);
      //TODO : this error can be accounted for... it just seems to never happen.
        dbg_printf("[webm] *******error: TODO Potential unconsumed samples\n");
    }
    else if (params->actualSampleCount == 0)
    {
        initMovieGetParams(source);
        params->requestedSampleCount = packetsRequested;
        err = InvokeMovieExportGetDataUPP(source->refCon, params, source->dataProc);
        dbg_printDataParams(source);

        if (err == eofErr)
        {
            //source->eos = true;
            dbg_printf("[Webm] Audio stream complete eos\n");
            return err;
        }

        if (err) return err;

        dbg_printf("[Webm] Audio Time = %f\n", getTimeAsSeconds(source));
    }

    if (params->actualSampleCount == 0)
    {
        dbg_printf("[WebM] fillBufferCallBack no more samples\n");
        ioData->mBuffers[0].mDataByteSize = 0;
        ioData->mBuffers[0].mData = NULL;
        source->eos = true;
        dbg_printf("[Webm] audio stream complete - no samples \n");
    }
    else
    {

        dbg_printf("[WebM] fillBufferCallBack %d samples, %d dataSize\n",
                   params->actualSampleCount, params->dataSize);
        ioData->mBuffers[0].mDataByteSize = params->dataSize;
        ioData->mBuffers[0].mData = params->dataPtr;

        source->time += params->durationPerSample * params->actualSampleCount;
        *ioNumberDataPackets = params->actualSampleCount;
        params->actualSampleCount = 0;
    }
    as->framesIn += *ioNumberDataPackets;

    return err;
}