static int log_read(ambit_object_t *object, ambit_log_skip_cb skip_cb, ambit_log_push_cb push_cb, ambit_log_progress_cb progress_cb, void *userref) { int entries_read = 0; uint8_t *reply_data = NULL; size_t replylen = 0; uint16_t log_entries_total = 0; uint16_t log_entries_walked = 0; uint32_t more = 0x00000400; bool read_pmem = false; ambit_log_header_t log_header; ambit_log_entry_t *log_entry; LOG_INFO("Reading number of logs"); log_header.activity_name = NULL; /* * Read number of log entries */ if (libambit_protocol_command(object, ambit_command_log_count, NULL, 0, &reply_data, &replylen, 0) != 0) { LOG_WARNING("Failed to read number of log entries"); return -1; } log_entries_total = le16toh(*(uint16_t*)(reply_data + 2)); libambit_protocol_free(reply_data); LOG_INFO("Number of logs=%d", log_entries_total); /* * First part walks through headers to check if there is any point in start * reading the PMEM content. If no skip callback is defined, there is no * point in checking the headers, because no one can tell us to not include * the logs... */ if (skip_cb != NULL) { LOG_INFO("Look in headers for new logs"); // Rewind if (libambit_protocol_command(object, ambit_command_log_head_first, NULL, 0, &reply_data, &replylen, 0) != 0) { LOG_WARNING("Failed to rewind header pointer"); return -1; } more = le32toh(*(uint32_t*)reply_data); libambit_protocol_free(reply_data); // Loop through logs while more entries exists while (more == 0x00000400) { LOG_INFO("Reading next header"); // Go to next entry if (libambit_protocol_command(object, ambit_command_log_head_step, NULL, 0, &reply_data, &replylen, 0) != 0) { LOG_WARNING("Failed to walk to next header"); return -1; } libambit_protocol_free(reply_data); // Assume every header is composited by 2 parts, where only the // second is of interrest right now if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) != 0) { LOG_WARNING("Failed to read first part of header"); return -1; } libambit_protocol_free(reply_data); if (libambit_protocol_command(object, ambit_command_log_head, NULL, 0, &reply_data, &replylen, 0) == 0) { if (replylen > 8 && libambit_pmem20_log_parse_header(reply_data + 8, replylen - 8, &log_header) == 0) { if (skip_cb(userref, &log_header) != 0) { // Header was NOT skipped, break out! read_pmem = true; LOG_INFO("Found new entry, start reading log data"); break; } } else { LOG_ERROR("Failed to parse log header"); return -1; } libambit_protocol_free(reply_data); } else { LOG_WARNING("Failed to read second part of header"); return -1; } // Is there more entries to read? if (libambit_protocol_command(object, ambit_command_log_head_peek, NULL, 0, &reply_data, &replylen, 0) != 0) { LOG_WARNING("Failed to check for more headers"); return -1; } more = le32toh(*(uint32_t*)reply_data); libambit_protocol_free(reply_data); } } else { LOG_INFO("No skip callback defined, reading log data"); read_pmem = true; } if (read_pmem) { if (libambit_pmem20_log_init(&object->driver_data->pmem20, PMEM20_LOG_START, PMEM20_LOG_SIZE) != 0) { return -1; } // Loop through all log entries, first check headers while (log_entries_walked < log_entries_total && libambit_pmem20_log_next_header(&object->driver_data->pmem20, &log_header) == 1) { LOG_INFO("Reading header of log %d of %d", log_entries_walked + 1, log_entries_total); if (progress_cb != NULL) { progress_cb(userref, log_entries_total, log_entries_walked+1, 100*log_entries_walked/log_entries_total); } // Check if this entry needs to be read if (skip_cb == NULL || skip_cb(userref, &log_header) != 0) { LOG_INFO("Reading data of log %d of %d", log_entries_walked + 1, log_entries_total); log_entry = libambit_pmem20_log_read_entry(&object->driver_data->pmem20); if (log_entry != NULL) { if (push_cb != NULL) { push_cb(userref, log_entry); } entries_read++; } } else { LOG_INFO("Log %d of %d already exists, skip reading data", log_entries_walked + 1, log_entries_total); } log_entries_walked++; if (progress_cb != NULL) { progress_cb(userref, log_entries_total, log_entries_walked, 100*log_entries_walked/log_entries_total); } } } LOG_INFO("%d entries read", entries_read); return entries_read; }
// // Renders the user interface using D2D on top of our D3D12 content. // HRESULT D3D12MemoryManagement::RenderUI() { HRESULT hr = S_OK; UINT FrameIndex = m_pDXGISwapChain->GetCurrentBackBufferIndex(); // // Acquire the wrapped back buffer object. When we release the wrapped object, it will // be placed in a presentable state, and we can call Present directly. // m_p11On12Device->AcquireWrappedResources(&m_pWrappedBackBuffers[FrameIndex], 1); m_pD2DContext->SetTarget(m_pD2DRenderTargets[FrameIndex]); m_pD2DContext->BeginDraw(); m_pD2DContext->SetTransform(D2D1::Matrix3x2F::Identity()); if (m_bRenderStats) { // // Render statistical information, such as the framerate, memory budget graph, // and glitch count. // m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING); m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); RenderMemoryGraph(); // // Frame statistics (FPS, CPU time, etc). // { D2D1_RECT_F TextRect; TextRect.left = 8; TextRect.top = 8; TextRect.right = 256; TextRect.bottom = 256; float StatTimeBetweenFrames = AverageStatistics(m_StatTimeBetweenFrames, STATISTIC_COUNT); float StatRenderScene = AverageStatistics(m_StatRenderScene, STATISTIC_COUNT); float StatRenderUI = AverageStatistics(m_StatRenderUI, STATISTIC_COUNT); m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); wchar_t FPSString[128]; swprintf_s( FPSString, _TRUNCATE, L"FPS: %d (%.2fms)\n" L"Glitch Count: %d\n" L"\n" L"RenderScene: %.2f ms\n" L"RenderUI: %.2f ms", (UINT)(1.0f / StatTimeBetweenFrames), StatTimeBetweenFrames * 1000.0f, GetGlitchCount(), StatRenderScene * 1000.0f, StatRenderUI * 1000.0f); m_pD2DContext->DrawTextW( FPSString, (UINT)wcslen(FPSString), m_pTextFormat, &TextRect, m_pTextBrush); } } hr = m_pD2DContext->EndDraw(); if (FAILED(hr)) { LOG_WARNING("D2D EndDraw failed, hr=0x%.8x", hr); } // // Unreference the render target after rendering completes. // m_pD2DContext->SetTarget(nullptr); m_p11On12Device->ReleaseWrappedResources(&m_pWrappedBackBuffers[FrameIndex], 1); // // Flush D2D based content on the D3D11On12 device to synchronize with D3D12 content. // m_p11Context->Flush(); return hr; }
// // Generates new graph geometry, which may change every frame. // HRESULT D3D12MemoryManagement::GenerateMemoryGraphGeometry(const RectF& Bounds, UINT GraphSizeMB, ID2D1PathGeometry** ppPathGeometry) { HRESULT hr; ID2D1PathGeometry* pPathGeometry = nullptr; ID2D1GeometrySink* pGeometrySink = nullptr; hr = m_pD2DFactory->CreatePathGeometry(&pPathGeometry); if (FAILED(hr)) { LOG_WARNING("Failed to create path geometry, hr=0x%.8x"); goto cleanup; } hr = pPathGeometry->Open(&pGeometrySink); if (FAILED(hr)) { LOG_WARNING("Failed to open path geometry sink, hr=0x%.8x"); goto cleanup; } { float GraphHeightPadded = GRAPH_HEIGHT * GRAPH_HEIGHT_RATIO / 100; float XStep = GRAPH_WIDTH / GRAPH_SEGMENTS; D2D1_POINT_2F Point; Point.x = Bounds.Left; Point.y = Bounds.Bottom; pGeometrySink->BeginFigure(Point, D2D1_FIGURE_BEGIN_FILLED); for (UINT i = 0; i < NUM_GRAPH_POINTS; ++i) { UINT32 GraphPoint = (i + m_CurrentGraphPoint) % NUM_GRAPH_POINTS; Point.y = Bounds.Bottom - (m_GraphPoints[GraphPoint] / 1024 / 1024) / (float)GraphSizeMB * GraphHeightPadded; pGeometrySink->AddLine(Point); Point.x += XStep; } Point.x = Bounds.Right; Point.y = Bounds.Bottom; pGeometrySink->AddLine(Point); pGeometrySink->EndFigure(D2D1_FIGURE_END_CLOSED); } hr = pGeometrySink->Close(); if (FAILED(hr)) { LOG_ERROR("Failed to close path geometry sink, hr=0x%.8x", hr); goto cleanup; } pGeometrySink->Release(); *ppPathGeometry = pPathGeometry; return S_OK; cleanup: SafeRelease(pGeometrySink); SafeRelease(pPathGeometry); return hr; }
int get_3d_objects_from_server (int nr_objs, const Uint8 *data, int len) { int iobj; int obj_x, obj_y; int offset, nb_left; float x = 0.0f, y = 0.0f, z = 0.0f, rx = 0.0f, ry = 0.0f, rz = 0.0f; char obj_name[128]; int name_len, max_name_len; int id = -1; int all_ok = 1; offset = 0; nb_left = len; for (iobj = 0; iobj < nr_objs; iobj++) { int obj_err = 0; if (nb_left < 14) { // Warn about this error! LOG_WARNING("Incomplete 3D objects list!"); all_ok = 0; break; } obj_x = SDL_SwapLE16 (*((Uint16 *)(&data[offset]))); offset += 2; obj_y = SDL_SwapLE16 (*((Uint16 *)(&data[offset]))); offset += 2; if (obj_x > tile_map_size_x * 6 || obj_y > tile_map_size_y * 6) { // Warn about this error! LOG_WARNING("A 3D object was located OUTSIDE the map!"); offset += 8; obj_err = 1; } else { rx = SwapLEFloat (*((float *)(&data[offset]))); offset += 2; ry = SwapLEFloat (*((float *)(&data[offset]))); offset += 2; rz = SwapLEFloat (*((float *)(&data[offset]))); offset += 2; id = SDL_SwapLE16 (*((Uint16 *)(&data[offset]))); offset += 2; x = 0.5f * obj_x + 0.25f; y = 0.5f * obj_y + 0.25f; z = get_tile_height(obj_x, obj_y); } nb_left -= 12; max_name_len = nb_left > sizeof (obj_name) ? sizeof (obj_name) : nb_left; name_len = safe_snprintf (obj_name, max_name_len, "%s", &data[offset]); if (name_len < 0 || name_len >= sizeof (obj_name)) { // Warn about this error! LOG_WARNING("3D object has invalid or too long file name!"); all_ok = 0; break; } offset += name_len + 1; nb_left -= name_len + 1; if (!obj_err) add_e3d_at_id (id, obj_name, x, y, z, rx, ry, rz, 0, 0, 1.0f, 1.0f, 1.0f, 1); else all_ok = 0; } return all_ok; }
static int str9xpec_write(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count) { struct str9xpec_flash_controller *str9xpec_info = bank->driver_priv; uint32_t dwords_remaining = (count / 8); uint32_t bytes_remaining = (count & 0x00000007); uint32_t bytes_written = 0; uint8_t status; uint32_t check_address = offset; struct jtag_tap *tap; struct scan_field field; uint8_t *scanbuf; int i; int first_sector = 0; int last_sector = 0; tap = str9xpec_info->tap; if (!str9xpec_info->isc_enable) str9xpec_isc_enable(bank); if (!str9xpec_info->isc_enable) return ERROR_FLASH_OPERATION_FAILED; if (offset & 0x7) { LOG_WARNING("offset 0x%" PRIx32 " breaks required 8-byte alignment", offset); return ERROR_FLASH_DST_BREAKS_ALIGNMENT; } for (i = 0; i < bank->num_sectors; i++) { uint32_t sec_start = bank->sectors[i].offset; uint32_t sec_end = sec_start + bank->sectors[i].size; /* check if destination falls within the current sector */ if ((check_address >= sec_start) && (check_address < sec_end)) { /* check if destination ends in the current sector */ if (offset + count < sec_end) check_address = offset + count; else check_address = sec_end; } if ((offset >= sec_start) && (offset < sec_end)) first_sector = i; if ((offset + count >= sec_start) && (offset + count < sec_end)) last_sector = i; } if (check_address != offset + count) return ERROR_FLASH_DST_OUT_OF_BANK; LOG_DEBUG("first_sector: %i, last_sector: %i", first_sector, last_sector); scanbuf = calloc(DIV_ROUND_UP(64, 8), 1); LOG_DEBUG("ISC_PROGRAM"); for (i = first_sector; i <= last_sector; i++) { str9xpec_set_address(bank, str9xpec_info->sector_bits[i]); dwords_remaining = dwords_remaining < (bank->sectors[i].size/8) ? dwords_remaining : (bank->sectors[i].size/8); while (dwords_remaining > 0) { str9xpec_set_instr(tap, ISC_PROGRAM, TAP_IRPAUSE); field.num_bits = 64; field.out_value = (buffer + bytes_written); field.in_value = NULL; jtag_add_dr_scan(tap, 1, &field, TAP_IDLE); /* small delay before polling */ jtag_add_sleep(50); str9xpec_set_instr(tap, ISC_NOOP, TAP_IRPAUSE); do { field.num_bits = 8; field.out_value = NULL; field.in_value = scanbuf; jtag_add_dr_scan(tap, 1, &field, TAP_IRPAUSE); jtag_execute_queue(); status = buf_get_u32(scanbuf, 0, 8); } while (!(status & ISC_STATUS_BUSY)); if ((status & ISC_STATUS_ERROR) != STR9XPEC_ISC_SUCCESS) return ERROR_FLASH_OPERATION_FAILED; /* if ((status & ISC_STATUS_INT_ERROR) != STR9XPEC_ISC_INTFAIL) return ERROR_FLASH_OPERATION_FAILED; */ dwords_remaining--; bytes_written += 8; } } if (bytes_remaining) { uint8_t last_dword[8] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; /* copy the last remaining bytes into the write buffer */ memcpy(last_dword, buffer+bytes_written, bytes_remaining); str9xpec_set_instr(tap, ISC_PROGRAM, TAP_IRPAUSE); field.num_bits = 64; field.out_value = last_dword; field.in_value = NULL; jtag_add_dr_scan(tap, 1, &field, TAP_IDLE); /* small delay before polling */ jtag_add_sleep(50); str9xpec_set_instr(tap, ISC_NOOP, TAP_IRPAUSE); do { field.num_bits = 8; field.out_value = NULL; field.in_value = scanbuf; jtag_add_dr_scan(tap, 1, &field, TAP_IRPAUSE); jtag_execute_queue(); status = buf_get_u32(scanbuf, 0, 8); } while (!(status & ISC_STATUS_BUSY)); if ((status & ISC_STATUS_ERROR) != STR9XPEC_ISC_SUCCESS) return ERROR_FLASH_OPERATION_FAILED; /* if ((status & ISC_STATUS_INT_ERROR) != STR9XPEC_ISC_INTFAIL) return ERROR_FLASH_OPERATION_FAILED; */ } free(scanbuf); str9xpec_isc_disable(bank); return ERROR_OK; }
bool SELFDecrypter::LoadHeaders(bool isElf32) { // Read SCE header. CHECK_ASSERTION(self_f.Seek(0) != -1); sce_hdr.Load(self_f); // Check SCE magic. if (!sce_hdr.CheckMagic()) { LOG_ERROR(LOADER, "SELF: Not a SELF file!"); return false; } // Read SELF header. self_hdr.Load(self_f); // Read the APP INFO. CHECK_ASSERTION(self_f.Seek(self_hdr.se_appinfooff) != -1); app_info.Load(self_f); // Read ELF header. CHECK_ASSERTION(self_f.Seek(self_hdr.se_elfoff) != -1); if (isElf32) elf32_hdr.Load(self_f); else elf64_hdr.Load(self_f); // Read ELF program headers. if (isElf32) { phdr32_arr.clear(); if(elf32_hdr.e_phoff == 0 && elf32_hdr.e_phnum) { LOG_ERROR(LOADER, "SELF: ELF program header offset is null!"); return false; } self_f.Seek(self_hdr.se_phdroff); for(u32 i = 0; i < elf32_hdr.e_phnum; ++i) { phdr32_arr.emplace_back(); phdr32_arr.back().Load(self_f); } } else { phdr64_arr.clear(); if (elf64_hdr.e_phoff == 0 && elf64_hdr.e_phnum) { LOG_ERROR(LOADER, "SELF: ELF program header offset is null!"); return false; } CHECK_ASSERTION(self_f.Seek(self_hdr.se_phdroff) != -1); for (u32 i = 0; i < elf64_hdr.e_phnum; ++i) { phdr64_arr.emplace_back(); phdr64_arr.back().Load(self_f); } } // Read section info. secinfo_arr.clear(); CHECK_ASSERTION(self_f.Seek(self_hdr.se_secinfoff) != -1); for(u32 i = 0; i < ((isElf32) ? elf32_hdr.e_phnum : elf64_hdr.e_phnum); ++i) { secinfo_arr.emplace_back(); secinfo_arr.back().Load(self_f); } // Read SCE version info. CHECK_ASSERTION(self_f.Seek(self_hdr.se_sceveroff) != -1); scev_info.Load(self_f); // Read control info. ctrlinfo_arr.clear(); CHECK_ASSERTION(self_f.Seek(self_hdr.se_controloff) != -1); u32 i = 0; while(i < self_hdr.se_controlsize) { ctrlinfo_arr.emplace_back(); ControlInfo &cinfo = ctrlinfo_arr.back(); cinfo.Load(self_f); i += cinfo.size; } // Read ELF section headers. if (isElf32) { shdr32_arr.clear(); if (elf32_hdr.e_shoff == 0 && elf32_hdr.e_shnum) { LOG_WARNING(LOADER, "SELF: ELF section header offset is null!"); return true; } CHECK_ASSERTION(self_f.Seek(self_hdr.se_shdroff) != -1); for(u32 i = 0; i < elf32_hdr.e_shnum; ++i) { shdr32_arr.emplace_back(); shdr32_arr.back().Load(self_f); } } else { shdr64_arr.clear(); if (elf64_hdr.e_shoff == 0 && elf64_hdr.e_shnum) { LOG_WARNING(LOADER, "SELF: ELF section header offset is null!"); return true; } CHECK_ASSERTION(self_f.Seek(self_hdr.se_shdroff) != -1); for(u32 i = 0; i < elf64_hdr.e_shnum; ++i) { shdr64_arr.emplace_back(); shdr64_arr.back().Load(self_f); } } return true; }
bool fs::file::open(const std::string& filename, u32 mode) { this->close(); g_tls_error = fse::ok; #ifdef _WIN32 DWORD access = 0; switch (mode & (fom::read | fom::write | fom::append)) { case fom::read: access |= GENERIC_READ; break; case fom::read | fom::append: access |= GENERIC_READ; break; case fom::write: access |= GENERIC_WRITE; break; case fom::write | fom::append: access |= FILE_APPEND_DATA; break; case fom::read | fom::write: access |= GENERIC_READ | GENERIC_WRITE; break; case fom::read | fom::write | fom::append: access |= GENERIC_READ | FILE_APPEND_DATA; break; default: { LOG_ERROR(GENERAL, "fs::file::open('%s') failed: neither fom::read nor fom::write specified (0x%x)", filename, mode); return false; } } DWORD disp = 0; switch (mode & (fom::create | fom::trunc | fom::excl)) { case 0: disp = OPEN_EXISTING; break; case fom::create: disp = OPEN_ALWAYS; break; case fom::trunc: disp = TRUNCATE_EXISTING; break; case fom::create | fom::trunc: disp = CREATE_ALWAYS; break; case fom::create | fom::excl: disp = CREATE_NEW; break; case fom::create | fom::excl | fom::trunc: disp = CREATE_NEW; break; } if (!disp || (mode & ~(fom::read | fom::write | fom::append | fom::create | fom::trunc | fom::excl))) { LOG_ERROR(GENERAL, "fs::file::open('%s') failed: unknown mode specified (0x%x)", filename, mode); return false; } m_fd = (std::intptr_t)CreateFileW(to_wchar(filename).get(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, disp, FILE_ATTRIBUTE_NORMAL, NULL); #else int flags = 0; switch (mode & (fom::read | fom::write)) { case fom::read: flags |= O_RDONLY; break; case fom::write: flags |= O_WRONLY; break; case fom::read | fom::write: flags |= O_RDWR; break; default: { LOG_ERROR(GENERAL, "fs::file::open('%s') failed: neither fom::read nor fom::write specified (0x%x)", filename, mode); return false; } } if (mode & fom::append) flags |= O_APPEND; if (mode & fom::create) flags |= O_CREAT; if (mode & fom::trunc) flags |= O_TRUNC; if (mode & fom::excl) flags |= O_EXCL; if (((mode & fom::excl) && !(mode & fom::create)) || (mode & ~(fom::read | fom::write | fom::append | fom::create | fom::trunc | fom::excl))) { LOG_ERROR(GENERAL, "fs::file::open('%s') failed: unknown mode specified (0x%x)", filename, mode); return false; } m_fd = ::open(filename.c_str(), flags, 0666); #endif if (m_fd == null) { LOG_WARNING(GENERAL, "fs::file::open('%s', 0x%x) failed: error 0x%llx", filename, mode, GET_API_ERROR); return false; } return true; }
/* If this fn returns ERROR_TARGET_RESOURCE_NOT_AVAILABLE, then the caller can fall * back to another mechanism that does not require onboard RAM * * Caller should not check for other return values specifically */ static int aduc702x_write_block(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count) { struct target *target = bank->target; uint32_t buffer_size = 7000; struct working_area *write_algorithm; struct working_area *source; uint32_t address = bank->base + offset; struct reg_param reg_params[6]; struct arm_algorithm arm_algo; int retval = ERROR_OK; if (((count%2) != 0) || ((offset%2) != 0)) { LOG_ERROR("write block must be multiple of two bytes in offset & length"); return ERROR_FAIL; } /* parameters: r0 - address of source data (absolute) r1 - number of halfwords to be copied r2 - start address in flash (offset from beginning of flash memory) r3 - exit code r4 - base address of flash controller (0xFFFFF800) registers: r5 - scratch r6 - set to 2, used to write flash command */ static const uint32_t aduc702x_flash_write_code[] = { /* <_start>: */ 0xe3a05008, /* mov r5, #8 ; 0x8 */ 0xe5845004, /* str r5, [r4, #4] */ 0xe3a06002, /* mov r6, #2 ; 0x2 */ /* <next>: */ 0xe1c421b0, /* strh r2, [r4, #16] */ 0xe0d050b2, /* ldrh r5, [r0], #2 */ 0xe1c450bc, /* strh r5, [r4, #12] */ 0xe5c46008, /* strb r6, [r4, #8] */ /* <wait_complete>: */ 0xe1d430b0, /* ldrh r3, [r4] */ 0xe3130004, /* tst r3, #4 ; 0x4 */ 0x1afffffc, /* bne 1001c <wait_complete> */ 0xe2822002, /* add r2, r2, #2 ; 0x2 */ 0xe2511001, /* subs r1, r1, #1 ; 0x1 */ 0x0a000001, /* beq 1003c <done> */ 0xe3130001, /* tst r3, #1 ; 0x1 */ 0x1afffff3, /* bne 1000c <next> */ /* <done>: */ 0xeafffffe /* b 1003c <done> */ }; /* flash write code */ if (target_alloc_working_area(target, sizeof(aduc702x_flash_write_code), &write_algorithm) != ERROR_OK) { LOG_WARNING("no working area available, can't do block memory writes"); return ERROR_TARGET_RESOURCE_NOT_AVAILABLE; } uint8_t code[sizeof(aduc702x_flash_write_code)]; target_buffer_set_u32_array(target, code, ARRAY_SIZE(aduc702x_flash_write_code), aduc702x_flash_write_code); retval = target_write_buffer(target, write_algorithm->address, sizeof(code), code); if (retval != ERROR_OK) return retval; /* memory buffer */ while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK) { buffer_size /= 2; if (buffer_size <= 256) { /* we already allocated the writing code, but failed to get a buffer, *free the algorithm */ target_free_working_area(target, write_algorithm); LOG_WARNING("no large enough working area available, can't do block memory writes"); return ERROR_TARGET_RESOURCE_NOT_AVAILABLE; } } arm_algo.common_magic = ARM_COMMON_MAGIC; arm_algo.core_mode = ARM_MODE_SVC; arm_algo.core_state = ARM_STATE_ARM; init_reg_param(®_params[0], "r0", 32, PARAM_OUT); init_reg_param(®_params[1], "r1", 32, PARAM_OUT); init_reg_param(®_params[2], "r2", 32, PARAM_OUT); init_reg_param(®_params[3], "r3", 32, PARAM_IN); init_reg_param(®_params[4], "r4", 32, PARAM_OUT); while (count > 0) { uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count; retval = target_write_buffer(target, source->address, thisrun_count, buffer); if (retval != ERROR_OK) break; buf_set_u32(reg_params[0].value, 0, 32, source->address); buf_set_u32(reg_params[1].value, 0, 32, thisrun_count/2); buf_set_u32(reg_params[2].value, 0, 32, address); buf_set_u32(reg_params[4].value, 0, 32, 0xFFFFF800); retval = target_run_algorithm(target, 0, NULL, 5, reg_params, write_algorithm->address, write_algorithm->address + sizeof(aduc702x_flash_write_code) - 4, 10000, &arm_algo); if (retval != ERROR_OK) { LOG_ERROR("error executing aduc702x flash write algorithm"); break; } if ((buf_get_u32(reg_params[3].value, 0, 32) & 1) != 1) { /* FIX!!!! what does this mean??? replace w/sensible error message */ LOG_ERROR("aduc702x detected error writing flash"); retval = ERROR_FAIL; break; } buffer += thisrun_count; address += thisrun_count; count -= thisrun_count; } target_free_working_area(target, source); target_free_working_area(target, write_algorithm); destroy_reg_param(®_params[0]); destroy_reg_param(®_params[1]); destroy_reg_param(®_params[2]); destroy_reg_param(®_params[3]); destroy_reg_param(®_params[4]); return retval; }
void SimulationManager::processInstruction(Instruction instructionIn) { Instruction instructionOut; Client* client = NULL; std::string argument = ""; switch (instructionIn.getOpCode()) { case OPCODE_SYNCHRONIZE_CLOCK: argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); client = this->getClients().getClient(argument); instructionOut.setOpCode(OPCODE_SYNCHRONIZE_CLOCK); argument = stringUtilities::unsignedToString(static_cast<unsigned>(SDL_GetTicks())); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_CONNECTED_AT, argument); client->addInstruction(instructionOut); this->lastBroadcast = ""; break; case OPCODE_SIMULATION_SYNCHRONIZE: argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); client = this->getClients().getClient(argument); instructionOut.setOpCode(OPCODE_SIMULATION_SYNCHRONIZE); argument = stringUtilities::unsignedToString(static_cast<unsigned>(SDL_GetTicks())); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_CONNECTED_AT, argument); client->addInstruction(instructionOut); this->lastBroadcast = ""; break; case OPCODE_DISCONNECT_FROM_SIMULATION: argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); client = this->getClients().detachClient(argument); client->stopClient(); delete client; client = NULL; LOG_DEBUG("THE USER " + argument + " DISCONNECTED FROM SIMULATION"); GameView::instance().setDisconnectedPlayer(argument); break; case OPCODE_CLIENT_COMMAND: { LOG_DEBUG("PROCESSING COMMAND FROM CLIENT: " + instructionIn.serialize()); std::string userID = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_COMMAND_DESTINATION); if (argument!="") { GameView::instance().manageMovementUpdate(userID, argument); } argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_COMMAND_STATE); if (argument!="") { GameView::instance().manageAnimationUpdate(userID, argument); } argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_COMMAND_CHANGE_WEAPON); if (argument!="") { GameView::instance().changeWeapon(userID,stringUtilities::stringToUnsigned(argument)); } argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_COMMAND_RESTART_GAME); if (argument == "RESTART GAME") { this->numberOfRestartedClients++; if (numberOfRestartedClients >= GameView::instance().numberOfLoggedInPlayers()) { GameView::instance().restart(); this->numberOfRestartedClients = 0; Instruction instructionOut = this->manageGeneralInitSynchronize(userID); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_RESTART, "0"); this->lastBroadcast = ""; this->getClients().addBroadcast(instructionOut); } } else { if (argument == "RESTART CHARACTER") { Instruction instructionOut; instructionOut.clear(); instructionOut.setOpCode(OPCODE_INIT_SYNCHRONIZE); std::string characterInit = GameView::instance().managePlayerInitialSynch(userID); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_CHARACTER_INIT, characterInit); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_RESTART, "1"); client = this->getClients().getClient(userID); if (client) client->addInstruction(instructionOut); } } break; } case OPCODE_INIT_SYNCHRONIZE: { argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); client = this->getClients().getClient(argument); std::string characterType = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_CHARACTER); GameView::instance().addPlayer(argument, characterType); GameView::instance().startUpdatingPlayer(argument); client->setActive(true); client->addInstruction(this->manageInitSynchronize(argument)); //broadcast for new players instructionOut.clear(); instructionOut.setOpCode(OPCODE_CHARACTERS_SYNCHRONIZE); argument = GameView::instance().manageCharactersPlaying(); instructionOut.insertArgument(INSTRUCTION_ARGUMENT_KEY_CHARACTERS_UPDATE, argument); this->lastBroadcast = ""; this->getClients().addBroadcast(instructionOut); break; } case OPCODE_SIMULATION_UPDATE: break; case OPCODE_CONNECTION_ERROR: { argument = instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID); LOG_ERROR("THE USER " + argument + " DISCONECTED ABRUPTLY FROM SIMULATION"); client = this->getClients().detachClient(argument); if (client != NULL) { client->stopClient(); delete client; client = NULL; } GameView::instance().setDisconnectedPlayer(argument); break; } default: LOG_WARNING("INVALID OPCODE RECEIVED FROM CLIENT " + instructionIn.getArgument(INSTRUCTION_ARGUMENT_KEY_USER_ID)); } }
int vdecRead(void* opaque, u8* buf, int buf_size) { VideoDecoder& vdec = *(VideoDecoder*)opaque; int res = 0; next: if (vdec.reader.size < (u32)buf_size /*&& !vdec.just_started*/) { while (vdec.job.IsEmpty()) { if (Emu.IsStopped()) { LOG_WARNING(HLE, "vdecRead(): aborted"); return 0; } Sleep(1); } switch (vdec.job.Peek().type) { case vdecEndSeq: { buf_size = vdec.reader.size; } break; case vdecDecodeAu: { if (!Memory.CopyToReal(buf, vdec.reader.addr, vdec.reader.size)) { LOG_ERROR(HLE, "vdecRead(): data reading failed (reader.size=0x%x)", vdec.reader.size); Emu.Pause(); return 0; } buf += vdec.reader.size; buf_size -= vdec.reader.size; res += vdec.reader.size; /*Callback cb; cb.SetAddr(vdec.cbFunc); cb.Handle(vdec.id, CELL_VDEC_MSG_TYPE_AUDONE, CELL_OK, vdec.cbArg); cb.Branch(false);*/ vdec.vdecCb->ExecAsCallback(vdec.cbFunc, false, vdec.id, CELL_VDEC_MSG_TYPE_AUDONE, CELL_OK, vdec.cbArg); vdec.job.Pop(vdec.task); vdec.reader.addr = vdec.task.addr; vdec.reader.size = vdec.task.size; //LOG_NOTICE(HLE, "Video AU: size = 0x%x, pts = 0x%llx, dts = 0x%llx", vdec.task.size, vdec.task.pts, vdec.task.dts); } break; default: LOG_ERROR(HLE, "vdecRead(): sequence error (task %d)", vdec.job.Peek().type); return 0; } goto next; } else if (vdec.reader.size < (u32)buf_size) { buf_size = vdec.reader.size; } if (!buf_size) { return res; } else if (!Memory.CopyToReal(buf, vdec.reader.addr, buf_size)) { LOG_ERROR(HLE, "vdecRead(): data reading failed (buf_size=0x%x)", buf_size); Emu.Pause(); return 0; } else { vdec.reader.addr += buf_size; vdec.reader.size -= buf_size; return res + buf_size; } }
/** * \brief Get the mimetype for a package * \param argc the number of command line arguments * \param argv the command line arguments * \return 0 on a successful program execution */ int main(int argc, char *argv[]) { int arg; char *Parm = NULL; char *Path = NULL; int c; char *agent_desc = "Determines mimetype for each file"; int pfile_count = 0; int Agent_pk; int ars_pk = 0; int upload_pk = 0; // the upload primary key int user_pk = 0; char *AgentARSName = "mimetype_ars"; int rv; PGresult *result; char sqlbuf[1024]; int CmdlineFlag = 0; ///< run from command line flag, 1 yes, 0 not char *COMMIT_HASH; char *VERSION; char agent_rev[MAXCMD]; /* initialize the scheduler connection */ fo_scheduler_connect(&argc, argv, &pgConn); /* Process command-line */ while((c = getopt(argc,argv,"iCc:hvV")) != -1) { switch(c) { case 'i': PQfinish(pgConn); return(0); case 'c': /* do nothing with this option */ break; case 'C': CmdlineFlag = 1; break; case 'v': agent_verbose++; break; case 'V': printf("%s", BuildVersion); PQfinish(pgConn); return(0); default: Usage(argv[0]); PQfinish(pgConn); exit(-1); } } COMMIT_HASH = fo_sysconfig("mimetype", "COMMIT_HASH"); VERSION = fo_sysconfig("mimetype", "VERSION"); sprintf(agent_rev, "%s.%s", VERSION, COMMIT_HASH); /* Get the Agent Key from the DB */ Agent_pk = fo_GetAgentKey(pgConn, basename(argv[0]), 0, agent_rev, agent_desc); FMimetype = fopen("/etc/mime.types","rb"); if (!FMimetype) { LOG_WARNING("Unable to open /etc/mime.types\n"); } MagicCookie = magic_open(MAGIC_PRESERVE_ATIME|MAGIC_MIME); if (MagicCookie == NULL) { LOG_FATAL("Failed to initialize magic cookie\n"); PQfinish(pgConn); exit(-1); } if (magic_load(MagicCookie,NULL) != 0) { LOG_FATAL("Failed to load magic file: UnMagic\n"); PQfinish(pgConn); exit(-1); } /* Run from the command-line (for testing) */ for(arg=optind; arg < argc; arg++) { Akey = -1; memset(A,'\0',sizeof(A)); strncpy(A,argv[arg],sizeof(A)); DBCheckMime(A); } /* Run from scheduler! */ if (0 == CmdlineFlag) { user_pk = fo_scheduler_userID(); /* get user_pk for user who queued the agent */ while(fo_scheduler_next()) { /* get piece of information, including upload_pk, others */ Parm = fo_scheduler_current(); if (Parm && Parm[0]) { upload_pk = atoi(Parm); /* Check Permissions */ if (GetUploadPerm(pgConn, upload_pk, user_pk) < PERM_WRITE) { LOG_ERROR("You have no update permissions on upload %d", upload_pk); continue; } /* does ars table exist? * If not, create it. */ rv = fo_tableExists(pgConn, AgentARSName); if (!rv) { rv = fo_CreateARSTable(pgConn, AgentARSName); if (!rv) return(0); } /* check ars table if this is duplicate request*/ memset(sqlbuf, 0, sizeof(sqlbuf)); snprintf(sqlbuf, sizeof(sqlbuf), "select ars_pk from mimetype_ars,agent \ where agent_pk=agent_fk and ars_success=true \ and upload_fk='%d' and agent_fk='%d'", upload_pk, Agent_pk); result = PQexec(pgConn, sqlbuf); if (fo_checkPQresult(pgConn, result, sqlbuf, __FILE__, __LINE__)) exit(-1); if (PQntuples(result) > 0) { PQclear(result); LOG_WARNING("Ignoring requested mimetype analysis of upload %d - Results are already in database.\n",upload_pk); continue; } PQclear(result); /* Record analysis start in mimetype_ars, the mimetype audit trail. */ ars_pk = fo_WriteARS(pgConn, ars_pk, upload_pk, Agent_pk, AgentARSName, 0, 0); /* get all pfile ids on a upload record */ memset(sqlbuf, 0, sizeof(sqlbuf)); snprintf(sqlbuf, sizeof(sqlbuf), "SELECT DISTINCT(pfile_pk) as Akey, pfile_sha1 || '.' || pfile_md5 || '.' || pfile_size AS A FROM uploadtree, pfile WHERE uploadtree.pfile_fk = pfile.pfile_pk AND pfile_mimetypefk is NULL AND upload_fk = '%d';", upload_pk); result = PQexec(pgConn, sqlbuf); if (fo_checkPQresult(pgConn, result, sqlbuf, __FILE__, __LINE__)) exit(-1); pfile_count = PQntuples(result); int i; for(i=0; i < pfile_count; i++) { Akey = atoi(PQgetvalue(result, i, 0)); strncpy(A, PQgetvalue(result, i, 1), sizeof(A)); if (Akey <= 0 || A[0]=='\0') { printf("ERROR: Data is in an unknown format.\n"); PQfinish(pgConn); exit(-1); } /* Process the repository file */ /* Find the path */ Path = fo_RepMkPath("files",A); if (Path && fo_RepExist("files",A)) { /* Get the mimetype! */ DBCheckMime(Path); } else { printf("ERROR pfile %d Unable to process.\n",Akey); printf("LOG pfile %d File '%s' not found.\n",Akey,A); PQfinish(pgConn); exit(-1); } /* Clean up Path memory */ if(Path) { free(Path); Path = NULL; } fo_scheduler_heart(1); } PQclear(result); /* Record analysis success in mimetype_ars. */ if (ars_pk) fo_WriteARS(pgConn, ars_pk, upload_pk, Agent_pk, AgentARSName, 0, 1); } } } /* if run from scheduler */ /* Clean up */ if (FMimetype) fclose(FMimetype); magic_close(MagicCookie); if (DBMime) PQclear(DBMime); if (pgConn) PQfinish(pgConn); /* after cleaning up agent, disconnect from the scheduler, this doesn't return */ fo_scheduler_disconnect(0); return(0); } /* main() */
u32 vdecOpen(VideoDecoder* data) { VideoDecoder& vdec = *data; vdec.vdecCb = &Emu.GetCPU().AddThread(CPU_THREAD_PPU); u32 vdec_id = cellVdec->GetNewId(data); vdec.id = vdec_id; vdec.vdecCb->SetName("Video Decoder[" + std::to_string(vdec_id) + "] Callback"); thread t("Video Decoder[" + std::to_string(vdec_id) + "] Thread", [&]() { LOG_NOTICE(HLE, "Video Decoder thread started"); VdecTask& task = vdec.task; while (true) { if (Emu.IsStopped()) { break; } if (vdec.job.IsEmpty() && vdec.is_running) { Sleep(1); continue; } if (vdec.frames.GetCount() >= 50) { Sleep(1); continue; } if (!vdec.job.Pop(task)) { break; } switch (task.type) { case vdecStartSeq: { // TODO: reset data LOG_WARNING(HLE, "vdecStartSeq:"); vdec.reader.addr = 0; vdec.reader.size = 0; vdec.is_running = true; vdec.just_started = true; } break; case vdecEndSeq: { // TODO: finalize LOG_WARNING(HLE, "vdecEndSeq:"); vdec.vdecCb->ExecAsCallback(vdec.cbFunc, false, vdec.id, CELL_VDEC_MSG_TYPE_SEQDONE, CELL_OK, vdec.cbArg); /*Callback cb; cb.SetAddr(vdec.cbFunc); cb.Handle(vdec.id, CELL_VDEC_MSG_TYPE_SEQDONE, CELL_OK, vdec.cbArg); cb.Branch(true); // ???*/ avcodec_close(vdec.ctx); avformat_close_input(&vdec.fmt); vdec.is_running = false; } break; case vdecDecodeAu: { int err; if (task.mode != CELL_VDEC_DEC_MODE_NORMAL) { LOG_ERROR(HLE, "vdecDecodeAu: unsupported decoding mode(%d)", task.mode); break; } vdec.reader.addr = task.addr; vdec.reader.size = task.size; //LOG_NOTICE(HLE, "Video AU: size = 0x%x, pts = 0x%llx, dts = 0x%llx", task.size, task.pts, task.dts); if (vdec.just_started) { vdec.first_pts = task.pts; vdec.last_pts = task.pts; vdec.first_dts = task.dts; } struct AVPacketHolder : AVPacket { AVPacketHolder(u32 size) { av_init_packet(this); if (size) { data = (u8*)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE); memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE); this->size = size + FF_INPUT_BUFFER_PADDING_SIZE; } else { data = NULL; size = 0; } } ~AVPacketHolder() { av_free(data); //av_free_packet(this); } } au(0); if (vdec.just_started) // deferred initialization { err = avformat_open_input(&vdec.fmt, NULL, av_find_input_format("mpeg"), NULL); if (err) { LOG_ERROR(HLE, "vdecDecodeAu: avformat_open_input() failed"); Emu.Pause(); break; } AVCodec* codec = avcodec_find_decoder(AV_CODEC_ID_H264); // ??? if (!codec) { LOG_ERROR(HLE, "vdecDecodeAu: avcodec_find_decoder() failed"); Emu.Pause(); break; } /*err = avformat_find_stream_info(vdec.fmt, NULL); if (err) { LOG_ERROR(HLE, "vdecDecodeAu: avformat_find_stream_info() failed"); Emu.Pause(); break; } if (!vdec.fmt->nb_streams) { LOG_ERROR(HLE, "vdecDecodeAu: no stream found"); Emu.Pause(); break; }*/ if (!avformat_new_stream(vdec.fmt, codec)) { LOG_ERROR(HLE, "vdecDecodeAu: avformat_new_stream() failed"); Emu.Pause(); break; } vdec.ctx = vdec.fmt->streams[0]->codec; // TODO: check data AVDictionary* opts = nullptr; av_dict_set(&opts, "refcounted_frames", "1", 0); { std::lock_guard<std::mutex> lock(g_mutex_avcodec_open2); // not multithread-safe err = avcodec_open2(vdec.ctx, codec, &opts); } if (err) { LOG_ERROR(HLE, "vdecDecodeAu: avcodec_open2() failed"); Emu.Pause(); break; } //vdec.ctx->flags |= CODEC_FLAG_TRUNCATED; //vdec.ctx->flags2 |= CODEC_FLAG2_CHUNKS; vdec.just_started = false; } bool last_frame = false; while (true) { if (Emu.IsStopped()) { LOG_WARNING(HLE, "vdecDecodeAu: aborted"); return; } last_frame = av_read_frame(vdec.fmt, &au) < 0; if (last_frame) { //break; av_free(au.data); au.data = NULL; au.size = 0; } struct VdecFrameHolder : VdecFrame { VdecFrameHolder() { data = av_frame_alloc(); } ~VdecFrameHolder() { if (data) { av_frame_unref(data); av_frame_free(&data); } } } frame; if (!frame.data) { LOG_ERROR(HLE, "vdecDecodeAu: av_frame_alloc() failed"); Emu.Pause(); break; } int got_picture = 0; int decode = avcodec_decode_video2(vdec.ctx, frame.data, &got_picture, &au); if (decode <= 0) { if (!last_frame && decode < 0) { LOG_ERROR(HLE, "vdecDecodeAu: AU decoding error(0x%x)", decode); } if (!got_picture && vdec.reader.size == 0) break; // video end? } if (got_picture) { u64 ts = av_frame_get_best_effort_timestamp(frame.data); if (ts != AV_NOPTS_VALUE) { frame.pts = ts/* - vdec.first_pts*/; // ??? vdec.last_pts = frame.pts; } else { vdec.last_pts += vdec.ctx->time_base.num * 90000 / (vdec.ctx->time_base.den / vdec.ctx->ticks_per_frame); frame.pts = vdec.last_pts; } //frame.pts = vdec.last_pts; //vdec.last_pts += 3754; frame.dts = (frame.pts - vdec.first_pts) + vdec.first_dts; frame.userdata = task.userData; //LOG_NOTICE(HLE, "got picture (pts=0x%llx, dts=0x%llx)", frame.pts, frame.dts); vdec.frames.Push(frame); // !!!!!!!! frame.data = nullptr; // to prevent destruction vdec.vdecCb->ExecAsCallback(vdec.cbFunc, false, vdec.id, CELL_VDEC_MSG_TYPE_PICOUT, CELL_OK, vdec.cbArg); /*Callback cb; cb.SetAddr(vdec.cbFunc); cb.Handle(vdec.id, CELL_VDEC_MSG_TYPE_PICOUT, CELL_OK, vdec.cbArg); cb.Branch(false);*/ } } vdec.vdecCb->ExecAsCallback(vdec.cbFunc, false, vdec.id, CELL_VDEC_MSG_TYPE_AUDONE, CELL_OK, vdec.cbArg); /*Callback cb; cb.SetAddr(vdec.cbFunc); cb.Handle(vdec.id, CELL_VDEC_MSG_TYPE_AUDONE, CELL_OK, vdec.cbArg); cb.Branch(false);*/ } break; case vdecClose: { vdec.is_finished = true; LOG_NOTICE(HLE, "Video Decoder thread ended"); return; } case vdecSetFrameRate: { LOG_ERROR(HLE, "TODO: vdecSetFrameRate(%d)", task.frc); } break; default: LOG_ERROR(HLE, "Video Decoder thread error: unknown task(%d)", task.type); } } vdec.is_finished = true; LOG_WARNING(HLE, "Video Decoder thread aborted"); }); t.detach(); return vdec_id; }
MojErr ConnectionManagerProxy::UpdateWANStatus(const MojObject& response) { MojErr err; bool wanAvailable = false; bool updated = false; MojInt64 confidence = (MojInt64)ConnectionConfidenceUnknown; MojObject wan; bool found = response.get(_T("wan"), wan); if (found) { updated = m_wanRequirementCore->SetCurrentValue(wan); MojString wanConnected; found = false; err = wan.get(_T("state"), wanConnected, found); MojErrCheck(err); if (!found) { LOG_WARNING(MSGID_WAN_CONN_STATUS_UNKNOWN, 0, "WAN connection status not returned by Connection Manager"); } else if (wanConnected == "connected") { MojString wanNetwork; found = false; err = wan.get(_T("network"), wanNetwork, found); MojErrCheck(err); if (!found) { LOG_WARNING(MSGID_WAN_NW_MODE_UNKNOWN, 0, "WAN network mode not returned by Connection Manager"); } else if (wanNetwork != "unusable") { MojString onInternet; err = wan.get(_T("onInternet"), onInternet, found); MojErrCheck(err); if (onInternet == "yes") { wanAvailable = true; confidence = GetConfidence(wan); } } } } if (wanAvailable) { if (!m_wanRequirementCore->IsMet()) { LOG_DEBUG("WAN connection is now available"); m_wanRequirementCore->Met(); std::for_each(m_wanRequirements.begin(), m_wanRequirements.end(), boost::mem_fn(&Requirement::Met)); } else if (updated) { std::for_each(m_wanRequirements.begin(), m_wanRequirements.end(), boost::mem_fn(&Requirement::Updated)); } } else { if (m_wanRequirementCore->IsMet()) { LOG_DEBUG("WAN connection is no longer available"); m_wanRequirementCore->Unmet(); std::for_each(m_wanRequirements.begin(), m_wanRequirements.end(), boost::mem_fn(&Requirement::Unmet)); } } if (m_wanConfidence != (int)confidence) { m_wanConfidence = (int)confidence; LOG_DEBUG("WAN confidence level changed to %d", m_wanConfidence); UpdateConfidenceRequirements(m_wanConfidenceCores, m_wanConfidenceRequirements, m_wanConfidence); } return MojErrNone; }
/* *luna://com.palm.connectionmanager/getstatus * * { * "isInternetConnectionAvailable" : <bool> * "wifi" : { * "state" : "connected"|"disconnected" * "ipAddress" : <string> * "ssid" : <string> * "bssid" : <string> * } * * "wan" : { * "state" : "connected"|"disconnected" * "ipAddress" : <string> * "network" : "unknown" | "unusable" | "gprs" | "edge" | "umts" ... * (unusable means WAN is available but blocked due to a call) * } * * } */ void ConnectionManagerProxy::ConnectionManagerUpdate(MojServiceMessage *msg, const MojObject& response, MojErr err) { LOG_TRACE("Entering function %s", __FUNCTION__); if (err != MojErrNone) { if (MojoCall::IsPermanentFailure(msg, response, err)) { LOG_WARNING(MSGID_UNSOLVABLE_CONN_MGR_SUBSCR_ERR, 0, "Subscription to Connection Manager experienced an uncorrectable failure: %s", MojoObjectJson(response).c_str()); m_call.reset(); } else { LOG_WARNING(MSGID_CONN_MGR_SUBSCR_ERR, 0, "Subscription to Connection Manager failed, resubscribing: %s",MojoObjectJson(response).c_str()); m_call->Call(); } return; } LOG_DEBUG("Update from Connection Manager: %s", MojoObjectJson(response).c_str()); bool isInternetConnectionAvailable = false; response.get(_T("isInternetConnectionAvailable"), isInternetConnectionAvailable); bool updated = m_internetRequirementCore->SetCurrentValue(response); if (isInternetConnectionAvailable) { if (!m_internetRequirementCore->IsMet()) { LOG_DEBUG("Internet connection is now available"); m_internetRequirementCore->Met(); std::for_each(m_internetRequirements.begin(), m_internetRequirements.end(), boost::mem_fn(&Requirement::Met)); } else if (updated) { std::for_each(m_internetRequirements.begin(), m_internetRequirements.end(), boost::mem_fn(&Requirement::Updated)); } } else { if (m_internetRequirementCore->IsMet()) { LOG_DEBUG("Internet connection is no longer available"); m_internetRequirementCore->Unmet(); std::for_each(m_internetRequirements.begin(), m_internetRequirements.end(), boost::mem_fn(&Requirement::Unmet)); } } UpdateWifiStatus(response); UpdateWANStatus(response); int maxConfidence = (m_wifiConfidence > m_wanConfidence) ? m_wifiConfidence : m_wanConfidence; if (m_internetConfidence != maxConfidence) { m_internetConfidence = maxConfidence; LOG_DEBUG("Internet confidence level changed to %d", m_internetConfidence); UpdateConfidenceRequirements(m_internetConfidenceCores, m_internetConfidenceRequirements, m_internetConfidence); } }
void business_entry(csnet_ss_t* ss, csnet_head_t* head, char* data, int data_len) { LOG_DEBUG(LOG, "new so business_entry: cmd: 0x%x, head len: %d, ctxid: %ld, data len: %d", head->cmd, head->len, head->ctxid, data_len); if (head->cmd == CSNET_NOTICE_REQ) { struct bmin_connect_server* bm = bmin_connect_server_new(ss, head); if (!bm) { LOG_ERROR(LOG, "could not create bmin_connect_server_new"); csnet_module_ref_decrement(CONNTOR->module); return; } bmin_connect_server_req(bm, ss, head, data, data_len); bmin_connect_server_free(bm); csnet_module_ref_decrement(CONNTOR->module); return; } if (head->cmd == csnet_echo_msg_req) { struct bmin_send_msg* bm = bmin_send_msg_new(ss, head); if (!bm) { LOG_ERROR(LOG, "could not create bmin_send_msg"); csnet_module_ref_decrement(CONNTOR->module); return; } int64_t ctxid = bm->ctxid; if (csnet_ctx_insert(CTX, ctxid, bm, sizeof(*bm)) == 0) { LOG_DEBUG(LOG, "insert bm ctxid: %d", ctxid); if (bmin_send_msg_req(bm, ss, head, data, data_len) == -1) { LOG_ERROR(LOG, "bmin_send_msg_req() failed. ctxid: %d", ctxid); csnet_ctx_delete(CTX, ctxid); bmin_send_msg_err(bm, ss, head); bmin_send_msg_free(bm); csnet_module_ref_decrement(CONNTOR->module); } } else { LOG_ERROR(LOG, "could not insert to CTX, ctxid: %ld", ctxid); bmin_send_msg_err(bm, ss, head); bmin_send_msg_free(bm); csnet_module_ref_decrement(CONNTOR->module); } return; } if (head->cmd == csnet_echo_msg_rsp) { struct bmin_send_msg* bm = csnet_ctx_search(CTX, head->ctxid); if (!bm) { LOG_ERROR(LOG, "could not find bm by ctxid: %ld", head->ctxid); csnet_module_ref_decrement(CONNTOR->module); return; } int ret = bm->ops.rsp(bm, head, data, data_len); if (ret == 0) { csnet_ctx_delete(CTX, head->ctxid); } csnet_module_ref_decrement(CONNTOR->module); bmin_send_msg_free(bm); return; } LOG_WARNING(LOG, "unknown cmd: 0x%x", head->cmd); }
static int jtagdp_transaction_endcheck(struct adiv5_dap *dap) { int retval; uint32_t ctrlstat; /* too expensive to call keep_alive() here */ /* Here be dragons! * * It is easy to be in a JTAG clock range where the target * is not operating in a stable fashion. This happens * for a few reasons: * * - the user may construct a simple test case to try to see * if a higher JTAG clock works to eke out more performance. * This simple case may pass, but more complex situations can * fail. * * - The mostly works JTAG clock rate and the complete failure * JTAG clock rate may be as much as 2-4x apart. This seems * to be especially true on RC oscillator driven parts. * * So: even if calling adi_jtag_scan_inout_check_u32() multiple * times here seems to "make things better here", it is just * hiding problems with too high a JTAG clock. * * Note that even if some parts have RCLK/RTCK, that doesn't * mean that RCLK/RTCK is the *correct* rate to run the JTAG * interface at, i.e. RCLK/RTCK rates can be "too high", especially * before the RC oscillator phase is not yet complete. */ /* Post CTRL/STAT read; discard any previous posted read value * but collect its ACK status. */ retval = adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; dap->ack = dap->ack & 0x7; /* common code path avoids calling timeval_ms() */ if (dap->ack != JTAG_ACK_OK_FAULT) { long long then = timeval_ms(); while (dap->ack != JTAG_ACK_OK_FAULT) { if (dap->ack == JTAG_ACK_WAIT) { if ((timeval_ms()-then) > 1000) { LOG_WARNING("Timeout (1000ms) waiting " "for ACK=OK/FAULT " "in JTAG-DP transaction - aborting"); uint8_t ack; int abort_ret = jtag_ap_q_abort(dap, &ack); if (abort_ret != 0) LOG_WARNING("Abort failed : return=%d ack=%d", abort_ret, ack); return ERROR_JTAG_DEVICE_ERROR; } } else { LOG_WARNING("Invalid ACK %#x " "in JTAG-DP transaction", dap->ack); return ERROR_JTAG_DEVICE_ERROR; } retval = adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; dap->ack = dap->ack & 0x7; } } /* REVISIT also STICKYCMP, for pushed comparisons (nyet used) */ /* Check for STICKYERR and STICKYORUN */ if (ctrlstat & (SSTICKYORUN | SSTICKYERR)) { LOG_DEBUG("jtag-dp: CTRL/STAT error, 0x%" PRIx32, ctrlstat); /* Check power to debug regions */ if ((ctrlstat & 0xf0000000) != 0xf0000000) { retval = ahbap_debugport_init(dap); if (retval != ERROR_OK) return retval; } else { uint32_t mem_ap_csw, mem_ap_tar; /* Maybe print information about last intended * MEM-AP access; but not if autoincrementing. * *Real* CSW and TAR values are always shown. */ if (dap->ap_tar_value != (uint32_t) -1) LOG_DEBUG("MEM-AP Cached values: " "ap_bank 0x%" PRIx32 ", ap_csw 0x%" PRIx32 ", ap_tar 0x%" PRIx32, dap->ap_bank_value, dap->ap_csw_value, dap->ap_tar_value); if (ctrlstat & SSTICKYORUN) LOG_ERROR("JTAG-DP OVERRUN - check clock, " "memaccess, or reduce jtag speed"); if (ctrlstat & SSTICKYERR) LOG_ERROR("JTAG-DP STICKY ERROR"); /* Clear Sticky Error Bits */ retval = adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC, DP_CTRL_STAT, DPAP_WRITE, dap->dp_ctrl_stat | SSTICKYORUN | SSTICKYERR, NULL); if (retval != ERROR_OK) return retval; retval = adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; LOG_DEBUG("jtag-dp: CTRL/STAT 0x%" PRIx32, ctrlstat); retval = dap_queue_ap_read(dap, AP_REG_CSW, &mem_ap_csw); if (retval != ERROR_OK) return retval; retval = dap_queue_ap_read(dap, AP_REG_TAR, &mem_ap_tar); if (retval != ERROR_OK) return retval; retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; LOG_ERROR("MEM_AP_CSW 0x%" PRIx32 ", MEM_AP_TAR 0x%" PRIx32, mem_ap_csw, mem_ap_tar); } retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; return ERROR_JTAG_DEVICE_ERROR; } return ERROR_OK; }
TRI_external_status_t TRI_CheckExternalProcess (TRI_external_id_t pid, bool wait) { TRI_external_status_t status; TRI_external_t* external = nullptr; // Just to please the compiler size_t i; TRI_LockMutex(&ExternalProcessesLock); status._status = TRI_EXT_NOT_FOUND; status._exitStatus = 0; for (i = 0; i < ExternalProcesses._length; ++i) { external = static_cast<TRI_external_t*>(TRI_AtVectorPointer(&ExternalProcesses, i)); if (external->_pid == pid._pid) { break; } } if (i == ExternalProcesses._length) { TRI_UnlockMutex(&ExternalProcessesLock); status._errorMessage = std::string("the pid you're looking for is not in our list: ") + triagens::basics::StringUtils::itoa(static_cast<int64_t>(pid._pid)); status._status = TRI_EXT_NOT_FOUND; LOG_WARNING("checkExternal: pid not found: %d", (int) pid._pid); return status; } if (external->_status == TRI_EXT_RUNNING || external->_status == TRI_EXT_STOPPED) { #ifndef _WIN32 TRI_pid_t res; int opts; int loc = 0; if (wait) { opts = WUNTRACED; } else { opts = WNOHANG | WUNTRACED; } res = waitpid(external->_pid, &loc, opts); if (res == 0) { if (wait) { status._errorMessage = std::string("waitpid returned 0 for pid while it shouldn't ") + triagens::basics::StringUtils::itoa(external->_pid); if (WIFEXITED(loc)) { external->_status = TRI_EXT_TERMINATED; external->_exitStatus = WEXITSTATUS(loc); } else if (WIFSIGNALED(loc)) { external->_status = TRI_EXT_ABORTED; external->_exitStatus = WTERMSIG(loc); } else if (WIFSTOPPED(loc)) { external->_status = TRI_EXT_STOPPED; external->_exitStatus = 0; } else { external->_status = TRI_EXT_ABORTED; external->_exitStatus = 0; } } else { external->_exitStatus = 0; } } else if (res == -1) { TRI_set_errno(TRI_ERROR_SYS_ERROR); LOG_WARNING("waitpid returned error for pid %d (%d): %s", (int) external->_pid, (int) wait, TRI_last_error()); status._errorMessage = std::string("waitpid returned error for pid ") + triagens::basics::StringUtils::itoa(external->_pid) + std::string(": ") + std::string(TRI_last_error()); } else if (static_cast<TRI_pid_t>(external->_pid) == static_cast<TRI_pid_t>(res)) { if (WIFEXITED(loc)) { external->_status = TRI_EXT_TERMINATED; external->_exitStatus = WEXITSTATUS(loc); } else if (WIFSIGNALED(loc)) { external->_status = TRI_EXT_ABORTED; external->_exitStatus = WTERMSIG(loc); } else if (WIFSTOPPED(loc)) { external->_status = TRI_EXT_STOPPED; external->_exitStatus = 0; } else { external->_status = TRI_EXT_ABORTED; external->_exitStatus = 0; } } else { LOG_WARNING("unexpected waitpid result for pid %d: %d", (int) external->_pid, (int) res); status._errorMessage = std::string("unexpected waitpid result for pid ") + triagens::basics::StringUtils::itoa(external->_pid) + std::string(": ") + triagens::basics::StringUtils::itoa(res); } #else { char windowsErrorBuf[256]; bool wantGetExitCode = wait; if (wait) { DWORD result; result = WaitForSingleObject(external->_process, INFINITE); if (result == WAIT_FAILED) { FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, windowsErrorBuf, sizeof(windowsErrorBuf), NULL); LOG_WARNING("could not wait for subprocess with PID '%ud': %s", (unsigned int) external->_pid, windowsErrorBuf); status._errorMessage = std::string("could not wait for subprocess with PID '") + triagens::basics::StringUtils::itoa(static_cast<int64_t>(external->_pid)) + std::string("'") + windowsErrorBuf; status._exitStatus = GetLastError(); } } else { DWORD result; result = WaitForSingleObject(external->_process, 0); switch (result) { case WAIT_ABANDONED: wantGetExitCode = true; LOG_WARNING("WAIT_ABANDONED while waiting for subprocess with PID '%ud'", (unsigned int)external->_pid); break; case WAIT_OBJECT_0: /// this seems to be the exit case - want getExitCodeProcess here. wantGetExitCode = true; break; case WAIT_TIMEOUT: // success - everything went well. external->_exitStatus = 0; break; case WAIT_FAILED: FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, windowsErrorBuf, sizeof(windowsErrorBuf), NULL); LOG_WARNING("could not wait for subprocess with PID '%ud': %s", (unsigned int)external->_pid, windowsErrorBuf); status._errorMessage = std::string("could not wait for subprocess with PID '") + triagens::basics::StringUtils::itoa(static_cast<int64_t>(external->_pid)) + std::string("'") + windowsErrorBuf; status._exitStatus = GetLastError(); default: wantGetExitCode = true; LOG_WARNING("unexpected status while waiting for subprocess with PID '%ud'", (unsigned int)external->_pid); } } if (wantGetExitCode) { DWORD exitCode = STILL_ACTIVE; if (!GetExitCodeProcess(external->_process, &exitCode)) { LOG_WARNING("exit status could not be determined for PID '%ud'", (unsigned int)external->_pid); status._errorMessage = std::string("exit status could not be determined for PID '") + triagens::basics::StringUtils::itoa(static_cast<int64_t>(external->_pid)) + std::string("'"); } else { if (exitCode == STILL_ACTIVE) { external->_exitStatus = 0; } else if (exitCode > 255) { // this should be one of our signals which we mapped... external->_status = TRI_EXT_ABORTED; external->_exitStatus = exitCode - 255; } else { external->_status = TRI_EXT_TERMINATED; external->_exitStatus = exitCode; } } } else { external->_status = TRI_EXT_RUNNING; } } #endif } else { LOG_WARNING("unexpected process status %d: %d", (int) external->_status, (int) external->_exitStatus); status._errorMessage = std::string("unexpected process status ") + triagens::basics::StringUtils::itoa(external->_status) + std::string(": ") + triagens::basics::StringUtils::itoa(external->_exitStatus); } status._status = external->_status; status._exitStatus = external->_exitStatus; // Do we have to free our data? if (external->_status != TRI_EXT_RUNNING && external->_status != TRI_EXT_STOPPED) { TRI_RemoveVectorPointer(&ExternalProcesses, i); FreeExternal(external); } TRI_UnlockMutex(&ExternalProcessesLock); return status; }
void App::interruptHandler(int sigNum) { LOG_WARNING("Received INT signal, stopping the frontend."); pipeline_->stop(); //frontend_->stop(); }
bool SELFDecrypter::DecryptNPDRM(u8 *metadata, u32 metadata_size) { aes_context aes; ControlInfo *ctrl = NULL; u8 npdrm_key[0x10]; u8 npdrm_iv[0x10]; // Parse the control info structures to find the NPDRM control info. for(unsigned int i = 0; i < ctrlinfo_arr.size(); i++) { if (ctrlinfo_arr[i].type == 3) { ctrl = &ctrlinfo_arr[i]; break; } } // Check if we have a valid NPDRM control info structure. // If not, the data has no NPDRM layer. if (!ctrl) { LOG_WARNING(LOADER, "SELF: No NPDRM control info found!"); return true; } u8 klicensee_key[0x10]; memcpy(klicensee_key, key_v.GetKlicenseeKey(), 0x10); // Use klicensee if available. if (klicensee_key != NULL) memcpy(npdrm_key, klicensee_key, 0x10); if (ctrl->npdrm.license == 1) // Network license. { LOG_ERROR(LOADER, "SELF: Can't decrypt network NPDRM!"); return false; } else if (ctrl->npdrm.license == 2) // Local license. { // Try to find a RAP file to get the key. if (!GetKeyFromRap(ctrl->npdrm.content_id, npdrm_key)) { LOG_ERROR(LOADER, "SELF: Can't find RAP file for NPDRM decryption!"); return false; } } else if (ctrl->npdrm.license == 3) // Free license. { // Use the NP_KLIC_FREE. memcpy(npdrm_key, NP_KLIC_FREE, 0x10); } else { LOG_ERROR(LOADER, "SELF: Invalid NPDRM license type!"); return false; } // Decrypt our key with NP_KLIC_KEY. aes_setkey_dec(&aes, NP_KLIC_KEY, 128); aes_crypt_ecb(&aes, AES_DECRYPT, npdrm_key, npdrm_key); // IV is empty. memset(npdrm_iv, 0, 0x10); // Use our final key to decrypt the NPDRM layer. aes_setkey_dec(&aes, npdrm_key, 128); aes_crypt_cbc(&aes, AES_DECRYPT, metadata_size, npdrm_iv, metadata, metadata); return true; }
void App::termHandler(int sigNum) { LOG_WARNING("TERM signal received, exiting."); exit(EXIT_TERM_RECEIVED); }
static int avr32_ap7k_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution) { struct avr32_ap7k_common *ap7k = target_to_ap7k(target); struct breakpoint *breakpoint = NULL; uint32_t resume_pc; int retval; if (target->state != TARGET_HALTED) { LOG_WARNING("target not halted"); return ERROR_TARGET_NOT_HALTED; } if (!debug_execution) { target_free_all_working_areas(target); /* avr32_ap7k_enable_breakpoints(target); avr32_ap7k_enable_watchpoints(target); */ } /* current = 1: continue on current pc, otherwise continue at <address> */ if (!current) { #if 0 if (retval != ERROR_OK) return retval; #endif } resume_pc = buf_get_u32(ap7k->core_cache->reg_list[AVR32_REG_PC].value, 0, 32); avr32_ap7k_restore_context(target); /* the front-end may request us not to handle breakpoints */ if (handle_breakpoints) { /* Single step past breakpoint at current address */ if ((breakpoint = breakpoint_find(target, resume_pc))) { LOG_DEBUG("unset breakpoint at 0x%8.8" PRIx32 "", breakpoint->address); #if 0 avr32_ap7k_unset_breakpoint(target, breakpoint); avr32_ap7k_single_step_core(target); avr32_ap7k_set_breakpoint(target, breakpoint); #endif } } #if 0 /* enable interrupts if we are running */ avr32_ap7k_enable_interrupts(target, !debug_execution); /* exit debug mode */ mips_ejtag_exit_debug(ejtag_info); #endif retval = avr32_ocd_clearbits(&ap7k->jtag, AVR32_OCDREG_DC, OCDREG_DC_DBR); if (retval != ERROR_OK) return retval; retval = avr32_jtag_exec(&ap7k->jtag, RETD); if (retval != ERROR_OK) return retval; target->debug_reason = DBG_REASON_NOTHALTED; /* registers are now invalid */ register_cache_invalidate(ap7k->core_cache); if (!debug_execution) { target->state = TARGET_RUNNING; target_call_event_callbacks(target, TARGET_EVENT_RESUMED); LOG_DEBUG("target resumed at 0x%" PRIx32 "", resume_pc); } else { target->state = TARGET_DEBUG_RUNNING; target_call_event_callbacks(target, TARGET_EVENT_DEBUG_RESUMED); LOG_DEBUG("target debug resumed at 0x%" PRIx32 "", resume_pc); } return ERROR_OK; }
static void CompactifyDatafile (TRI_sim_collection_t* sim, TRI_voc_fid_t fid) { TRI_datafile_t* df; bool ok; size_t n; size_t i; // locate the datafile TRI_READ_LOCK_DATAFILES_SIM_COLLECTION(sim); n = sim->base.base._datafiles._length; for (i = 0; i < n; ++i) { df = sim->base.base._datafiles._buffer[i]; if (df->_fid == fid) { break; } } TRI_READ_UNLOCK_DATAFILES_SIM_COLLECTION(sim); if (i == n) { return; } // now compactify the datafile LOG_DEBUG("starting to compactify datafile '%s'", df->_filename); ok = TRI_IterateDatafile(df, Compactifier, sim, false); if (! ok) { LOG_WARNING("failed to compactify the datafile '%s'", df->_filename); return; } // wait for the journals to sync WaitCompactSync(sim, df); // remove the datafile from the list of datafiles TRI_WRITE_LOCK_DATAFILES_SIM_COLLECTION(sim); n = sim->base.base._datafiles._length; for (i = 0; i < n; ++i) { df = sim->base.base._datafiles._buffer[i]; if (df->_fid == fid) { TRI_RemoveVectorPointer(&sim->base.base._datafiles, i); break; } } TRI_WRITE_UNLOCK_DATAFILES_SIM_COLLECTION(sim); if (i == n) { LOG_WARNING("failed to locate the datafile '%lu'", (unsigned long) df->_fid); return; } // add a deletion marker to the result set container TRI_CreateBarrierDatafile(&sim->base._barrierList, df, RemoveDatafileCallback, &sim->base.base); }
int RTRDemo::init(const std::string& configFile) { // Init log file std::string logFile = "log/" + createTimeStamp() + ".log"; if (!CLogger::initLogFile(logFile)) { LOG_WARNING("Failed to create log file at %s.", logFile.c_str()); } m_debugInfo = std::make_shared<CDebugInfo>(); CLogger::addListener(m_debugInfo.get()); if (!m_config.load(configFile)) { LOG_WARNING("Failed to load config file %s, starting with default settings.", configFile.c_str()); } // Create window for rendering if (!initWindow()) { LOG_ERROR("Failed to initialize window."); return 1; } m_inputProvider = std::make_shared<CGlfwInputProvider>(m_window->getGlfwHandle()); // Create resource manager m_resourceManager.reset(createResourceManager()); if (m_resourceManager == nullptr) { LOG_ERROR("Failed to initialize resource manager."); return 1; } // Create animation world m_animationWorld = std::make_shared<CAnimationWorld>(); // Graphics resource manager, listens to resource manager CGraphicsResourceManager* manager = new CGraphicsResourceManager; m_resourceManager->addResourceListener(manager); m_graphicsResourceManager.reset(manager); // Create renderer if (!initRenderer()) { LOG_ERROR("Failed to initialize renderer."); return 1; } if (!initScene()) { LOG_ERROR("Failed to initialize scene."); return 1; } m_camera = std::make_shared<CFirstPersonCamera>( glm::vec3(0.5f, 0.f, 0.5f), glm::vec3(0.f, 0.f, 1.f), glm::vec3(0.f, 1.f, 0.f), 45.f, 4.f / 3.f, 0.01f, 1000.f); m_cameraController = std::make_shared<CCameraController>(); m_cameraController->setCamera(m_camera); m_cameraController->setInputProvider(m_inputProvider.get()); m_debugInfoDisplay = std::make_shared<CDebugInfoDisplay>(m_resourceManager); m_window->addListener(m_cameraController.get()); return 0; }
/* FIX! make service return error instead of invoking exit() */ int add_service(char *name, const char *port, int max_connections, new_connection_handler_t new_connection_handler, input_handler_t input_handler, connection_closed_handler_t connection_closed_handler, void *priv) { struct service *c, **p; int so_reuseaddr_option = 1; c = malloc(sizeof(struct service)); c->name = strdup(name); c->port = strdup(port); c->max_connections = 1; /* Only TCP/IP ports can support more than one connection */ c->fd = -1; c->connections = NULL; c->new_connection = new_connection_handler; c->input = input_handler; c->connection_closed = connection_closed_handler; c->priv = priv; c->next = NULL; long portnumber; if (strcmp(c->port, "pipe") == 0) c->type = CONNECTION_STDINOUT; else { char *end; portnumber = strtol(c->port, &end, 0); if (!*end && (parse_long(c->port, &portnumber) == ERROR_OK)) { c->portnumber = portnumber; c->type = CONNECTION_TCP; } else c->type = CONNECTION_PIPE; } if (c->type == CONNECTION_TCP) { c->max_connections = max_connections; c->fd = socket(AF_INET, SOCK_STREAM, 0); if (c->fd == -1) { LOG_ERROR("error creating socket: %s", strerror(errno)); exit(-1); } setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&so_reuseaddr_option, sizeof(int)); socket_nonblock(c->fd); memset(&c->sin, 0, sizeof(c->sin)); c->sin.sin_family = AF_INET; c->sin.sin_addr.s_addr = INADDR_ANY; c->sin.sin_port = htons(c->portnumber); if (bind(c->fd, (struct sockaddr *)&c->sin, sizeof(c->sin)) == -1) { LOG_ERROR("couldn't bind to socket: %s", strerror(errno)); exit(-1); } #ifndef _WIN32 int segsize = 65536; setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG, &segsize, sizeof(int)); #endif int window_size = 128 * 1024; /* These setsockopt()s must happen before the listen() */ setsockopt(c->fd, SOL_SOCKET, SO_SNDBUF, (char *)&window_size, sizeof(window_size)); setsockopt(c->fd, SOL_SOCKET, SO_RCVBUF, (char *)&window_size, sizeof(window_size)); if (listen(c->fd, 1) == -1) { LOG_ERROR("couldn't listen on socket: %s", strerror(errno)); exit(-1); } } else if (c->type == CONNECTION_STDINOUT) { c->fd = fileno(stdin); #ifdef _WIN32 /* for win32 set stdin/stdout to binary mode */ if (_setmode(_fileno(stdout), _O_BINARY) < 0) LOG_WARNING("cannot change stdout mode to binary"); if (_setmode(_fileno(stdin), _O_BINARY) < 0) LOG_WARNING("cannot change stdin mode to binary"); if (_setmode(_fileno(stderr), _O_BINARY) < 0) LOG_WARNING("cannot change stderr mode to binary"); #else socket_nonblock(c->fd); #endif } else if (c->type == CONNECTION_PIPE) { #ifdef _WIN32 /* we currenty do not support named pipes under win32 * so exit openocd for now */ LOG_ERROR("Named pipes currently not supported under this os"); exit(1); #else /* Pipe we're reading from */ c->fd = open(c->port, O_RDONLY | O_NONBLOCK); if (c->fd == -1) { LOG_ERROR("could not open %s", c->port); exit(1); } #endif } /* add to the end of linked list */ for (p = &services; *p; p = &(*p)->next) ; *p = c; return ERROR_OK; }
// // LoadAssets goes through the texture asset directory and attempts to load all files // as images for the application to stream in. Texture assets are located in // Assets\Textures, relative to the sample binary. // HRESULT D3D12MemoryManagement::LoadAssets() { WCHAR FileName[MAX_PATH]; GetWorkingDir(FileName, MAX_PATH); wcscat_s(FileName, L"Assets\\Textures\\*"); WCHAR* pEnd = FileName + wcslen(FileName) - 1; WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile(FileName, &ffd); if (INVALID_HANDLE_VALUE == hFind) { // // Does the directory not exist? // LOG_ERROR("Failed to load texture assets"); return E_FAIL; } UINT ImageIndex = 0; do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // // Ignore directories. // continue; } else { // // Try to create the resource from the file. This may not be a valid image file, // and if this is the case, we will fail to create the resource, and continue // with the next file. // *pEnd = L'\0'; wcscat_s(FileName, ffd.cFileName); Resource* pResource = nullptr; HRESULT hr = CreateResource(FileName, &pResource); if (FAILED(hr)) { continue; } Image Img; InitializeImage(&Img, pResource, ImageIndex); m_Images.push_back(Img); ++ImageIndex; } } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); for (UINT GeneratedImage = 0; GeneratedImage < MAX_GENERATED_IMAGES; ++GeneratedImage) { Resource* pResource = nullptr; HRESULT hr = CreateResource(L"", &pResource); if (FAILED(hr)) { LOG_WARNING("Unable to generate image %d", GeneratedImage); continue; } Image Img; InitializeImage(&Img, pResource, ImageIndex); m_Images.push_back(Img); ++ImageIndex; } return S_OK; }
int parse_cmdline_args(struct command_context_s *cmd_ctx, int argc, char *argv[]) { int c; char command_buffer[128]; while (1) { /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long(argc, argv, "hvd::l:f:s:c:p", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 'h': /* --help | -h */ help_flag = 1; break; case 'v': /* --version | -v */ version_flag = 1; break; case 'f': /* --file | -f */ { snprintf(command_buffer, 128, "script {%s}", optarg); add_config_command(command_buffer); break; } case 's': /* --search | -s */ add_script_search_dir(optarg); break; case 'd': /* --debug | -d */ if (optarg) snprintf(command_buffer, 128, "debug_level %s", optarg); else snprintf(command_buffer, 128, "debug_level 3"); command_run_line(cmd_ctx, command_buffer); break; case 'l': /* --log_output | -l */ if (optarg) { snprintf(command_buffer, 128, "log_output %s", optarg); command_run_line(cmd_ctx, command_buffer); } break; case 'c': /* --command | -c */ if (optarg) { add_config_command(optarg); } break; case 'p': /* --pipe | -p */ #if BUILD_ECOSBOARD == 1 /* pipes unsupported on hosted platforms */ LOG_WARNING("pipes not supported on this platform"); #else server_use_pipes = 1; #endif break; } } if (help_flag) { LOG_OUTPUT("Open On-Chip Debugger\n(c) 2005-2008 by Dominic Rath\n\n"); LOG_OUTPUT("--help | -h\tdisplay this help\n"); LOG_OUTPUT("--version | -v\tdisplay OpenOCD version\n"); LOG_OUTPUT("--file | -f\tuse configuration file <name>\n"); LOG_OUTPUT("--search | -s\tdir to search for config files and scripts\n"); LOG_OUTPUT("--debug | -d\tset debug level <0-3>\n"); LOG_OUTPUT("--log_output | -l\tredirect log output to file <name>\n"); LOG_OUTPUT("--command | -c\trun <command>\n"); LOG_OUTPUT("--pipe | -p\tuse pipes for gdb communication\n"); exit(-1); } if (version_flag) { /* Nothing to do, version gets printed automatically. */ // It is not an error to request the VERSION number. exit(0); } return ERROR_OK; }
void D3D12MemoryManagement::RenderMemoryGraph() { static const D2D1_COLOR_F BackgroundColor = { 0.1f, 0.1f, 0.1f, 0.85f }; static const D2D1_COLOR_F BorderColor = { 0.75f, 0.75f, 0.75f, 0.75f }; static const D2D1_COLOR_F NotchColor = { 0.75f, 0.75f, 0.75f, 0.4f }; static const D2D1_COLOR_F UsageColor = { 0.5f, 0.5f, 0.0f, 0.75f }; static const D2D1_COLOR_F CurrentUsageColor = { 0.8f, 0.8f, 0.0f, 1.0f }; static const D2D1_COLOR_F CurrentBudgetColor = { 0.8f, 0.0f, 0.0f, 1.0f }; HRESULT hr; DXGI_QUERY_VIDEO_MEMORY_INFO LocalInfo = GetLocalVideoMemoryInfo(); UINT64 Tick = GetTickCount64(); if (Tick - m_LastGraphTick > 1000 / GRAPH_SEGMENTS * 10) { // Record data point. m_GraphPoints[m_CurrentGraphPoint % NUM_GRAPH_POINTS] = LocalInfo.CurrentUsage; ++m_CurrentGraphPoint; m_LastGraphTick = Tick; } // // Get largest sample in point set for an upper bound. // UINT64 LargestSeenValue = 0; for (UINT i = 0; i < NUM_GRAPH_POINTS; ++i) { if (m_GraphPoints[i] > LargestSeenValue) { LargestSeenValue = m_GraphPoints[i]; } } if (LargestSeenValue == 0) { return; } // // Calculate graph scale values. // UINT LargestSeenValueMB = (UINT)(LargestSeenValue / 1024 / 1024); // // Graph is scaled by powers of 2 scaled by 100, e.g. 100, 200, 400, 800, ... // Use the power of two value to scale the graph accordingly. // DWORD ScaleIndex; DWORD Result = BitScanReverse(&ScaleIndex, LargestSeenValueMB / 100); if (Result == 0) { ScaleIndex = 0; } else { ++ScaleIndex; } // // Graph only goes up GRAPH_HEIGHT_RATIO % to the top to leave a little bit of room // at the top of the graph. Purely aesthetics. // UINT GraphSizeMB = (1 << ScaleIndex) * 100; float GraphHeightPadded = GRAPH_HEIGHT * GRAPH_HEIGHT_RATIO / 100; float GraphPaddingTop = GRAPH_HEIGHT - GraphHeightPadded; // // Calculate the graph rectangle bounds. // RectF GraphDest; GraphDest.Right = m_WindowWidth - GRAPH_PADDING; GraphDest.Left = GraphDest.Right - GRAPH_WIDTH; GraphDest.Top = GRAPH_PADDING; GraphDest.Bottom = GraphDest.Top + GRAPH_HEIGHT; // // Try to create the brush and path geometry for the graph. If either fails, we cannot render the graph. // ComPtr<ID2D1SolidColorBrush> pBrush; ComPtr<ID2D1PathGeometry> pPathGeometry; hr = m_pD2DContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush); if (FAILED(hr)) { LOG_WARNING("Failed to create solid color brush for rendering UI, hr=0x.8x", hr); return; } hr = GenerateMemoryGraphGeometry(GraphDest, GraphSizeMB, &pPathGeometry); if (FAILED(hr)) { LOG_WARNING("Failed to generate path geometry for memory graph, hr=0x.8x", hr); return; } // // Render memory graph border and background. // { pBrush->SetColor(BackgroundColor); m_pD2DContext->FillRectangle((D2D1_RECT_F&)GraphDest, pBrush.Get()); pBrush->SetColor(BorderColor); m_pD2DContext->DrawRectangle((D2D1_RECT_F&)GraphDest, pBrush.Get(), 2); } // // Render the path geometry for the graph. // { pBrush->SetColor(UsageColor); m_pD2DContext->FillGeometry(pPathGeometry.Get(), pBrush.Get()); } // // Render the notches on the graph for reference values. // { pBrush->SetColor(NotchColor); UINT SizePerNotch = GraphSizeMB / GRAPH_NOTCH_COUNT; for (int i = 0; i < GRAPH_NOTCH_COUNT + 1; ++i) { wchar_t Text[32]; swprintf_s(Text, _TRUNCATE, L"%dMB", SizePerNotch * i); D2D1_RECT_F TextRect; TextRect.left = GraphDest.Left - 100; TextRect.top = GraphDest.Top + GraphPaddingTop + (GRAPH_NOTCH_COUNT - i) * (GraphHeightPadded / GRAPH_NOTCH_COUNT) - 10; TextRect.right = GraphDest.Left - 5; TextRect.bottom = TextRect.top + 20; m_pD2DContext->DrawTextW( Text, (UINT)wcslen(Text), m_pTextFormat, &TextRect, m_pTextBrush); // // Label 0MB, but do not draw the line. // if (i > 0) { D2D1_POINT_2F Point0 = { GraphDest.Left, TextRect.top + 10 }; D2D1_POINT_2F Point1 = { GraphDest.Right, TextRect.top + 10 }; m_pD2DContext->DrawLine(Point0, Point1, pBrush.Get(), 1); } } } // // Draw current usage/budget line and value. // { // // Usage // { pBrush->SetColor(CurrentUsageColor); float Top = GraphDest.Bottom - (LocalInfo.CurrentUsage / 1024 / 1024) / (float)GraphSizeMB * GraphHeightPadded; D2D1_POINT_2F Point0 = { GraphDest.Left, Top }; D2D1_POINT_2F Point1 = { GraphDest.Right, Top }; m_pD2DContext->DrawLine(Point0, Point1, pBrush.Get(), 1); wchar_t Text[32]; swprintf_s(Text, L"%dMB", (UINT)(LocalInfo.CurrentUsage / 1024 / 1024)); D2D1_RECT_F TextRect; TextRect.left = Point0.x; TextRect.top = Top; TextRect.right = Point1.x - 5; TextRect.bottom = Top + 10; m_pD2DContext->DrawTextW( Text, (UINT)wcslen(Text), m_pTextFormat, &TextRect, m_pTextBrush); } // // Budget // { pBrush->SetColor(CurrentBudgetColor); float Top = max(GraphDest.Bottom - (LocalInfo.Budget / 1024 / 1024) / (float)GraphSizeMB * GraphHeightPadded, GraphDest.Top); D2D1_POINT_2F Point0 = { GraphDest.Left, Top }; D2D1_POINT_2F Point1 = { GraphDest.Right, Top }; m_pD2DContext->DrawLine(Point0, Point1, pBrush.Get(), 1); wchar_t Text[32]; swprintf_s(Text, L"%dMB", (UINT)(LocalInfo.Budget / 1024 / 1024)); D2D1_RECT_F TextRect; TextRect.left = Point0.x; TextRect.top = Top - 10; TextRect.right = Point1.x - 5; TextRect.bottom = Top; m_pD2DContext->DrawTextW( Text, (UINT)wcslen(Text), m_pTextFormat, &TextRect, m_pTextBrush); } } }
static int X_io_error_handler(Display *dpy) { LOG_WARNING("fatal error, connection to X server lost? cleaning up\n"); cleanup(); return 0; }
bool D3D12GSRender::LoadProgram() { if (m_PSO != nullptr) return true; if (!m_cur_fragment_prog) { LOG_WARNING(RSX, "LoadProgram: m_cur_shader_prog == NULL"); return false; } m_cur_fragment_prog->ctrl = m_shader_ctrl; if (!m_cur_vertex_prog) { LOG_WARNING(RSX, "LoadProgram: m_cur_vertex_prog == NULL"); return false; } D3D12PipelineProperties prop = {}; switch (m_draw_mode - 1) { case GL_POINTS: prop.Topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; break; case GL_LINES: case GL_LINE_LOOP: case GL_LINE_STRIP: prop.Topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; break; case GL_TRIANGLES: case GL_TRIANGLE_STRIP: case GL_TRIANGLE_FAN: prop.Topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; break; case GL_QUADS: case GL_QUAD_STRIP: case GL_POLYGON: default: // LOG_ERROR(RSX, "Unsupported primitive type"); prop.Topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; break; } static D3D12_BLEND_DESC CD3D12_BLEND_DESC = { FALSE, FALSE, { FALSE,FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL, } }; prop.Blend = CD3D12_BLEND_DESC; if (m_set_blend) { prop.Blend.RenderTarget[0].BlendEnable = true; if (m_set_blend_mrt1) prop.Blend.RenderTarget[1].BlendEnable = true; if (m_set_blend_mrt2) prop.Blend.RenderTarget[2].BlendEnable = true; if (m_set_blend_mrt3) prop.Blend.RenderTarget[3].BlendEnable = true; } if (m_set_blend_equation) { prop.Blend.RenderTarget[0].BlendOp = getBlendOp(m_blend_equation_rgb); prop.Blend.RenderTarget[0].BlendOpAlpha = getBlendOp(m_blend_equation_alpha); if (m_set_blend_mrt1) { prop.Blend.RenderTarget[1].BlendOp = getBlendOp(m_blend_equation_rgb); prop.Blend.RenderTarget[1].BlendOpAlpha = getBlendOp(m_blend_equation_alpha); } if (m_set_blend_mrt2) { prop.Blend.RenderTarget[2].BlendOp = getBlendOp(m_blend_equation_rgb); prop.Blend.RenderTarget[2].BlendOpAlpha = getBlendOp(m_blend_equation_alpha); } if (m_set_blend_mrt3) { prop.Blend.RenderTarget[3].BlendOp = getBlendOp(m_blend_equation_rgb); prop.Blend.RenderTarget[3].BlendOpAlpha = getBlendOp(m_blend_equation_alpha); } } if (m_set_blend_sfactor && m_set_blend_dfactor) { prop.Blend.RenderTarget[0].SrcBlend = getBlendFactor(m_blend_sfactor_rgb); prop.Blend.RenderTarget[0].DestBlend = getBlendFactor(m_blend_dfactor_rgb); prop.Blend.RenderTarget[0].SrcBlendAlpha = getBlendFactorAlpha(m_blend_sfactor_alpha); prop.Blend.RenderTarget[0].DestBlendAlpha = getBlendFactorAlpha(m_blend_dfactor_alpha); if (m_set_blend_mrt1) { prop.Blend.RenderTarget[1].SrcBlend = getBlendFactor(m_blend_sfactor_rgb); prop.Blend.RenderTarget[1].DestBlend = getBlendFactor(m_blend_dfactor_rgb); prop.Blend.RenderTarget[1].SrcBlendAlpha = getBlendFactorAlpha(m_blend_sfactor_alpha); prop.Blend.RenderTarget[1].DestBlendAlpha = getBlendFactorAlpha(m_blend_dfactor_alpha); } if (m_set_blend_mrt2) { prop.Blend.RenderTarget[2].SrcBlend = getBlendFactor(m_blend_sfactor_rgb); prop.Blend.RenderTarget[2].DestBlend = getBlendFactor(m_blend_dfactor_rgb); prop.Blend.RenderTarget[2].SrcBlendAlpha = getBlendFactorAlpha(m_blend_sfactor_alpha); prop.Blend.RenderTarget[2].DestBlendAlpha = getBlendFactorAlpha(m_blend_dfactor_alpha); } if (m_set_blend_mrt3) { prop.Blend.RenderTarget[3].SrcBlend = getBlendFactor(m_blend_sfactor_rgb); prop.Blend.RenderTarget[3].DestBlend = getBlendFactor(m_blend_dfactor_rgb); prop.Blend.RenderTarget[3].SrcBlendAlpha = getBlendFactorAlpha(m_blend_sfactor_alpha); prop.Blend.RenderTarget[3].DestBlendAlpha = getBlendFactorAlpha(m_blend_dfactor_alpha); } } if (m_set_logic_op) { prop.Blend.RenderTarget[0].LogicOpEnable = true; prop.Blend.RenderTarget[0].LogicOp = getLogicOp(m_logic_op); } if (m_set_blend_color) { // glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a); // checkForGlError("glBlendColor"); } switch (m_surface_depth_format) { case 0: break; case CELL_GCM_SURFACE_Z16: prop.DepthStencilFormat = DXGI_FORMAT_D16_UNORM; break; case CELL_GCM_SURFACE_Z24S8: prop.DepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; break; default: LOG_ERROR(RSX, "Bad depth format! (%d)", m_surface_depth_format); assert(0); } switch (m_surface_color_format) { case CELL_GCM_SURFACE_A8R8G8B8: prop.RenderTargetsFormat = DXGI_FORMAT_R8G8B8A8_UNORM; break; case CELL_GCM_SURFACE_F_W16Z16Y16X16: prop.RenderTargetsFormat = DXGI_FORMAT_R16G16B16A16_FLOAT; break; } switch (m_surface_color_target) { case CELL_GCM_SURFACE_TARGET_0: case CELL_GCM_SURFACE_TARGET_1: prop.numMRT = 1; break; case CELL_GCM_SURFACE_TARGET_MRT1: prop.numMRT = 2; break; case CELL_GCM_SURFACE_TARGET_MRT2: prop.numMRT = 3; break; case CELL_GCM_SURFACE_TARGET_MRT3: prop.numMRT = 4; break; default: LOG_ERROR(RSX, "Bad surface color target: %d", m_surface_color_target); } prop.DepthStencil.DepthEnable = m_set_depth_test; prop.DepthStencil.DepthWriteMask = m_depth_mask ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO; prop.DepthStencil.DepthFunc = getCompareFunc(m_depth_func); prop.DepthStencil.StencilEnable = m_set_stencil_test; prop.DepthStencil.StencilReadMask = m_stencil_func_mask; prop.DepthStencil.StencilWriteMask = m_stencil_mask; prop.DepthStencil.FrontFace.StencilPassOp = getStencilOp(m_stencil_zpass); prop.DepthStencil.FrontFace.StencilDepthFailOp = getStencilOp(m_stencil_zfail); prop.DepthStencil.FrontFace.StencilFailOp = getStencilOp(m_stencil_fail); prop.DepthStencil.FrontFace.StencilFunc = getCompareFunc(m_stencil_func); if (m_set_two_sided_stencil_test_enable) { prop.DepthStencil.BackFace.StencilFailOp = getStencilOp(m_back_stencil_fail); prop.DepthStencil.BackFace.StencilFunc = getCompareFunc(m_back_stencil_func); prop.DepthStencil.BackFace.StencilPassOp = getStencilOp(m_back_stencil_zpass); prop.DepthStencil.BackFace.StencilDepthFailOp = getStencilOp(m_back_stencil_zfail); } else { prop.DepthStencil.BackFace.StencilPassOp = getStencilOp(m_stencil_zpass); prop.DepthStencil.BackFace.StencilDepthFailOp = getStencilOp(m_stencil_zfail); prop.DepthStencil.BackFace.StencilFailOp = getStencilOp(m_stencil_fail); prop.DepthStencil.BackFace.StencilFunc = getCompareFunc(m_stencil_func); } // Sensible default value static D3D12_RASTERIZER_DESC CD3D12_RASTERIZER_DESC = { D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_NONE, FALSE, D3D12_DEFAULT_DEPTH_BIAS, D3D12_DEFAULT_DEPTH_BIAS_CLAMP, D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, TRUE, FALSE, FALSE, 0, D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF, }; prop.Rasterization = CD3D12_RASTERIZER_DESC; switch (m_set_cull_face) { case CELL_GCM_FRONT: prop.Rasterization.CullMode = D3D12_CULL_MODE_FRONT; break; case CELL_GCM_BACK: prop.Rasterization.CullMode = D3D12_CULL_MODE_BACK; break; default: prop.Rasterization.CullMode = D3D12_CULL_MODE_NONE; break; } switch (m_front_face) { case CELL_GCM_CW: prop.Rasterization.FrontCounterClockwise = FALSE; break; case CELL_GCM_CCW: prop.Rasterization.FrontCounterClockwise = TRUE; break; } if (m_set_color_mask) { UINT8 mask = 0; mask |= m_color_mask_r ? D3D12_COLOR_WRITE_ENABLE_RED : 0; mask |= m_color_mask_g ? D3D12_COLOR_WRITE_ENABLE_GREEN : 0; mask |= m_color_mask_b ? D3D12_COLOR_WRITE_ENABLE_BLUE : 0; mask |= m_color_mask_a ? D3D12_COLOR_WRITE_ENABLE_ALPHA : 0; for (unsigned i = 0; i < prop.numMRT; i++) prop.Blend.RenderTarget[i].RenderTargetWriteMask = mask; } prop.IASet = m_IASet; m_PSO = m_cachePSO.getGraphicPipelineState(m_cur_vertex_prog, m_cur_fragment_prog, prop, std::make_pair(m_device.Get(), m_rootSignatures)); return m_PSO != nullptr; }
int cellMsgDialogOpen2(u32 type, vm::ptr<const char> msgString, vm::ptr<CellMsgDialogCallback> callback, u32 userData, u32 extParam) { cellSysutil->Warning("cellMsgDialogOpen2(type=0x%x, msgString_addr=0x%x, callback_addr=0x%x, userData=0x%x, extParam=0x%x)", type, msgString.addr(), callback.addr(), userData, extParam); //type |= CELL_MSGDIALOG_TYPE_PROGRESSBAR_SINGLE | CELL_MSGDIALOG_TYPE_BG_INVISIBLE; //type |= CELL_MSGDIALOG_TYPE_BUTTON_TYPE_YESNO | CELL_MSGDIALOG_TYPE_DEFAULT_CURSOR_NO; MsgDialogState old = msgDialogNone; if (!g_msg_dialog_state.compare_exchange_strong(old, msgDialogOpen)) { return CELL_SYSUTIL_ERROR_BUSY; } g_msg_dialog_wait_until = get_system_time() + 31536000000000ull; // some big value switch (type & CELL_MSGDIALOG_TYPE_PROGRESSBAR) { case CELL_MSGDIALOG_TYPE_PROGRESSBAR_DOUBLE: g_msg_dialog_progress_bar_count = 2; break; case CELL_MSGDIALOG_TYPE_PROGRESSBAR_SINGLE: g_msg_dialog_progress_bar_count = 1; break; default: g_msg_dialog_progress_bar_count = 0; break; // ??? } std::string msg = msgString.get_ptr(); thread t("MsgDialog thread", [type, msg, callback, userData, extParam]() { switch (type & CELL_MSGDIALOG_TYPE_SE_TYPE) { case CELL_MSGDIALOG_TYPE_SE_TYPE_NORMAL: LOG_WARNING(TTY, "%s", msg.c_str()); break; case CELL_MSGDIALOG_TYPE_SE_TYPE_ERROR: LOG_ERROR(TTY, "%s", msg.c_str()); break; } switch (type & CELL_MSGDIALOG_TYPE_SE_MUTE) // TODO { case CELL_MSGDIALOG_TYPE_SE_MUTE_OFF: break; case CELL_MSGDIALOG_TYPE_SE_MUTE_ON: break; } g_msg_dialog_status = CELL_MSGDIALOG_BUTTON_NONE; volatile bool m_signal = false; CallAfter([type, msg, &m_signal]() { if (Emu.IsStopped()) return; MsgDialogCreate(type, msg.c_str(), g_msg_dialog_status); m_signal = true; }); while (!m_signal) { if (Emu.IsStopped()) { cellSysutil->Warning("MsgDialog thread aborted"); return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } while (g_msg_dialog_state == msgDialogOpen || (s64)(get_system_time() - g_msg_dialog_wait_until) < 0) { if (Emu.IsStopped()) { g_msg_dialog_state = msgDialogAbort; break; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } if (callback && (g_msg_dialog_state != msgDialogAbort)) { Emu.GetCallbackManager().Register([callback, userData]() -> s32 { callback((s32)g_msg_dialog_status, userData); return CELL_OK; }); } CallAfter([]() { MsgDialogDestroy(); g_msg_dialog_state = msgDialogNone; }); }); t.detach(); return CELL_OK; }