As the title mentioned, I'm confusing about where is the debug info stored in .Framework file.
I googled for serval days, what I gots are:
Framework binary compiled by debug mode will include a debug info segment, to indicate the symbol location. Release mode compiling will move it to a dSYM file.
But, what confused me is, I build a framework with ninja, and it doesn't generate dSYM file. Meanwhile I can't find the symbol location by dwarfdump command or MachOView app. As Regards strings command can get some relative file path results, like ../../flutter/fml/memory/task_runner_checker.cc.
Here dwarfdump prints:
Flutter.framework/Flutter: file format Mach-O arm64
.debug_info contents:
Here is my questions:
When I triggered breakpoint at somewhere in the framework, the source code still shows. Why?
When I run lldb command, it shows:
(lldb) image lookup -a $pc --verbose
Address: Flutter[0x0000000001964f18] (Flutter.__TEXT.__text + 26604184)
Summary: Flutter`dart::BootstrapNatives::DN_LoadLibraryFromTypedData(dart::Thread*, dart::Zone*, dart::NativeArguments*) + 44 [inlined] dart::NativeArguments::NativeArgAt(int) const at object.cc:537
Flutter`dart::BootstrapNatives::DN_LoadLibraryFromTypedData(dart::Thread*, dart::Zone*, dart::NativeArguments*) + 44 [inlined] dart::DN_HelperLoadLibraryFromTypedData(dart::Isolate*, dart::Thread*, dart::Zone*, dart::NativeArguments*) at object.cc:534
Flutter`dart::BootstrapNatives::DN_LoadLibraryFromTypedData(dart::Thread*, dart::Zone*, dart::NativeArguments*) + 44 at object.cc:534
Module: file = "/Users/xx/Library/Developer/Xcode/DerivedData/XXX-ddigzjlnuypwnydlawevfrkmdsov/Build/Products/Debug-iphoneos/XXX.app/Frameworks/Flutter.framework/Flutter", arch = "arm64"
CompileUnit: id = {0x00000000}, file = "/Users/xx/Documents/workspace/aion/flutter_engine/src/third_party/dart/runtime/lib/object.cc", language = "c++14"
Function: id = {0x7d40006244d}, name = "dart::BootstrapNatives::DN_LoadLibraryFromTypedData(dart::Thread*, dart::Zone*, dart::NativeArguments*)", mangled = "_ZN4dart16BootstrapNatives27DN_LoadLibraryFromTypedDataEPNS_6ThreadEPNS_4ZoneEPNS_15NativeArgumentsE", range = [0x0000000117310eec-0x0000000117311490)
FuncType: id = {0x7d40006244d}, byte-size = 0, decl = bootstrap_natives.h:507, compiler_type = "class dart::ObjectPtr (class dart::Thread *, class dart::Zone *, class dart::NativeArguments *)"
Blocks: id = {0x7d40006244d}, range = [0x117310eec-0x117311490)
id = {0x7d40006249b}, ranges = [0x117310f18-0x1173113e0)[0x117311404-0x117311490), name = "DN_HelperLoadLibraryFromTypedData", decl = object.cc:534, mangled = _ZN4dartL33DN_HelperLoadLibraryFromTypedDataEPNS_7IsolateEPNS_6ThreadEPNS_4ZoneEPNS_15NativeArgumentsE, demangled = dart::DN_HelperLoadLibraryFromTypedData(dart::Isolate*, dart::Thread*, dart::Zone*, dart::NativeArguments*)
id = {0x7d40006253a}, range = [0x117310f18-0x117310f24), name = "NativeArgAt", decl = native_arguments.h:129, mangled = _ZNK4dart15NativeArguments11NativeArgAtEi, demangled = dart::NativeArguments::NativeArgAt(int) const
LineEntry: [0x0000000117310f18-0x0000000117310f24): /Users/xx/Documents/workspace/xxx/flutter_engine/src/third_party/dart/runtime/vm/native_arguments.h:132:14
Symbol: id = {0x0013fd0f}, range = [0x0000000117310eec-0x0000000117311490), name="dart::BootstrapNatives::DN_LoadLibraryFromTypedData(dart::Thread*, dart::Zone*, dart::NativeArguments*)", mangled="_ZN4dart16BootstrapNatives27DN_LoadLibraryFromTypedDataEPNS_6ThreadEPNS_4ZoneEPNS_15NativeArgumentsE"
Variable: id = {0x7d400062553}, name = "this", type = "const dart::NativeArguments *", location = DW_OP_reg20 W20, decl =
Variable: id = {0x7d40006255c}, name = "index", type = "int", location = <decoding error> 00 00 00, decl = native_arguments.h:129
Variable: id = {0x7d4000624a8}, name = "isolate", type = "dart::Isolate *", location = , decl = object.cc:534
Variable: id = {0x7d4000624ad}, name = "thread", type = "dart::Thread *", location = , decl = object.cc:534
Variable: id = {0x7d4000624b2}, name = "zone", type = "dart::Zone *", location = DW_OP_reg19 W19, decl = object.cc:534
Variable: id = {0x7d4000624bb}, name = "arguments", type = "dart::NativeArguments *", location = DW_OP_reg20 W20, decl = object.cc:534
Variable: id = {0x7d4000624c4}, name = "program", type = "unique_ptr<dart::xx_kernel::Program, std::__1::default_delete<dart::xx_kernel::Program> >", location = DW_OP_breg31 WSP+64, decl = object.cc:556
Variable: id = {0x7d400062468}, name = "thread", type = "dart::Thread *", location = DW_OP_reg24 W24, decl = object.cc:534
Variable: id = {0x7d400062479}, name = "zone", type = "dart::Zone *", location = DW_OP_reg19 W19, decl = object.cc:534
Variable: id = {0x7d40006248a}, name = "arguments", type = "dart::NativeArguments *", location = DW_OP_reg20 W20, decl = object.cc:534
So, where the lldb get Compile Unit and LineEntry outputs?
Debug information on Darwin systems exists in one of two places: In the .o files, and later after dsymutil is run to create a .dSYM, it exists in the .dSYM bundle, all collected together, relocated to the actual binary's addresses.
This was a build-link-debug performance enhancement. Linking all of the debug information -- updating all the symbol addresses, copying it all around -- is very slow, so leaving the debug information in the .o files for this common iterative development cycle, and having the debugger locate the .o files and update the addresses of the functions internally, allows for rapid development.
Leaving all of the debug information in the .o files requires that they all be present, of course! And at the same file paths. So it is not good when you need to move a binary between computers, or save it for later debugging. For these cases, you link the debug information with dsymutil and you get a .dSYM bundle.
Related
I try to perform a test run for an XDP BPF program. The BPF program uses the bpf_xdp_adjust_meta() helper, to adjust the meta data.
I tried:
to run bpf_prog_test_run()
to run bpf_prog_test_run_xattr()
1. bpf_prog_test_run()
(The first time I tried my bpf program's debug messages told me that adjusting the data_meta field failed.) Now it can adjust the data_meta, but the iph.ihl field is apparently not set to 5.
2. bpf_prog_test_xattr()
This always returns -1, so something failed.
The Code
packet:
struct ipv4_packet pkt_v4 = {
.eth.h_proto = __bpf_constant_htons(ETH_P_IP),
.iph.ihl = 5,
.iph.daddr = __bpf_constant_htonl(33554442),
.iph.saddr = __bpf_constant_htonl(50331658),
.iph.protocol = IPPROTO_TCP,
.iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
.tcp.urg_ptr = 123,
.tcp.doff = 5,
};
test attribute:
__u32 size, retval, duration;
char data_out[128];
struct xdp_md ctx_in, ctx_out;
struct bpf_prog_test_run_attr test_attr = {
.prog_fd = prog_fd,
.repeat = 100,
.data_in = &pkt_v4,
.data_size_in = sizeof(&pkt_v4),
.data_out = &data_out,
.data_size_out = sizeof(data_out),
.ctx_in = &ctx_in,
.ctx_size_in = sizeof(ctx_in),
.ctx_out = &ctx_out,
.ctx_size_out = sizeof(ctx_out),
.retval = &retval,
.duration = &duration,
};
test execution:
bpf_prog_test_run(main_prog_fd, 1, &pkt_v4, sizeof(pkt_v4), &data_out, &size, &retval, &duration) -> iph.ihl field is 0.
bpf_prog_test_run_xattr(&test_attr) -> returns -1.
Note
The program was already successfully attached to the hook point of a real network interface and ran as intended. I just replaced the code that attaches the program to the hook point with the above code for testing.
The struct ipv4_packet pkt_v4 was not packed.
When I replace __packed with __attribute__ ((__packed__)) it works.
For information what happens without packing, see for example this question.
Basically the compiler adds padding bytes which leads to the fields in the packet being in different places than expected.
I modified quantstrat demo bee and tried to run optimization on indicator parameters. However, I have tried to simplify optimization as much as I can, but I still got the same error as following:
error calling combine function:
<simpleError in fun(result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9, result.10): attempt to select less than one element>
Error in .subset2(x, i, exact = exact) : subscript out of bounds
my sessionInfo output:
R version 3.2.4 (2016-03-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] parallel stats graphics grDevices utils
[6] datasets methods base
other attached packages:
[1] doMC_1.3.4
[2] iterators_1.0.8
[3] lubridate_1.5.0
[4] dplyr_0.4.3
[5] quantstrat_0.9.1739
[6] foreach_1.4.3
[7] blotter_0.9.1741
[8] PerformanceAnalytics_1.4.4000
[9] FinancialInstrument_1.2.0
[10] quantmod_0.4-5
[11] TTR_0.23-1
[12] xts_0.9-7
[13] zoo_1.7-12
loaded via a namespace (and not attached):
[1] Rcpp_0.12.3 magrittr_1.5
[3] lattice_0.20-33 R6_2.1.2
[5] stringr_1.0.0 tools_3.2.4
[7] grid_3.2.4 DBI_0.3.1
[9] htmltools_0.3 yaml_2.1.13
[11] lazyeval_0.1.10 assertthat_0.1
[13] digest_0.6.9 codetools_0.2-14
[15] rsconnect_0.4.1.4 rmarkdown_0.9.5
[17] stringi_1.0-1 compiler_3.2.4
Here is my code and data is to be download from here. Could anyone help me to figure out where goes wrong? thanks
####################################################################
#### Load packages
#####################################################################
library(dplyr)
suppressMessages(require(quantstrat))
####################################################################
#### remove objects
########################################################################
rm(list = ls(all.names = T))
if(!exists(".instrument")) .instrument <<- new.env()
if(!exists(".blotter")) .blotter <<- new.env()
if(!exists(".strategy")) .strategy <- new.env()
########################################################################
#### DEFINE VARIABLES or parameters
########################################################################
initDate = "2000-01-01"
symbol.st = 'CYB_DAY'
portf.st = 'bug'
acct.st = 'colony'
strat.st = 'bee'
initEq = 100000
nFast = 10
nSlow = 30
nSd = 1
########################################################################
#### GET DATA
###############################################################
# set your working directory where the data is stored
setwd("/Users/Natsume/Documents/data_exploration_r/data")
currency('USD') # initiate currency
stock(symbol.st ,currency='USD', multiplier=1) # initiate stock
getSymbols(Symbols = symbol.st, src = "csv")
initPortf(
portf.st,
symbol.st,
initDate=initDate) # initiate portfolio
initAcct(
acct.st,
portf.st,
initEq=initEq,
initDate=initDate) # initiate account
initOrders(
portf.st,
initDate=initDate ) # initiate order_book
bee = strategy(strat.st) # create strategy object
addPosLimit(
portfolio=portf.st,
symbol=symbol.st,
timestamp=initDate,
maxpos=300, longlevels = 3) # only trade in one direction once
bee <- add.indicator(
strategy = strat.st,
name = 'BBands', # TA name
arguments = list(HLC=quote(HLC(mktdata)),
n=nSlow,
sd=nSd),
label = 'BBand')
#### SMA column
bee <- add.indicator(
strategy = strat.st,
name = 'SMA', # TA name
arguments = list(x=quote(Cl(mktdata)),
n=nFast),
label = 'MA' )
bee <- add.signal(
strategy = strat.st,
name = 'sigCrossover',
arguments = list(columns=c('MA','dn'),
relationship='lt'),
label = 'MA.lt.dn')
#### SMA cross over upperBand
bee <- add.signal(
strategy = strat.st,
name = 'sigCrossover',
arguments = list(columns=c('MA','up'),
relationship='gt'),
label = 'MA.gt.up')
bee <- add.rule(
strategy = strat.st,
name = 'ruleSignal',
arguments = list(sigcol = 'MA.gt.up',
sigval = TRUE,
replace = F,
orderqty = 100,
ordertype = 'market',
# one of "market","limit","stoplimit", "stoptrailing", or "iceberg"
orderside = 'long',
osFUN = 'osMaxPos'),
type = 'enter',
label = 'EnterLONG')
#### exitLong when SMA cross under LowerBand
bee <- add.rule(
strategy = strat.st,
name = 'ruleSignal',
arguments = list(sigcol = 'MA.lt.dn',
sigval = TRUE,
replace = F,
orderqty = 'all',
ordertype = 'market',
orderside = 'long'),
type = 'exit',
label = 'ExitLONG')
#### enterShort when SMA cross under LowerBand
bee <- add.rule(
strategy = strat.st,
name = 'ruleSignal',
arguments = list(sigcol = 'MA.lt.dn',
sigval = TRUE,
replace = F,
orderqty = -100,
ordertype = 'market',
orderside = 'short',
osFUN = 'osMaxPos'),
type = 'enter',
label = 'EnterSHORT')
#### exitShort when SMA cross over upperBand
bee <- add.rule(
strategy = strat.st,
name = 'ruleSignal',
arguments = list(sigcol = 'MA.gt.up',
sigval = TRUE,
replace = F,
orderqty = 'all',
ordertype = 'market',
orderside = 'short'),
type = 'exit',
label = 'ExitSHORT')
applyStrategy(
strat.st,
portf.st,
prefer='Open', # why prefer='Open'
verbose=T)
updatePortf(
portf.st) #,
updateAcct(
acct.st) # ,
updateEndEq(
Account = acct.st)#,
### User Set up pf parameter ranges to test
.nFastList = 5:13
.nSlowList = 10:40
.nSdList = 1:3
# number of random samples of the parameter distribution to use for random run
.nsamples = 10
add.distribution(strat.st,
paramset.label = 'SMA_BBparams',
component.type = 'indicator',
component.label = 'BBand', #this is the label given to the indicator in the strat
variable = list(n = .nSlowList),
label = 'BBandMA'
)
add.distribution(strat.st,
paramset.label = 'SMA_BBparams',
component.type = 'indicator',
component.label = 'BBand', #this is the label given to the indicator in the strat
variable = list(sd = .nSdList),
label = 'BBandSD'
)
add.distribution(strat.st,
paramset.label = 'SMA_BBparams',
component.type = 'indicator',
component.label = 'MA', #this is the label given to the indicator in the strat
variable = list(n = .nFastList),
label = 'MAn'
)
add.distribution.constraint(strat.st,
paramset.label = 'SMA_BBparams',
distribution.label.1 = 'BBandMA',
distribution.label.2 = 'MAn',
operator = '>',
label = 'BBandMA>MAn'
)
### parallel computing to speed up
if( Sys.info()['sysname'] == "Windows" )
{
library(doParallel)
# registerDoParallel(cores=detectCores())
registerDoSEQ()
} else {
library(doMC)
registerDoMC(cores=detectCores())
}
results <- apply.paramset(strat.st,
paramset.label='SMA_BBparams',
portfolio.st=portf.st,
account.st=acct.st,
nsamples= .nsamples, # take all options
#.nsamples, only take 10 samples
verbose=TRUE)
results$tradeStats %>% View()
After you make global search and replace operation in Xcode it adds xcLanguageSpecificationIdentifier and lineEnding to every manipulated file entry in *.pbxproj files in the form of e.g.:
036B04CB1B2AE8A70010F649 /* MyClass.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MyClass.m; sourceTree = "<group>"; };
to:
036B04CB1B2AE8A70010F649 /* MyClass.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; path = MyClass.m; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.objc; };
What is it for?
Does it improve something like search performance?
If yes, how can I generate it for other files without making search and replace operation?
If no, how can I prevent Xcode from creating such things?
I think xcLanguageSpecificationIdentifier is just a temporary indication from Xcode 6 with Swift's comming; and you can find it in your project.pbxproj if you write mixture code with Swift and objc.
For example, you have ProfileVC.h and ProfileVC.m, then you delete ProfileVC.h and rename ProfileVC.m to ProfileVC.swift (and rewrite it in Swift), in your projectName.xcodeproject/project.pbxproj, some line change from
49E89AB31C3D4494006C95BB /* ProfileVC.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ProfileVC.m; sourceTree = "<group>";};
to
49E89AB31C3D4494006C95BB /* ProfileVC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = ProfileVC.swift; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.objc; };
However, in this situation, code in ProfileVC.swift seems not correctly colored, and code completion is broken. I delete the part xcLanguageSpecificationIdentifier = xcode.lang.objc; and everything goes quite OK.
I need to access all memory of a running process in my local Windows 7-64bit. I am new to winapi.
Here is my problem; Whenever I try to Open a process and reads its memory, I get Access is Denied error.
I searched and found something. It is said that If I run the main process as Administrator and use PROCESS_ALL_ACCESS on OpenProcess, I would have enough right to do it as it is said. OK, I did it. but nothing is changed. On reading memory, I still get Access is Denied.
So, I kept searching and found another thing which is enabling SeDebugPrivilege. I have also done that but nothing is changed. I still get the error.
I've read the quest and his answer here;
Windows Vista/Win7 Privilege Problem: SeDebugPrivilege & OpenProcess .
But as I said, I am really new to winapi. I could not solve my problem yet. Is there anything which which I need to configure in my local operating system?
Here is my Python code with pywin32;
from _ctypes import byref, sizeof, Structure
from ctypes import windll, WinError, c_buffer, c_void_p, create_string_buffer
from ctypes.wintypes import *
import win32security
import win32api
import gc
import ntsecuritycon
from struct import Struct
from win32con import PROCESS_ALL_ACCESS
from struct import calcsize
MEMORY_STATES = {0x1000: "MEM_COMMIT", 0x10000: "MEM_FREE", 0x2000: "MEM_RESERVE"}
MEMORY_PROTECTIONS = {0x10: "PAGE_EXECUTE", 0x20: "PAGE_EXECUTE_READ", 0x40: "PAGEEXECUTE_READWRITE",
0x80: "PAGE_EXECUTE_WRITECOPY", 0x01: "PAGE_NOACCESS", 0x04: "PAGE_READWRITE",
0x08: "PAGE_WRITECOPY"}
MEMORY_TYPES = {0x1000000: "MEM_IMAGE", 0x40000: "MEM_MAPPED", 0x20000: "MEM_PRIVATE"}
class MEMORY_BASIC_INFORMATION(Structure):
_fields_ = [
("BaseAddress", c_void_p),
("AllocationBase", c_void_p),
("AllocationProtect", DWORD),
("RegionSize", UINT),
("State", DWORD),
("Protect", DWORD),
("Type", DWORD)
]
class SYSTEM_INFO(Structure):
_fields_ = [("wProcessorArchitecture", WORD),
("wReserved", WORD),
("dwPageSize", DWORD),
("lpMinimumApplicationAddress", DWORD),
("lpMaximumApplicationAddress", DWORD),
("dwActiveProcessorMask", DWORD),
("dwNumberOfProcessors", DWORD),
("dwProcessorType", DWORD),
("dwAllocationGranularity", DWORD),
("wProcessorLevel", WORD),
("wProcessorRevision", WORD)]
class PyMEMORY_BASIC_INFORMATION:
def __init__(self, MBI):
self.MBI = MBI
self.set_attributes()
def set_attributes(self):
self.BaseAddress = self.MBI.BaseAddress
self.AllocationBase = self.MBI.AllocationBase
self.AllocationProtect = MEMORY_PROTECTIONS.get(self.MBI.AllocationProtect, self.MBI.AllocationProtect)
self.RegionSize = self.MBI.RegionSize
self.State = MEMORY_STATES.get(self.MBI.State, self.MBI.State)
# self.Protect = self.MBI.Protect # uncomment this and comment next line if you want to do a bitwise check on Protect.
self.Protect = MEMORY_PROTECTIONS.get(self.MBI.Protect, self.MBI.Protect)
self.Type = MEMORY_TYPES.get(self.MBI.Type, self.MBI.Type)
ASSUME_ALIGNMENT = True
class TARGET:
"""Given a ctype (initialized or not) this coordinates all the information needed to read, write and compare."""
def __init__(self, ctype):
self.alignment = 1
self.ctype = ctype
# size of target data
self.size = sizeof(ctype)
self.type = ctype._type_
# get the format type needed for struct.unpack/pack.
while hasattr(self.type, "_type_"):
self.type = self.type._type_
# string_buffers and char arrays have _type_ 'c'
# but that makes it slightly slower to unpack
# so swap is for 's'.
if self.type == "c":
self.type = "s"
# calculate byte alignment. this speeds up scanning substantially
# because we can read and compare every alignment bytes
# instead of every single byte.
# although if we are scanning for a string the alignment is defaulted to 1 \
# (im not sure if this is correct).
elif ASSUME_ALIGNMENT:
# calc alignment
divider = 1
for i in xrange(4):
divider *= 2
if not self.size % divider:
self.alignment = divider
# size of target ctype.
self.type_size = calcsize(self.type)
# length of target / array length.
self.length = self.size / self.type_size
self.value = getattr(ctype, "raw", ctype.value)
# the format string used for struct.pack/unpack.
self.format = str(self.length) + self.type
# efficient packer / unpacker for our own format.
self.packer = Struct(self.format)
def get_packed(self):
"""Gets the byte representation of the ctype value for use with WriteProcessMemory."""
return self.packer.pack(self.value)
def __str__(self):
return str(self.ctype)[:10] + "..." + " <" + str(self.value)[:10] + "..." + ">"
class Memory(object):
def __init__(self, process_handle, target):
self._process_handle = process_handle
self._target = target
self.found = []
self.__scann_process()
def __scann_process(self):
"""scans a processes pages for the target value."""
si = SYSTEM_INFO()
psi = byref(si)
windll.kernel32.GetSystemInfo(psi)
base_address = si.lpMinimumApplicationAddress
max_address = si.lpMaximumApplicationAddress
page_address = base_address
while page_address < max_address:
page_address = self.__scan_page(page_address)
if len(self.found) >= 60000000:
print("[Warning] Scan ended early because too many addresses were found to hold the target data.")
break
gc.collect()
return self.found
def __scan_page(self, page_address):
"""Scans the entire page for TARGET instance and returns the next page address and found addresses."""
information = self.VirtualQueryEx(page_address)
base_address = information.BaseAddress
region_size = information.RegionSize
next_region = base_address + region_size
size = self._target.size
target_value = self._target.value
step = self._target.alignment
unpacker = self._target.packer.unpack
if information.Type != "MEM_PRIVATE" or \
region_size < size or \
information.State != "MEM_COMMIT" or \
information.Protect not in ["PAGE_EXECUTE_READ", "PAGEEXECUTE_READWRITE", "PAGE_READWRITE"]:
return next_region
page_bytes = self.ReadMemory(base_address, region_size)
for i in xrange(0, (region_size - size), step):
partial = page_bytes[i:i + size]
if unpacker(partial)[0] == target_value:
self.found.append(base_address + i)
del page_bytes # free the buffer
return next_region
def ReadMemory(self, address, size):
cbuffer = c_buffer(size)
success = windll.kernel32.ReadProcessMemory(
self._process_handle,
address,
cbuffer,
size,
0)
assert success, "ReadMemory Failed with success == %s and address == %s and size == %s.\n%s" % (
success, address, size, WinError(win32api.GetLastError()))
return cbuffer.raw
def VirtualQueryEx(self, address):
MBI = MEMORY_BASIC_INFORMATION()
MBI_pointer = byref(MBI)
size = sizeof(MBI)
success = windll.kernel32.VirtualQueryEx(
self._process_handle,
address,
MBI_pointer,
size)
assert success, "VirtualQueryEx Failed with success == %s.\n%s" % (
success, WinError(win32api.GetLastError())[1])
assert success == size, "VirtualQueryEx Failed because not all data was written."
return PyMEMORY_BASIC_INFORMATION(MBI)
def AdjustPrivilege(priv):
flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
p = win32api.GetCurrentProcess()
htoken = win32security.OpenProcessToken(p, flags)
id = win32security.LookupPrivilegeValue(None, priv)
newPrivileges = [(id, win32security.SE_PRIVILEGE_ENABLED)]
win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
win32api.CloseHandle(htoken)
def OpenProcess(pid=win32api.GetCurrentProcessId()):
# ntsecuritycon.SE_DEBUG_NAME = "SeDebugPrivilege"
AdjustPrivilege(ntsecuritycon.SE_DEBUG_NAME)
phandle = windll.kernel32.OpenProcess( \
PROCESS_ALL_ACCESS,
0,
pid)
assert phandle, "Failed to open process!\n%s" % WinError(win32api.GetLastError())[1]
return phandle
PID = 22852
process_handle = OpenProcess(PID)
Memory(process_handle, TARGET(create_string_buffer("1456")))
Here is the error I always get;
AssertionError: ReadMemory Failed with success == 0 and address == 131072 and size == 4096.
[Error 5] Access is denied.
I do not know what information else about my code and my personal Windows 7 operating system, I should provide to you. If you need to know more, please ask it from me, I will provide it to solve that problem.
I guess, this is about a lack of configuration in my operating system , not about pywin32. I'll be waiting for your solutions.
I have this function:
void PickupFileAndSave(std::vector<unsigned char> file_data, int *error_code, char *file_mask = "All files (*.*)\0*.*\0\0")
{
OPENFILENAMEA ofn; // common dialog box structure
char szFile[MAX_PATH]; // buffer for file name
char initial_dir[MAX_PATH] = { 0 };
GetStartupPath(initial_dir);
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = GetActiveWindow();
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = file_mask;
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = initial_dir;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_EXPLORER;
if (!GetSaveFileNameA(&ofn))
{
*error_code = GetLastError();
return;
}
char err_msg[1024] = { 0 };
std::string file_name = ofn.lpstrFile; //this stores path to file without extension
file_name.append(".");
file_name.append(ofn.lpstrDefExt); //this is NULL and fails to copy too
WriteAllBytes(file_name.c_str(), &file_data[0], file_data.size(), &err_msg[0]);
if (strlen(err_msg) > 0)
{
*error_code = GetLastError();
return;
}
}
I call it that way:
int write_error = 0;
PickupFileAndSave(compressed, &write_error, "RLE compressed files (*.rle)\0*.rle\0\0");
When I choose file it shows in the filter needed extension, but do not add it to lpstrFile.
Any ideas why and how to fix it?
You did not assign lpstrDefExt so the system will not add the extension in case you omit it. So you simply need to initialise the field before you show the dialog:
lpstrDefExt = "rle";
The documentation explains this:
lpstrDefExt
The default extension. GetOpenFileName and GetSaveFileName append this extension to the file name if the user fails to type an extension. This string can be any length, but only the first three characters are appended. The string should not contain a period (.). If this member is NULL and the user fails to type an extension, no extension is appended.
It's not clear from the code in the question but you want to handle the case where there are multiple filters and you wish to append the extension of the selected filter.
The system won't do that for you so you will have to. Read nFilterIndex after you have shown the dialog. That tells you which filter the user selected. Then parse the filter string to obtain the chosen extension, and append it to the filename if it has no extension.