Automatically Generate C Code From Header - c

I want to generate empty implementations of procedures defined in a header file. Ideally they should return NULL for pointers, 0 for integers, etc, and, in an ideal world, also print to stderr which function was called.
The motivation for this is the need to implement a wrapper that adapts a subset of a complex, existing API (the header file) to another library. Only a small number of the procedures in the API need to be delegated, but it's not clear which ones. So I hope to use an iterative approach, where I run against this auto-generated wrapper, see what is called, implement that with delegation, and repeat.
I've see Automatically generate C++ file from header? but the answers appear to be C++ specific.
So, for people that need the question spelled out in simple terms, how can I automate the generation of such an implementation given the header file? I would prefer an existing tool - my current best guess at a simple solution is using pycparser.
update Thanks guys. Both good answers. Also posted my current hack.

so, i'm going to mark the ea suggestion as the "answer" because i think it's probably the best idea in general. although i think that the cmock suggestion would work very well in tdd approach where the library development was driven by test failures, and i may end up trying that. but for now, i need a quicker + dirtier approach that works in an interactive way (the library in question is a dynamically loaded plugin for another, interactive, program, and i am trying to reverse engineer the sequence of api calls...)
so what i ended up doing was writing a python script that calls pycparse. i'll include it here in case it helps others, but it is not at all general (assumes all functions return int, for example, and has a hack to avoid func defs inside typedefs).
from pycparser import parse_file
from pycparser.c_ast import NodeVisitor
class AncestorVisitor(NodeVisitor):
def __init__(self):
self.current = None
self.ancestors = []
def visit(self, node):
if self.current:
self.ancestors.append(self.current)
self.current = node
try:
return super(AncestorVisitor, self).visit(node)
finally:
if self.ancestors:
self.ancestors.pop(-1)
class FunctionVisitor(AncestorVisitor):
def visit_FuncDecl(self, node):
if len(self.ancestors) < 3: # avoid typedefs
print node.type.type.names[0], node.type.declname, '(',
first = True
for param in node.args.params:
if first: first = False
else: print ',',
print param.type.type.names[0], param.type.declname,
print ')'
print '{fprintf(stderr, "%s\\n"); return 0;}' % node.type.declname
print '#include "myheader.h"'
print '#include <stdio.h>'
ast = parse_file('myheader.h', use_cpp=True)
FunctionVisitor().visit(ast)

UML modeling tools are capable of generating default implementation in the language of choice. Generally there is also a support for importing source code (including C headers). You can try to import your headers and generate source code from them. I personally have experience with Enterprise Architect and it supports both of these operations.

Caveat: this is an unresearched answer as I haven't had any experience with it myself.
I think you might have some luck with a mocking framework designed for unit testing. An example of such a framework is: cmock
The project page suggests it will generate code from a header. You could then take the code and tweak it.

Related

Is there a Python alternative to IDL's array_indices() function?

I am working on a port of some IDL code to Python (3.7). I have a translation working which uses whatever direct Python alternatives are available, and supplementing what I can with idlwrap. In an effort to eliminate legacy IDL functions from the code, I am looking for an alternative to ARRAY_INDICES(). Right now, I have simply translated the entire function directly and import it on its own. I've spent a good deal of time trying to understand exactly what it does, and even after translating it verbatim, it is still unclear to me, which makes coming up with a simple Python solution challenging.
The good news is I only need it to work with one specific set of arrays whose shapes wont change. An example of the code that will be run follows:
temp = np.sum(arr, axis=0)
goodval = idlwrap.where(temp > -10)
ngood = goodval.size
arr2 = np.zeros_like(arr)
for i in range(0, ngood - 1):
indices = array_indices(arr2, goodval[i])
#use indices for computation

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

How to get attribute value from Xml using C

I have the XML file as given as below
-<fmiModelDescription numberOfEventIndicators="0" variableNamingConvention="structured" generationDateAndTime="2015-06-22T14:46:19Z" generationTool="Dassault Systemes FMU Export from Simulink, ver. 2.1.1 (MATLAB 8.7 (R2014b) 08-Sep-2014)" version="1.4" author="Dan Henriksson" description="S-function with FMI generated from Simulink model BouncingBalls" guid="{76da271a-0d11-469c-bc24-0343629fb38e}" modelName="BouncingBalls_sf" fmiVersion="2.0"> <CoSimulation canHandleVariableCommunicationStepSize="true" modelIdentifier="BouncingBalls_sf"/> <DefaultExperiment stepSize="0.001" stopTime="10.0" startTime="0.0"/> -<ModelVariables>
I want to fetch the attribute value for eg GUID which is given in the above XML,how can i do that using C programming
Well the only valid answer is: use a library!
The probably best one (in terms of feature completeness) is libxml. Use this if there aren't any other concerns. There's good documentation, too.
If you need something small, there are a LOT of options, all with their limitations. I recently created badxml for this purpose. There are many other options, such as ezxml which I discovered just today in a question here.
But as I said, if size is not a concern, just use libxml, because it is widely used, well tested and feature-complete.

How to use phloc schematron-pure with Document -schema-definition

