How to list more lines of code code in LLDB - lldb

How do I get LLDB to list more lines of code in the current frame. By default it only does 7. This is the best I can do so far:
(lldb) f
frame #9: 0x000000010001fce0 DualIssueInstructionSchedulerTest`void std::__1::random_shuffle<std::__1::__wrap_iter<exchange::ExchangeMessage*>, ExchangeWithLotsOfMessages::test_method()::$_5&>(__first=__wrap_iter<exchange::ExchangeMessage *> # 0x00007ffeefbf5298, __last=__wrap_iter<exchange::ExchangeMessage *> # 0x00007ffeefbf5290, __rand=0x00007ffeefbf56e0)::$_5&&&) at algorithm:3203
3200 for (--__last; __first < __last; ++__first, --__d)
3201 {
3202 difference_type __i = __rand(__d);
-> 3203 swap(*__first, *(__first + __i));
3204 }
3205 }
3206 }
(lldb) l 3100
3100 result_type max() const {return b();}
3101
3102 friend bool operator==(const uniform_int_distribution& __x,
3103 const uniform_int_distribution& __y)
3104 {return __x.__p_ == __y.__p_;}
3105 friend bool operator!=(const uniform_int_distribution& __x,
3106 const uniform_int_distribution& __y)
3107 {return !(__x == __y);}
3108 };
3109
(lldb) l
3110 template<class _IntType>
3111 template<class _URNG>
3112 typename uniform_int_distribution<_IntType>::result_type
3113 uniform_int_distribution<_IntType>::operator()(_URNG& __g, const param_type& __p)
3114 {
3115 typedef typename conditional<sizeof(result_type) <= sizeof(uint32_t),
3116 uint32_t, uint64_t>::type _UIntType;
3117 const _UIntType _Rp = __p.b() - __p.a() + _UIntType(1);
3118 if (_Rp == 1)
3119 return __p.a();
(lldb) l
3120 const size_t _Dt = numeric_limits<_UIntType>::digits;
3121 typedef __independent_bits_engine<_URNG, _UIntType> _Eng;
3122 if (_Rp == 0)
3123 return static_cast<result_type>(_Eng(__g, _Dt)());
3124 size_t __w = _Dt - __clz(_Rp) - 1;
3125 if ((_Rp & (std::numeric_limits<_UIntType>::max() >> (_Dt - __w))) != 0)
3126 ++__w;
3127 _Eng __e(__g, __w);
3128 _UIntType __u;
3129 do
(lldb) l
3130 {
3131 __u = __e();
3132 } while (__u >= _Rp);
3133 return static_cast<result_type>(__u + __p.a());
3134 }
3135
3136 #if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE) \
3137 || defined(_LIBCPP_BUILDING_LIBRARY)
3138 class _LIBCPP_TYPE_VIS __rs_default;
3139
Is there a way to increase the context for f or lass a range of lines to l?

If you just want to widen the window for one source listing, do:
(lldb) source list -c 40 -l 3100
then just hitting return (to auto-repeat the command) will continue with this count.
There are also two lldb settings that control the default for how much source gets printed:
(lldb) help settings set
...
stop-line-count-after -- The number of sources lines to display that come after the current source line when displaying a stopped context.
stop-line-count-before -- The number of sources lines to display that come before the current source line when displaying a stopped context.
The "current source line" is the pc if you are looking at the stop listing and the source line you passed to "list" if you are using that command.
Repeated calls to "l" (or just pressing to auto-repeat) will just print the sum of the two number of lines. So you would put:
settings set stop-line-count-before 10
settings set stop-line-count-after 10
or whatever number you like in your ~/.lldbinit to change this behavior.

Related

Variable inside if block is shown in call stack even though the if statement didn't get evaluated to true

