How to get crashed process id from a minidump file - crashpad

My application is developed with Electron(v11.1.1), and it uses crashpad to catch all crash dmp files from every processes.
How can I get crashed process id or other meta data from a minidump file

I found that we can parse some field directly from the dmp file
async function parseProcessDetailFromDump(dumpPath) {
return new Promise((ok, fail) => {
const readStream = fs.createReadStream(dumpPath)
let ptype = null
let pid = null
readStream.on("data", (chunk) => {
const text = chunk.toString(`utf-8`)
const lines = text.split(path.sep)
for (const line of lines) {
const found = line.match(/ptype/)
if (found != null && found.length > 0) {
const regPtype = /(?<=ptype[^0-9a-zA-Z]+)[0-9a-zA-Z]+/gu
const regPid = /(?<=pid[^0-9a-zA-Z]+)[0-9a-zA-Z]+/gu
ptype = line.match(regPtype)[0]
pid = line.match(regPid)[0]
}
}
})
readStream.on("error" , () => {
rejects()
})
readStream.on("end", () => {
ok({pid, ptype})
})
})
}

Related

Call data after refreshing the page (React Native Hooks)

Here's my code first
const [getData, setGetData] = useState();
const [ref, setRef] = useState();
const initializeData = async() => {
const userToken = await AsyncStorage.getItem('user_id');
setGetData(JSON.parse(userToken));
}
useEffect(() => {
return initializeData();
},[])
useEffect(() => {
let interval;
if(getData != null)
{
interval = setInterval(() => {
setRef(firestore().collection('**********').where("SendersNo", "==", getData.number));
}, 2000);
}
return () => clearInterval(interval);
},[getData])
useEffect(() => {
if(ref != null)
{
return ref.onSnapshot(querySnapshot => {
const list = [];
querySnapshot.forEach(doc => {
const {
id,driverName,driverContactNumber,driverRating,driverPlateNumber,driverTrackingNumber,userPlaceName,
destinationPlaceName,PaymentMethod,Fare
} = doc.data();
list.push({id: doc.id,driverName,driverContactNumber,driverRating,
driverPlateNumber,driverTrackingNumber,userPlaceName,destinationPlaceName,PaymentMethod,Fare});
});
setUserBookingData(list);
console.log("HEY!");
});
}
},[])
const CurrentTransaction = () => {
if(ref == null)
{
return (
<View>
<Text>You don't have a Current Transaction</Text>
</View>
)
}
else
{
return userBookingData.map((element) => {
return (
<View key={element.id}>
<View>
<Text>{element.name}</Text>
</View>
</View>
)
});
}
}
So currently right now what I am trying to is if there's a data on my firestore it will update on the screen but before updating it I need to get the data from the setGetData so that I can query it but the problem is that when I refresh the whole simulator/page it doesn't get the data but instead just a blank page . But when i edit and save my code without refreshing the page/simulator it can get the data . Can someone help me what I am doing wrong .
EDIT
if I do this
useEffect(() => {
if(ref != null)
{
return ref.onSnapshot(querySnapshot => {
const list = [];
querySnapshot.forEach(doc => {
const {
id,driverName,driverContactNumber,driverRating,driverPlateNumber,driverTrackingNumber,userPlaceName,
destinationPlaceName,PaymentMethod,Fare
} = doc.data();
list.push({id: doc.id,driverName,driverContactNumber,driverRating,
driverPlateNumber,driverTrackingNumber,userPlaceName,destinationPlaceName,PaymentMethod,Fare});
});
setUserBookingData(list);
console.log("HEY!");
});
}
else
{
return null;
}
},[ref])
it keeps looping the console.log('hey') but it can get the data and display it . but it loops so its bad.
i believe snapshot from firebase realtime database is a listener so its doesn't need setinterval
useEffect(() => {
if(getData != null)
{
const ref = firestore().collection('**********').where("SendersNo", "==", getData.number);
ref.onSnapshot(querySnapshot => {
const list = [];
querySnapshot.forEach(doc => {
const {
id,driverName,driverContactNumber,driverRating,driverPlateNumber,driverTrackingNumber,userPlaceName,
destinationPlaceName,PaymentMethod,Fare
} = doc.data();
list.push({id: doc.id,driverName,driverContactNumber,driverRating,
driverPlateNumber,driverTrackingNumber,userPlaceName,destinationPlaceName,PaymentMethod,Fare});
});
setUserBookingData(list);
console.log("HEY!");
});
}
return () => {
//clear your ref listener here
}
},[getData])
if you put a return on use effect it will be called after the screen is no longer used.
useEffect(()=>{
//inside this will be called when the screen complete render
const someListener = DeviceEventEmitter('listentosomething',()=>{
//do something
});
return ()=>{
//inside this will be called after the screen no longer be used
//example go to other screen
someListener.remove();
}
},)