This question concerns phloc-schematron, a library for ISO Schematron validation.
I am creating schematron-files on the fly, so I have them available as document (or as string of course)
I cannot find a constructor for SchematronResourcePure that takes a string or document as argument, nor can I find a method to create a IReadableResource from the same.
Can someone suggest how to do this?
In case this is still relevant:
Switch to ph-schematron at https://github.com/phax/ph-schematron/ and use the static SchematronResourcePure.fromString method.
But you are right - this is a case that is currently not considered - building the Schematron from scratch. I will see, what I can do!

Is there such a thing as a javascript deminifier (deobfuscator)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
This question is exactly the opposite of Which Javascript minifier (cruncher) does the same things that the one Google uses for its JS APIs?
I want to learn how google does it's loading so I can build my own with non-popular JS toolkits.
Try this: JS Beautifier
Try http://www.jsnice.org/
I just stumbled on it and it is great. It expands the code. It has statistical variable renaming. for example, if you have this code:
var g = f.originalEvent.targetTouches[0];
Then it it turns your code into:
var touches = event.originalEvent.targetTouches[0];
Pretty good guess, methinks.
It turned this:
d.slide.hasClass("selected") ? (e.onSlideOpen.call(d.prev.children("div")[0]), q ? (e.rtl && d.slide.position().left > i.w / 2 || d.slide.position().left < i.w / 2) && h.animateSlide.call(d) : t && d.index ? (h.animateGroup(d, !0), h.fitToContent(d.prev)) : d.slide.position().top < i.h / 2 && h.animateSlide.call(d)) : (setTimeout(function() { e.onSlideOpen.call(d.slide.children("div")[0]) }, e.slideSpeed), h.animateGroup(d), t && h.fitToContent(d.slide)), e.autoPlay && (f.stop(), f.play(l.index(j.filter(".selected"))))
Into this:
if (e.slide.hasClass("selected")) {
settings.onSlideOpen.call(e.prev.children("div")[0]);
if (val) {
if (settings.rtl && e.slide.position().left > box.w / 2 || e.slide.position().left < box.w / 2) {
self.animateSlide.call(e);
}
} else {
if (isMac && e.index) {
self.animateGroup(e, true);
self.fitToContent(e.prev);
} else {
if (e.slide.position().top < box.h / 2) {
self.animateSlide.call(e);
}
}
}
} else {
setTimeout(function() {
settings.onSlideOpen.call(e.slide.children("div")[0]);
}, settings.slideSpeed);
self.animateGroup(e);
if (isMac) {
self.fitToContent(e.slide);
}
}
if (settings.autoPlay) {
node.stop();
node.play(tabs.index(options.filter(".selected")));
}
A library I'm working on has a couple of bugs, and after spending hours trying to decipher the code, finding this is going to save me a bunch of time.
Seriously, this tool wipes the floor with JS Beautifier.
Uhhh, it would be impossible to restore variable names unless there was a mapping of minified -> original variable names available. Otherwise, I think the authors of that tool could win the Randi prize for psychic feats.
Chrome Developer tools has this built in
You will not be able to reconstruct method name or variable names. The best you can hope for is a simple JS code formater (like those previously mentioned), and then to go through the file method by method, line by line, working out what each part does.
Perhaps using a good JS refactoring tool would make this easier as well (being able to rename/document methods)
You can use the \b (word boundary) feature in regular expressions to find single-letter variable names in a file.
for i in "abcdefghij..z"; do
sed -i "s/\b$i\b/$(random /usr/share/dict/words)/g" somefile.js
done
You can also use this in vim with something like :%s/\<a\>/truesaiyanpower/g.
To unminify js files, Unminify would be the best!
To unminify css, html and js files, you can use Unminify or Unminify JS online tool!
See our SD ECMAScript Formatter for a tool that will nicely format code.
EDIT: If you want to reverse the renaming process you need something can rename the obfuscated names back to the originals.
This tool can technically do that: SD Thicket ECMAScript Obfuscator.
It does so by applying a renaming map over which you have precise control.
Typically you implicitly construct such a map during the obfuscation process by choosing which names to obfuscate and which to preserve, and the obfuscator applies that map to produce the obfuscated code.
The Thicket obfuscator generates this map as side effect when you obfuscate
in the form essentially of a set of pairs (originalname,obfuscatedname)
for reference and debugging purposes.
Swapping elements gives the map (obfuscatedname,originalname). That inverted map can be applied by Thicket to recover the code with the original names, from the obfuscated code. And the Thicket obfuscator includes the Formatter to let you make it look nice again.
The catch to "reversing minification" (as you put it poorly, you are trying to reverse obfuscation), is that you need the map. Since people doing obfuscation don't give away the map, you, as a recipient of obfuscated code, have nothing to apply. A would-be pirate would have to reconstruct the map presumably by painful reverse engineering.
The "reversing" process also can't recover comments. They're gone forever.
This is all by design, so the real question is why are you looking to reverse obfuscation?
Javascript minifier and Javascript Obfuscator are two different things.
Minifier - removes the comments, unnecessary whitespace and newlines from a program.
Obfuscator - make modifications to the program, changing the names of variables, functions, and members, making the program much harder to understand. Some obfuscators are quite aggressive in their modifications to code.
This Javascript Obfuscator will obfuscate your code.
If you want to deobfuscate your code, try Javascript Beautifier. It will deobfuscate if obfuscation is found and then beautify the code.

Resources