I have a piece of code in C as shown below-
In a .c file-
1 custom_data_type2 myFunction1(custom_data_type1 a, custom_data_type2 b)
2 {
3 int c=foo();
4 custom_data_type3 t;
5 check_for_ir_path();
6 ...
7 ...
8 }
9
10 custom_data_type4 myFunction2(custom_data_type3 c, const void* d)
11 {
12 custom_data_type4 e;
13 struct custom_data_type5 f;
14 check_for_ir_path();
15 ...
16 temp = myFunction1(...);
17 return temp;
18 }
In a header file-
1 void CRASH_DUMP(int *i)
2 __attribute__((noinline));
3
4 #define INTRPT_FORCE_DUMMY_STACK 3
5
6 #define check_for_ir_path() { \
7 if (checkfunc1() && !checkfunc2()) { \
8 int temp = INTRPT_FORCE_DUMMY_STACK; \
9 ...
10 CRASH_DUMP(&sv);\
11 }\
12 }\
In an unknown scenario, there is a crash.
After processing the core dump using GDB, we get the call stack like -
#0 0x00007ffa589d9619 in myFunction1 [...]
(custom_data_type1=0x8080808080808080, custom_data_type2=0x7ff9d77f76b8) at ../xxx/yyy/zzz.c:5
temp = 32761
t = <optimized out>
#1 0x00007ffa589d8f91 in myFunction2 [...]
(custom_data_type3=<optimized out>, d=0x7ff9d77f7748) at ../xxx/yyy/zzz.c:16
temp = 167937677
f = {
...
}
If you see the code, check_for_ir_path is invoked from both myFunction1() and myFunction2().
And inside check_for_ir_path, there is a check inside if block like - checkfunc1() && !checkfunc2(). If that check evaluates to TRUE then a SIGSEGV is fired and the process is crashed intentionally. And the variable temp is declared only if that condition passes.
Now if you look at the call stack, you can see the local variable temp shown even in the StackFrame_1. However it didn't crash inside the function myFunction2. How could this be possible?
If i declare another variable, say 'int temp' just after the statement int temp = INTRPT_FORCE_DUMMY_STACK;, that is not shown as part of bt full
How could this be even possible?
Compilers are allowed to reorganise your code in any way that doesn't change the outcome of the program. So if you write:
void foo()
{
if (something)
{
int sv;
...
}
}
the compiler is allowed to change it into something equivalent to:
void foo()
{
int sv;
if (something)
{
...
}
}
regardless of something being true or false.
But the compiler must make sure that this will fail to compile:
void foo()
{
if (something)
{
int sv;
...
}
sv = whatever; // Compiler error....
}

Linker error when trying to use Azure-iot-sdk-c serializer model in multiple files