Angular 9 async-await Uncaught (in promise) Error

//to check the uploaded pdf file total pages > 5
static validatePdfFile(event: any) {
const file = event.target.files[0];
file.arrayBuffer().then(async buff => {
let fileUint8Array = new Uint8Array(buff);
const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false});
const totalPages = pdfDoc.getPageCount();
if(totalPages > 5) {
throw new Error('File must be less than 5 pages.');
}
});
}
Using async await, Getting the Below Exception:
Uncaught (in promise): Error: File must be less than 5 pages.. Error: File must be less than 5 pages. at Function.
(http://localhost:4200/main.ca25b55f0dfc50ab2.....
What is the right way to throw new Error from async?
:)
validatePdfFile(event: any) {
const file = event.target.files[0];
this.PdfPagesCount(file).subscribe(
(pageCount: number) => {
if (pageCount > 5) {
throw new Error('File must be less than 5 pages.');
} else {
//...
}
},
(error: any) => {
event.target.value = '';
throw error;
}
);
}
countPdfPages(file: File) {
return from(file.arrayBuffer().then(
async buff => {
const fileUint8Array = new Uint8Array(buff);
const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false, ignoreEncryption: true});
return pdfDoc.getPageCount();
}
));
}

Convert File to base64 in Nativescript

I have been trying to get the base64 of a File of Nativescript, so far I have tried the next:
const documents: Folder = <Folder>knownFolders.documents();
const folder: Folder = <Folder>documents.getFolder("Download");
const file: File = <File>folder.getFile("Vista general Aguas.pdf");
const toBase64 = (fle: File) => new Promise((resolve, reject) => {
const reader = new FileReader();
const newFile = fle.readSync(err => console.log(err));
// I know that I have to convert the binary to base64, but I'm getting this [B#9b1d878 in newFile
reader.readAsDataURL(newFile);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
toBase64(file).then(result => console.log('64', result));
Any help is appreciated!
I have created function using native implementation. This function return base64 string.
public getBase64String = (path) => {
const sourceFile: fs.File = fs.File.fromPath(path);
const data = sourceFile.readSync();
if (isIOS) {
return data.base64EncodedStringWithOptions(0);
} else {
return android.util.Base64.encodeToString(
data,
android.util.Base64.NO_WRAP
);
}
};

How to run wasm on d8

I have a wasm file fib.wasm which contains function fib(n).
If run it in the browser, we can do
var module, functions = {};
fetch('fib.wasm')
.then(response => response.arrayBuffer())
.then(buffer => new Uint8Array(buffer))
.then(binary => {
var moduleArgs = {
wasmBinary: binary,
onRuntimeInitialized: function () {
functions.fib =
module.cwrap('fib',
'number',
['number']);
onReady();
}
};
module = Module(moduleArgs);
});
If in Node, since fetch is not implemented, we can do
const fs = require('fs')
const buf = fs.readFileSync('fib.wasm')
(async () => { res = await WebAssembly.instantiate(buf); })()
const { fib } = res.instance.exports
However, in d8 shell, both ways involves functions undefined. How can we run wasm in d8?
The d8 shell has a function read() which reads a file from disk. It takes an optional parameter to specify binary mode. So the following should work:
const buf = read('fib.wasm', 'binary');
let res;
WebAssembly.instantiate(buf).then((x) => res = x, (error) => console.log(error));
const { fib } = res.instance.exports;

How to list folders and files in a directory using ReactiveX

When using Observables for certain tasks that involve a lot of chaining and a lot of asynchronous operations, such as listing all the items in a folder and checking all of the folders in it for a specific file, I often end up either needing to build the complex chain for each task (return Observable.of(folder)...) or having some kind of special value that gets forwarded to the end to signal the end of a batch (every operator starts with if(res === false) return Observable.of(false)).
Sort of like that stick that you put between your groceries and those of the person in front of you at the checkout.
It seems like there should be a better way that doesn't involve forwarding a stop value through all kinds of callbacks and operators.
So what is a good way to call a function that takes a folder path string and returns a list of all the files and folders in it. It also specifies whether the files are HTML files or not, and whether or not the folders contain a file called tiddlywiki.json.
The only requirement is that it can't return anything like Observable.of(...).... It should probably have a subject at the top of the chain, but that is not a requirement.
function listFolders(folder) {
return [
{ type: 'folder', name: 'folder1' },
{ type: 'datafolder', name: 'folder2' }, //contains "tiddlywiki.json" file
{ type: 'folder', name: 'folder3' },
{ type: 'htmlfile', name: 'test.html' },
{ type: 'other', name: 'mytest.txt' }
]
}
Here is one that does not follow the rules I layed out (see below for one that does), but it took about ten minutes, using the first one as a guide.
export function statFolder(subscriber, input: Observable<any>) {
return input.mergeMap(([folder, tag]) => {
return obs_readdir({ folder, tag })(folder);
}).mergeMap(([err, files, { folder, tag }]) => {
if (err) { return Observable.of({ error: err }) as any; }
else return Observable.from(files).mergeMap(file => {
return obs_stat([file,folder])(path.join(folder, file as string));
}).map(statFolderEntryCB).mergeMap<any, any>((res) => {
let [entry, [name, folder]] = res as [any, [string, string, number, any]];
if (entry.type === 'folder')
return obs_readdir([entry])(path.join(entry.folder, entry.name));
else return Observable.of([true, entry]);
}, 20).map((res) => {
if (res[0] === true) return (res);
let [err, files, [entry]] = res as [any, string[], [FolderEntry, number, any]];
if (err) {
entry.type = "error";
} else if (files.indexOf('tiddlywiki.json') > -1)
entry.type = 'datafolder';
return ([true, entry]);
}).reduce((n, [dud, entry]) => {
n.push(entry);
return n;
}, []).map(entries => {
return { entries, folder, tag };
}) as Observable<{ entries: any, folder: any, tag: any }>;
}).subscribe(subscriber);
}
Original: This took a few hours to write...and it works...but...it uses concatMap, so it can only take one request at a time. It uses a custom operator that I wrote for the purpose.
export function statFileBatch(subscriber, input: Observable<any>) {
const signal = new Subject<number>();
var count = 0;
//use set timeout to fire after the buffer recieves this item
const sendSignal = (item) => setTimeout(() => { count = 0; signal.next(item); });
return input.concatMap(([folder, tag]) => {
return obs_readdir({ folder, tag })(folder);
}).lift({
call: (subs: Subscriber<any>, source: Observable<any>) => {
const signalFunction = (count) => signal.mapTo(1), forwardWhenEmpty = true;
const waiting = [];
const _output = new Subject();
var _count = new Subject<number>()
const countFactory = Observable.defer(() => {
return Observable.create(subscriber => {
_count.subscribe(subscriber);
})
});
var isEmpty = true;
const sourceSubs = source.subscribe(item => {
if (isEmpty && forwardWhenEmpty) {
_output.next(item);
} else {
waiting.push(item)
}
isEmpty = false;
})
const pulse = new Subject<any>();
const signalSubs = pulse.switchMap(() => {
return signalFunction(countFactory)
}).subscribe(count => {
//act on the closing observable value
var i = 0;
while (waiting.length > 0 && i++ < count)
_output.next(waiting.shift());
//if nothing was output, then we are empty
//if something was output then we are not
//this is meant to be used with bufferWhen
if (i === 0) isEmpty = true;
_count.next(i);
_count.complete();
_count = new Subject<number>();
pulse.next();
})
pulse.next(); //prime the pump
const outputSubs = Observable.create((subscriber) => {
return _output.subscribe(subscriber);
}).subscribe(subs) as Subscription;
return function () {
outputSubs.unsubscribe();
signalSubs.unsubscribe();
sourceSubs.unsubscribe();
}
}
}).mergeMap(([err, files, { folder, tag }]) => {
if (err) { sendSignal(err); return Observable.empty(); }
return Observable.from(files.map(a => [a, folder, files.length, tag])) as any;
}).mergeMap((res: any) => {
let [file, folder, fileCount, tag] = res as [string, string, number, any];
return obs_stat([file, folder, fileCount, tag])(path.join(folder, file))
}, 20).map(statFolderEntryCB).mergeMap<any, any>((res) => {
let [entry, [name, folder, fileCount, tag]] = res as [any, [string, string, number, any]];
if (entry.type === 'folder')
return obs_readdir([entry, fileCount, tag])(path.join(entry.folder, entry.name));
else return Observable.of([true, entry, fileCount, tag]);
}, 20).map((res) => {
//if (res === false) return (false);
if (res[0] === true) return (res);
let [err, files, [entry, fileCount, tag]] = res as [any, string[], [FolderEntry, number, any]];
if (err) {
entry.type = "error";
} else if (files.indexOf('tiddlywiki.json') > -1)
entry.type = 'datafolder';
return ([true, entry, fileCount, tag]);
}).map(([dud, entry, fileCount, tag]) => {
count++;
if (count === fileCount) {
sendSignal([count, tag]);
}
return entry;
}).bufferWhen(() => signal).withLatestFrom(signal).map(([files, [sigResult, tag]]: any) => {
return [
typeof sigResult !== 'number' ? sigResult : null, //error object
files, //file list
typeof sigResult === 'number' ? sigResult : null, //file count
tag //tag
];
}).subscribe(subscriber);
}

Resources