I try to use a serializer model with the azure-iot-sdk-c in multiple files. As long as I use it only in the main file, everything compiles.
But when I declare the model in another header file, use it in the corresponding c file and in the main file, I get a linker error:
CMakeFiles/simplesample_amqp.dir/otherfile.c.o: In function `FromAGENT_DATA_TYPE_ContosoAnemometer':
otherfile.c:(.text+0x1165): multiple definition of `FromAGENT_DATA_TYPE_ContosoAnemometer'
CMakeFiles/simplesample_amqp.dir/simplesample_amqp.c.o:simplesample_amqp.c:(.text+0x1165): first defined here
collect2: error: ld returned 1 exit status
serializer/samples/simplesample_amqp/CMakeFiles/simplesample_amqp.dir/build.make:160: recipe for target 'serializer/samples/simplesample_amqp/simplesample_amqp' failed
make[2]: *** [serializer/samples/simplesample_amqp/simplesample_amqp] Error 1
CMakeFiles/Makefile2:3947: recipe for target 'serializer/samples/simplesample_amqp/CMakeFiles/simplesample_amqp.dir/all' failed
make[1]: *** [serializer/samples/simplesample_amqp/CMakeFiles/simplesample_amqp.dir/all] Error 2
I tried this by adapting the serializer/samples/simplesample_amqp example:
diff --git a/serializer/samples/simplesample_amqp/CMakeLists.txt b/serializer/samples/simplesample_amqp/CMakeLists.txt
index 4f26060..52d55d7 100644
--- a/serializer/samples/simplesample_amqp/CMakeLists.txt
+++ b/serializer/samples/simplesample_amqp/CMakeLists.txt
## -11,6 +11,7 ## endif()
set(simplesample_amqp_c_files
simplesample_amqp.c
+otherfile.c
)
if(WIN32)
## -21,6 +22,7 ## endif()
set(simplesample_amqp_h_files
simplesample_amqp.h
+otherfile.h
)
IF(WIN32)
diff --git a/serializer/samples/simplesample_amqp/simplesample_amqp.c b/serializer/samples/simplesample_amqp/simplesample_amqp.c
index 0a9c9a8..b312c9c 100644
--- a/serializer/samples/simplesample_amqp/simplesample_amqp.c
+++ b/serializer/samples/simplesample_amqp/simplesample_amqp.c
## -26,24 +26,11 ##
#include "certs.h"
#endif // SET_TRUSTED_CERT_IN_SAMPLES
+#include "otherfile.h"
+
/*String containing Hostname, Device Id & Device Key in the format: */
/* "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>" */
-static const char* connectionString = "[device connection string]";
-
-// Define the Model
-BEGIN_NAMESPACE(WeatherStation);
-
-DECLARE_MODEL(ContosoAnemometer,
-WITH_DATA(ascii_char_ptr, DeviceId),
-WITH_DATA(int, WindSpeed),
-WITH_DATA(float, Temperature),
-WITH_DATA(float, Humidity),
-WITH_ACTION(TurnFanOn),
-WITH_ACTION(TurnFanOff),
-WITH_ACTION(SetAirResistance, int, Position)
-);
-
-END_NAMESPACE(WeatherStation);
+static const char* connectionString = "";
static char propText[1024];
## -199,10 +186,8 ## void simplesample_amqp_run(void)
}
else
{
- myWeather->DeviceId = "myFirstDevice";
- myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
- myWeather->Temperature = minTemperature + (rand() % 10);
- myWeather->Humidity = minHumidity + (rand() % 20);
+ myWeather->DeviceId = "myFirstDevice";
+ process_model(myWeather);
if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed, myWeather->Temperature, myWeather->Humidity) != CODEFIRST_OK)
{
otherfile.h:
// Define the Model
#include "serializer.h"
BEGIN_NAMESPACE(WeatherStation);
DECLARE_MODEL(ContosoAnemometer,
WITH_DATA(ascii_char_ptr, DeviceId),
WITH_DATA(int, WindSpeed),
WITH_DATA(float, Temperature),
WITH_DATA(float, Humidity),
WITH_ACTION(TurnFanOn),
WITH_ACTION(TurnFanOff),
WITH_ACTION(SetAirResistance, int, Position)
);
END_NAMESPACE(WeatherStation);
void process_model(ContosoAnemometer *myWeather);
otherfile.c:
#include "otherfile.h"
void process_model(ContosoAnemometer *myWeather) {
int avgWindSpeed = 10;
float minTemperature = 20.0;
float minHumidity = 60.0;
myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
myWeather->Temperature = minTemperature + (rand() % 10);
myWeather->Humidity = minHumidity + (rand() % 20);
}
Is there any way to work with the serializer model in multiple files?
Feel free to ask me for more information, please. Right now I'm not so sure what information is relevant for this post. I tried rigorously with the mqtt serializer example some time ago but got stuck with the same error as far as I can remember. It is really messy if you can not modularize your code and just have one monolithic file containing almost everything.
GCC:
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
OS:
4.4.0-97-generic #120-Ubuntu SMP Tue Sep 19 17:28:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
You can't reuse models but you can reuse datastructures. This can help you reuse up to 80% of your definitions.
You can design JSON structure as a set of DECLARE_STRUCT like this in separate file:
DECLARE_STRUCT(MyCommon,
EDM_DATE_TIME_OFFSET, datetime,
ascii_char_ptr, deviceid,
ascii_char_ptr, vin,
int32_t, message_id,
int32_t, request_messageid
);
After that you can use #include to reuse DECLARE_STRUCT for different models in С files:
BEGIN_NAMESPACE(cctcp);
#include "MyCommon_json.inc"
DECLARE_MODEL(Message,
WITH_DATA(EDM_GUID, edge_message_id),
WITH_DATA(int8_t, message_type),
WITH_DATA(MyCommon, tcu_common)
);

C - Parse string from SNMP SET (weird)

I am working on my own SNMP agent and am having trouble processing strings. I am pretty new to SNMP as well.
I've referred to the following links for some of implementing my own agent :
http://www.net-snmp.org/dev/agent/ucdDemoPublic_8c_source.html
http://www.net-snmp.org/dev/agent/example_8h_source.html
The second link shows exactly how to handle when a user attempts to set an integer type MIB object :
line 657 shows :
intval = *((long *) var_val);
My Question : How would I go about it with a string? I've tried casting it, strncpy, snprintf, etc.
My work :
I know, or at least think, that the following is legal :
int
setString(int action,
u_char * var_val,
u_char var_val_type,
size_t var_val_len,
u_char * statP, oid * name, size_t name_len)
{
unsigned char publicString[10];
static long intval;
char *cmd_string = NULL;
/*
* Define an arbitrary maximum permissible value
*/
switch (action) {
case RESERVE1:
//intval = *((long *) var_val);
/*
* Check that the value being set is acceptable
*/
if (var_val_type != ASN_OCTET_STR) {
DEBUGMSGTL(("setString", "%x not string type", var_val_type));
return SNMP_ERR_WRONGTYPE;
}
if (var_val_len > 1 ) {
DEBUGMSGTL(("setString", "wrong length %" NETSNMP_PRIz "u",
var_val_len));
return SNMP_ERR_WRONGLENGTH;
}
if ( !(var_val[0] == '1' || var_val[0] == '0') )
{
DEBUGMSGTL(("setString", "wrong value %s", var_val));
return SNMP_ERR_WRONGVALUE;
}
I know it is somewhat working because when I invoke
# snmpset -v 2c -c xxx 10.20.30.40 1.3.6.1.4.1.54321.3.0 s 3
Error in packet.
Reason: wrongValue (The set value is illegal or unsupported in some way)
Failed object: MY-TEST-MIB::testSnmp.3.0
AND
snmpset -v 2c -c xxx 10.20.30.40 1.3.6.1.4.1.54321.3.0 s 1
MY-TEST-MIB::testSnmp.3.0 = STRING: "1"
This proves to me at least the last collection of code is working.
Here is the action part :
case ACTION:
/*
* Set the variable as requested.
* Note that this may need to be reversed,
* so save any information needed to do this.
*/
if ( var_val[0] == '1' )
{
//do stuff - there realy is a script call here that does something
}
if ( var_val[0] == '0' )
{
//do stuff - there realy is a script call here that does something
}
break;
The above section I cannot get to work.
I've been able to get what I want by making the object an INTEGER (ASN.1) type but I can't do that because when reading this object it returns a STRING (ASN.1).

Program cannot pass test cases

There is a problem on Hacker Earth called Dhoom 4:
Samarpit is the main hero of the Dhoom 4. He is trying to steal from the Code Bank Of Hackers. Samarpit has a key with an integer value printed on it. He also has N other keys with each key having its own specific value. Samarpit is trying to break the Lock for which he is supposed to get to the lock's key value. He can perform one type of operation. Take his own key and one of the other N keys and merge them. During merging, Samarpit's Key value changes to the product of both the keys modulus 100000.
For example, if his key value were X and he took a key with value Y, his new key will be (X*Y)%100000.The other key that was used during the merging process remains along with the other N-1 keys.
This entire process of merging takes 1 second. Now, since he is in a hurry, he asks to you to find the minimum time in which he could reach to the lock's key value.
Input:
The first line contains 2 integers. They are Samarpit's Key value and the Lock's key value.
The second line contains N, indicating the number of other keys Samarpit has.
The third line contains N space-separated integers indicating the value of N other keys.
Output:
The minimum time required to get to the Lock's Key. If he is unable to reach that print -1.
Constraints:
1 ≤ N ≤ 1000
1 ≤ Value of all the keys ≤ 100000
My code is:
#include <stdio.h>
#include <time.h>
void main()
{
int i,f=0,n,skey,lkey,t=0;
long int a[1000],prod;
scanf("%d",&skey);
scanf("%d",&lkey);
prod=skey;
scanf("%d",&n);
if(n<=1000)
{
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
if(skey==lkey)
printf("0");
else
{
for(i=0;i<n;i++)
{
if(a[i]<=100000L && lkey % a[i]==0)
{
prod=(a[i]*prod)%100000L;
t++;
if(prod==lkey)
{
f=1;
printf("%d",t);
break;
}
else
f=0;
}
}
}
}
if(f==0)
printf("-1");
}
My program is working for smaller inputs but not for large inputs like:
18023 15115
356
18121 1326 22175 6108 24870 5429 25714 8945 22404 19339 21602 31878 10196 `14252 7186 6020 15854 2140 6205 25226 32646 14294 6218 30002 21596 17190 18465 8855 32436 28884 27710 5396 22534 27330 9219 22350 17910 12119 9811 28276 31622 7645 11356 27077 23179 8744 32436 2899 2398 17273 22696 28167 4307 6818 5585 19686 5743 29546 24040 20370 1749 7474 17114 20 17538 11993 1311 19928 11962 16862 29256 16889 5314 26820 4568 18624 26960 25787 5205 13415 19008 24188 14495 23842 12424 9845 7040 608 23662 16422 9603 20813 20985 15563 2826 13468 31141 10555 4763 20869 14682 4880 5499 22025 6559 26888 28286 31869 19212 15019 19229 26694 8189 6958 4809 16354 20110 11160 22655 10280 3779 4131 2717 1232 26886 21733 21748 8757 18647 1455 26910 11354 10175 32054 8465 5931 25733 12144 12277 23558 6821 29505 21811 12410 3582 3927 17871 6735 32459 3667 16375 1222 31188 7721 31964 15137 30950 32457 29888 27750 26496 17407 10576 7265 24527 28311 27189 9704 13276 8390 18406 12899 5893 29125 10432 19083 31658 9407 13400 25713 31016 18157 2320 4802 19979 30976 28648 14666 21119 26559 663 27320 28424 14321 30683 21409 27507 27005 2573 22215 10765 30160 11256 16026 8978 11647 32747 10239 13416 6445 17677 2641 6541 25008 12017 165 8143 879 23402 14419 27323 20750 23201 10418 23767 2382 32100 30754 30868 1070 24001 12880 19838 15191 21972 13237 17846 12726 22749 28256 26530 32363 25237 27638 24547 32482 28867 12535 26503 29759 15114 25922 23168 4096 7429 26076 4693 13277 26262 9197 22808 26867 1658 29963 2200 21026 17185 14523 10711 7604 30141 30517 10431 14911 31642 23912 28688 21196 20909 14910 413 22072 3695 24865 24248 3547 11756 5566 21739 1896 25622 25865 745 22036 26976 3969 10691 28411 30088 26805 7775 9407 23732 20487 28455 1650 705 9904 4606 9654 6360 26372 11896 2082 22850 16631 22602 18408 13693 24545 19967 10165 10895 15742 4077 7641 12186 9785 25448 6824 29361 21162 5685 3616 22506 14941 5697 28876 28340 981 12691 21479 20843 13776 4736 15557 9002 3533 19486 20335 8161 8140 2811 3214 29351 9045`
I tried to solve this problem using Queue in java language and below is my code. It worked properly.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Dhoom4 {
public static void main(String args[] ) throws Exception {
//Read input from stdin and provide input before running
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String value[] = line.split(" ");
int Skey = Integer.parseInt(value[0]);
int Lkey = Integer.parseInt(value[1]);
line = br.readLine();
int N = Integer.parseInt(line);
int all_key[] = new int[N];
line = br.readLine();
String temp[] = line.split(" ");
int k=0;
for(String s : temp)
all_key[k++] = Integer.parseInt(s);
//actual code
Queue q = new LinkedList();
q.add(Skey);
//For getting answer
int ans[] = new int[100005];
for(int i=0;i<ans.length;i++)
ans[i] = -1;
ans[Skey] = 0;
while(!q.isEmpty()){
int x = (int) q.poll();
if(x==Lkey)
break;
for(int i=0;i<k;i++){
int y = all_key[i];
y = (y*x);
y = y%100000;
if( y>=0 )
{
if(ans[y]==-1){
ans[y] = ans[x]+1;
q.add(y);}
}
}
}
System.out.println(ans[Lkey]);
}
}
I'm sorry to say your approach is too simplistic. The 'modulus 100000' constraint makes this a hard problem that cannot be solved with a single loop.
You would have noticed this sooner if you would have tested your algorithm with more than just a few trivial numbers. Pick any two 4-digit numbers at random and multiply them; e.g.
1234 * 5678 = 7006652
Obviously, 1234 and 5678 are divisors of 7006652, but 1234 and 5678 are not divisors of 6652. In fact, it's a rare coincidence for successful keys to be divisors of the lock key (unless of course the product is less than 100000). So why the following line of code?
if (a[i]<=100000L && lkey % a[i]==0)
Notice the condition fails for both keys:
lkey % a[i] == 6652 % 1234 == 482 != 0
lkey % a[i] == 6652 % 5678 == 974 != 0
Neither key would be accepted (except for the one held by Samarpit; but not the other).
Try it in a debugger and you will see. Here is the input file:
1234 6652
1
5678
Bottom line is, your algorithm is not suitable to solve this problem; you will have to follow a totally different approach.
The most straightforward way is to generate all possible k-combinations of keys, starting with k = 1 and increase until you find a match. This may not be most efficient approach, but it works. Worry about optimizations later.

Remove byte-order-mark in R/C

This SO post has an example of a server that generates json with a byte order mark. RFC7159 says:
Implementations MUST NOT add a byte order mark to the beginning of a JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.
Currently yajl and hence jsonlite choke on the BOM. I would like to follow the RFC suggestion and ignore the BOM from the UTF8 string if present. What is an efficient way to do this? A naive implementation:
if(substr(json, 1, 1) == "\uFEFF"){
json <- substring(json, 2)
}
However substr is a bit slow for large strings, and I am not sure this is the correct way to do this. Is there a more efficient way in R or C to remove the BOM if present?
A simple solution:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::string stripBom(std::string x) {
if (x.size() < 3)
return x;
if (x[0] == '\xEF' && x[1] == '\xBB' && x[2] == '\xBF')
return x.substr(3);
return x;
}
/*** R
x <- "\uFEFFabcdef"
print(x)
print(stripBom(x))
identical(x, stripBom(x))
utf8ToInt(x)
utf8ToInt(stripBom(x))
*/
gives
> x <- "\uFEFFabcdef"
> print(x)
[1] "abcdef"
> print(stripBom(x))
[1] "abcdef"
> identical(x, stripBom(x))
[1] FALSE
> utf8ToInt(x)
[1] 65279 97 98 99 100 101 102
> utf8ToInt(stripBom(x))
[1] 97 98 99 100 101 102
EDIT: What might also be useful is seeing how R does it internally -- there are a number of situations where R strips BOM (e.g. for its scanners and file readers). See:
https://github.com/wch/r-source/blob/bfe73ecd848198cb9b68427cec7e70c40f96bd72/src/main/scan.c#L455-L458
https://github.com/wch/r-source/blob/bfe73ecd848198cb9b68427cec7e70c40f96bd72/src/main/connections.c#L3950-L3957
Based on Kevin's Rcpp example I used the following C function to check for the bom:
SEXP R_parse(SEXP x) {
/* get data from R */
const char* json = translateCharUTF8(asChar(x));
/* ignore BOM as suggested by RFC */
if(json[0] == '\xEF' && json[1] == '\xBB' && json[2] == '\xBF'){
warning("JSON string contains UTF8 byte-order-mark!");
json = json + 3;
}
/* parse json */
char errbuf[1024];
yajl_val node = yajl_tree_parse(json, errbuf, sizeof(errbuf));
}

Resources