728x90

Official link: https://valgrind.org/

 

Valgrind Home

Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. You can also use Valgrind to build new tool

valgrind.org

 

Install:

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.
sudo pacman -Syu valgrind  # Arch, Manjaro, Garuda, etc

 

 

내부적으로 GDB를 사용하기 때문에 addr2line같은 것들이 제대로 동작해야 한다.

이전 포스팅에서 추가했던 secure compile option들을 넣으면 안된다.

대신 -g를 추가하여 debugging이 가능하도록 해야 한다.

https://bluelimn.tistory.com/entry/secure-compile

 

secure compile

checksec를 통해 secure compile 정보를 알 수 있다. https://github.com/slimm609/checksec.sh GitHub - slimm609/checksec.sh: Checksec.sh Checksec.sh. Contribute to slimm609/checksec.sh development by creating an account on GitHub. github.com 우선 3

bluelimn.tistory.com

 

ref: https://stackoverflow.com/questions/5134891/how-do-i-use-valgrind-to-find-memory-leaks

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

 

728x90
728x90

MyComboBox.java

import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.*;

public class MyComboBox extends JComboBox {


	final UndoManager undoMgr = new UndoManager();
	
	public MyComboBox() {
		super();
        init();
    }
	
    public final static String UNDO_ACTION = "Undo";

    public final static String REDO_ACTION = "Redo";

    private void init()
    {

    	setEditable(true);

        getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
		    @Override
		    public void keyReleased(KeyEvent event) {
		        if (event.getKeyCode() == KeyEvent.VK_F3)
		        {
		        	addItem((String)((JTextComponent)getEditor().getEditorComponent()).getText());
		        }
		        else if (event.getKeyCode() == KeyEvent.VK_F4)
		        {
		        	removeItemAt(getSelectedIndex());
		        }
		    }
		    public void keyPressed(KeyEvent e) {
		        if (e.getKeyCode() == KeyEvent.VK_Z && e.isControlDown()) {
		            if (undoMgr.canUndo()) {
		            	undoMgr.undo();
		            }
		        } else if (e.getKeyCode() == KeyEvent.VK_Y && e.isControlDown()) {
		            if (undoMgr.canRedo()) {
		            	undoMgr.redo();
		            }
		        }
		    }
		});

        // Add listener for undoable events
    	(((JTextField)getEditor().getEditorComponent()).getDocument()).addUndoableEditListener(new UndoableEditListener() {
            public void undoableEditHappened(UndoableEditEvent pEvt) {
                undoMgr.addEdit(pEvt.getEdit());
            }
        });

    }

}

 

 

MyTextField.java

import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.*;

public class MyTextField extends JTextField {
    public MyTextField() {
        final UndoManager undoMgr = new UndoManager();

        // Add listener for undoable events
        getDocument().addUndoableEditListener(new UndoableEditListener() {
            public void undoableEditHappened(UndoableEditEvent pEvt) {
                undoMgr.addEdit(pEvt.getEdit());
            }
        });

        // Add undo/redo actions
        getActionMap().put(UNDO_ACTION, new AbstractAction(UNDO_ACTION) {
            public void actionPerformed(ActionEvent pEvt) {
                try {
                    if (undoMgr.canUndo()) {
                        undoMgr.undo();
                    }
                } catch (CannotUndoException e) {
                    e.printStackTrace();
                }
            }
        });
        getActionMap().put(REDO_ACTION, new AbstractAction(REDO_ACTION) {
            public void actionPerformed(ActionEvent pEvt) {
                try {
                    if (undoMgr.canRedo()) {
                        undoMgr.redo();
                    }
                } catch (CannotRedoException e) {
                    e.printStackTrace();
                }
            }
        });

        // Create keyboard accelerators for undo/redo actions (Ctrl+Z/Ctrl+Y)
        getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK),
            UNDO_ACTION);
        getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK),
            REDO_ACTION);
    }
    
    public final static String UNDO_ACTION = "Undo";

    public final static String REDO_ACTION = "Redo";

    public static void makeUndoable(JTextComponent pTextComponent) {
        final UndoManager undoMgr = new UndoManager();

        // Add listener for undoable events
        pTextComponent.getDocument().addUndoableEditListener(new UndoableEditListener() {
            public void undoableEditHappened(UndoableEditEvent evt) {
                undoMgr.addEdit(evt.getEdit());
            }
        });

        // Add undo/redo actions
        pTextComponent.getActionMap().put(UNDO_ACTION, new AbstractAction(UNDO_ACTION) {
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undoMgr.canUndo()) {
                        undoMgr.undo();
                    }
                } catch (CannotUndoException e) {
                    e.printStackTrace();
                }
            }
        });
        pTextComponent.getActionMap().put(REDO_ACTION, new AbstractAction(REDO_ACTION) {
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undoMgr.canRedo()) {
                        undoMgr.redo();
                    }
                } catch (CannotRedoException e) {
                    e.printStackTrace();
                }
            }
        });

        // Create keyboard accelerators for undo/redo actions (Ctrl+Z/Ctrl+Y)
        pTextComponent.getInputMap().put(
            KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK), UNDO_ACTION);
        pTextComponent.getInputMap().put(
            KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK), REDO_ACTION);
    }
}
728x90

'Programming > JAVA잡기' 카테고리의 다른 글

자바 RMI (Remote Method Invovation) 사용하기  (0) 2008.09.23
자바 컴포넌트 기술(JDBC, JSP,JFC...)  (0) 2008.03.13
why JAVA?  (0) 2008.03.13
728x90

checksec를 통해 secure compile 정보를 알 수 있다.

https://github.com/slimm609/checksec.sh

 

GitHub - slimm609/checksec.sh: Checksec.sh

Checksec.sh. Contribute to slimm609/checksec.sh development by creating an account on GitHub.

github.com

 

우선 3가지 방향으로 compile을 해봤다.

test$ gcc pie_test.c -o default_pie

test$ gcc -static pie_test.c -o without_pie

test$ gcc -pie -fPIE pie_test.c -o with_pie

 

x86_64에서는 default로 PIE를 지원하고 있다.

Arm에서는 어떤지 알아보자

 

test$ aarch64-none-linux-gnu-gcc pie_test.c -o default_arm_pie
test$ aarch64-none-linux-gnu-gcc pie_test.c -static -o static_arm_pie
test$ aarch64-none-linux-gnu-gcc pie_test.c -fPIE -pie -o with_pie_arm_pie

Default로 PIE가 지원하지 않음을 알 수 있다. PIE를 위해서는 -fPIE -pie가 필요하다.

-fPIE는 compile option이고 -pie는 linker option이라고 한다.

 

stack canary에 대해 확인해보자

 

canary를 지원하기 위해서는 -fstack-protector-all를 추가해야 한다.

 

FORTIFY 추가: -D_FORTIFY_SOURCE=2

이건 -O를 함께 요구하기도 한다.

 

RELRO로 한번 넣어보자.:Relocation Read-Only : -Wl,-z,relro,-z,now

test$ aarch64-none-linux-gnu-gcc pie_test.c -fPIE -pie -fstack-protector-all -O -D_FORTIFY_SOURCE=2 -Wl,-z,relro,-z,now -o with_fortify

 

Symbols : -s

test$ aarch64-none-linux-gnu-gcc pie_test.c -fPIE -pie -fstack-protector-all -O -D_FORTIFY_SOURCE=2 -Wl,-z,relro,-z,now  -s -o with_fortify

 

* NX: "No eXecute" 영역이 적용되어 있는지 여부를 나타냅니다. 이 기능은 데이터 섹션에서 실행할 수 있는 코드 실행을 막아서, 공격자가 바이너리에 대한 취약점을 악용하는 것을 방지합니다.

* RPATH: ELF 바이너리에서 실행 시 참조할 라이브러리 경로를 지정하는데 사용됩니다. RPATH는 보안 위험이 발생할 수 있는 기능 중 하나로, 바이너리가 취약점을 가지고 있는 경우, 공격자가 RPATH를 이용하여 공격할 수 있습니다.

* RUNPATH: RPATH와 비슷한 역할을 하지만, 라이브러리 경로를 찾는 방법이 다릅니다. RUNPATH는 LD_LIBRARY_PATH와 같이 컴파일러나 링커에서 지정된 환경 변수에서 라이브러리 경로를 찾습니다.

* FORTIFY: FORTIFY는 C 라이브러리 함수를 보안 강화된 버전으로 대체하는 방식으로, 버퍼 오버플로우나 포맷 문자열 취약점 등의 보안 문제를 방지합니다.

* Symbols: ELF 바이너리에서 전역 심볼이 제대로 제한되었는지 여부를 나타냅니다. 이 기능은 공격자가 ELF 바이너리 내부의 함수나 변수의 위치를 찾아서 악용하는 것을 방지합니다. 따라서, 이 기능이 활성화되어 있으면 ELF 바이너리가 더욱 안전하게 실행될 수 있습니다.

* RELRO: RELRO는 "RELocation Read-Only"의 약자로, 바이너리의 메모리 매핑을 보호하는 기능입니다. 바이너리가 실행될 때, 공유 라이브러리나 동적 연결된 라이브러리들을 메모리에 로드합니다. 그런데 이러한 라이브러리들이 바이너리의 일부로 취급될 경우, 메모리 매핑이 변경될 수 있습니다. 이 때, 공격자가 바이너리의 실행 흐름을 변경하여 악용할 수 있습니다. 이를 방지하기 위해 RELRO 기능을 사용하여 바이너리의 메모리 매핑을 읽기 전용으로 설정합니다. RELRO 기능은 Partial RELRO와 Full RELRO가 있으며, Full RELRO는 보안성이 높아 추천되는 옵션입니다.

728x90
728x90

REF. 

https://interrupt.memfault.com/blog/ble-throughput-primer#:~:text=For%20Bluetooth%204.0%2C%20the%20BLE,be%20encoded%20in%20each%20symbol

 

A Practical Guide to BLE Throughput

A community and blog for embedded software makers

interrupt.memfault.com

https://novelbits.io/bluetooth-5-speed-maximum-throughput/

 

Bluetooth 5 speed: How to achieve maximum throughput for your BLE application

In this second post in the series on Bluetooth 5, we cover the new feature of 2x speed and how to achieve maximum data throughput for your BLE application.

novelbits.io

 

Why is it impossible to achieve the theoretical speeds of BLE?

The data rates of 1 Mbps (LE 1M PHY), 2 Mbps (LE 2M PHY), 125 kbps and 500 kbps (both using the LE Coded PHY with S=8 and S=2, respectively) are the rates at which the radio transmits data, but this is not achievable for the application throughput due to the following reasons:

  • Limit on the number of packets per connection interval
  • Inter Frame Space (IFS) delay between packets (150 us)
  • Empty packets required to be sent from a device even if no data is available for transmission
  • Packet overhead – not all bytes in a packet are used for payload

In order to better understand these factors and understand what impacts application throughput, we have to take a deeper look at the packet format. The following figure shows what LE 1M PHY and 2M PHY data packets look like:

The part we’re interested in (and the one that really defines the application data) is the ATT Payload. As you can see from the figure, there are a number of overhead bytes that are used by each layer in Bluetooth Low Energy.

  • In 4.0 and 4.1, the maximum ATT Payload is 20 bytes.
  • In 4.2 and 5.0, a new feature called Data Length Extensions (DLE) allows the ATT Payload to hold up to 244 bytes of data.

 

Factors that impact/determine the data throughput

There are a few factors that impact the data throughput of a BLE application. The most common are:

  • PHY being used (LE 1M vs. LE 2M vs. LE Coded (S=2 or S=8))
  • Connection interval
  • Maximum number of packets per connection interval
  • ATT Maximum Transmission Unit (ATT MTU)
  • Data Length Extension (DLE)
  • Operation type: Write with response vs. write without response, Indications vs. Notifications
  • Inter Frame Space (IFS): time gap between consequent packets (150 us)
  • Transmission of empty packets
  • Packet overhead – not all bytes, in a packet, are used for the application payload

Calculating your application data throughput

The big question is: how do we calculate our application throughput?

As we mentioned before, there are a few variables that impact the data throughput:

  • Bluetooth version & PHY used
  • DLE: Data Length Extensions – enabled or not
  • ATT MTU value
  • Connection interval
  • Maximum number of packets per connection event
  • Operation (writes with responses vs. writes without responses, and notification vs. indication)
  • Inter Frame Space (IFS): 150 microseconds

The Link Layer (LL) Packet

All data during a BLE connection is sent via Link Layer (LL) packets. All higher level messages are packed within Data Payloads of LL Packets. Below is what a LL Packet sending data looks like (each tick mark represents 1 byte):

 

NOTE: The astute reader may note that Data Payload can be up to 251 bytes. This however is an optional feature known as “LE Data Packet Length Extension” which we will explore in more detail below

Maximum Link Layer Data Payload Throughput

With the three rules we mentioned about transmissions on the Bluetooth Radio in mind, let’s take a look at the procedure to transmit a maximally sized LL packet.

  • Side A sends a maximum size LL data packet (27 bytes of data in a 41 byte payload) which takes 328μs (41 bytes * 8 bits / byte * 1Mbps) to transmit
  • Side B receives the packet and waits T_IFS (150μs)
  • Side B ACKs the LL packet it received in 80μs (0 bytes of data)
  • Side A waits T_IFS before sending any more data

Here’s an example exchange of two packets of data in one Connection Event:

The time it takes to transmit one packet can be computed as:

328μs data packet + 150μs T_IFS + 80μs ACK + 150μs T_IFS = 708μs

During this time period, 27 bytes of actual data can be transmitted which takes 216μs.

This yields a raw data throughput of:

(216μs / 708μs) * 1Mbps = 305,084 bits/second = ~0.381 Mbps

The Link Layer (LL) Packet

All data during a BLE connection is sent via Link Layer (LL) packets. All higher level messages are packed within Data Payloads of LL Packets. Below is what a LL Packet sending data looks like (each tick mark represents 1 byte):

NOTE: The astute reader may note that Data Payload can be up to 251 bytes. This however is an optional feature known as “LE Data Packet Length Extension” which we will explore in more detail below

Maximum Link Layer Data Payload Throughput

With the three rules we mentioned about transmissions on the Bluetooth Radio in mind, let’s take a look at the procedure to transmit a maximally sized LL packet.

  • Side A sends a maximum size LL data packet (27 bytes of data in a 41 byte payload) which takes 328μs (41 bytes * 8 bits / byte * 1Mbps) to transmit
  • Side B receives the packet and waits T_IFS (150μs)
  • Side B ACKs the LL packet it received in 80μs (0 bytes of data)
  • Side A waits T_IFS before sending any more data

Here’s an example exchange of two packets of data in one Connection Event:

The time it takes to transmit one packet can be computed as:

328μs data packet + 150μs T_IFS + 80μs ACK + 150μs T_IFS = 708μs

During this time period, 27 bytes of actual data can be transmitted which takes 216μs.

This yields a raw data throughput of:

(216μs / 708μs) * 1Mbps = 305,084 bits/second = ~0.381 Mbps

 

Maximum throughput over GATT

The Attribute Protocol Handle Value Notification is the best way for a server to stream data to a client when using GATT. The Opcode Overhead for this operation is 2 bytes. That means there are 3 bytes of ATT packet overhead and 4 bytes of L2CAP overhead for each ATT payload. We can determine the max ATT throughput by taking the maximum raw Link Layer throughput and multiplying it by the efficiency of the ATT packet:

ATT Throughput = LL throughput * ((MTU Size - ATT Overhead) / (L2CAP overhead + MTU Size))

Tabulating this information for a couple common MTU sizes we get:

MTU size (bytes) Throughput (Mbps)
23 (default) 0.226
185 (iOS 10 max) 0.294
512 0.301

LE Data Packet Length Extension (BT v4.2)

As part of the 4.2 Bluetooth Core Specification revision, a new feature known as LE Data Packet Length Extension was added 4. This optional feature allows for a device to extend the length of the Data Payload in a Link Layer packet from 27 up to 251 bytes! This means that instead of sending 27 bytes of data in a 41 byte payload, 251 bytes of data can now be sent in a 265 byte payload. Furthermore, we can send a lot more data with fewer T_IFS gaps. Let’s take a look at what exchanging a maximally sized packet looks like:

We can calculate the raw data throughput and see that this modification yields greater than a 2x improvement on the maximum raw data throughput which can be achieved!

251 bytes / 2500μs = 100.4 kBytes/sec = ~0.803 Mbps

 

LE 2M PHY (BT v5.0)

As part of the 5.0 Bluetooth Core Specification revision, a new feature known as “LE 2M PHY”5 was added. As you may recall in the section above, we discussed how the BLE Radio is capable of transmitting 1 symbol per μs for a bitrate of 1Mbps. This revision to the Bluetooth Low Energy Physical Layer (PHY), allows for a symbol rate of 2Mbps. This means we can transmit each individual bit in half the time. However, the 150μs IFS is still needed between transmissions. Let’s take a look on how this impacts the throughput when sending packets that are using the data packet length extension feature:

We can calculate this throughput and see the modification yields almost a 4x improvement over the original maximal raw data speed that could be achived with BLE 4.0:

251 bytes / 1400μs = 179.3 kBytes/sec = ~1.434 Mbps

 

LE Coded PHY (BT v5.0)

The “LE Coded PHY” feature, also introduced in the 5.0 Spec 5 provides a way to extend the range of BLE at the cost of speed. The feature works by encoding a bit across multiple symbols on the radio. This makes the bits being transmitted more resilient to noise. There are two operation modes where either two symbols or eight symbols can be used to encode a single bit. This effectively reduces the radio bitrate to 500 kbps or 125kbps, respectively.

 

 

Determine the time it takes to send one data packet and the empty packet from the receiver.

The time during which one data packet can be sent will include the following:
Data_Packet_Time = Time to transmit empty packet + IFS + Time to transmit the actual data packet + IFS.

An empty packet transmission time can be calculated as follows:
Time to transmit empty packet = empty packet size / raw data rate

An empty packet will contain the following fields:
Preamble + Access Address + LL Header + CRC.
For 1M PHY, Preamble will be 1 byte, and so the total size of the empty packet = 1 + 4 + 2 + 3 bytes = 10 bytes = 
80 bits.

(for 2M PHY, the size of an empty packet will be 88 bits since the Premable is 2 bytes instead of 1 byte).
Based on this, the time to transmit an empty 1M PHY packet will be:
Time to transmit empty packet = empty packet size / raw data rate = 80 bits/ 1 Megabits per second =
80 micro seconds

A data packet will contain all fields listed in the packet format diagram with the exception of the MIC field (encryption disabled).
Time to transmit data packet = data packet size / raw data rate

If we have DLE enabled and the ATT MTU is equal to the maximum bytes allowed in one packet: 247 bytes, then we can calculate the data packet size as:
Data packet size = 1 + 4 + 2 + 4 + 247 + 3 bytes = 265 bytes = 265*8 bits = 2088 bits
Time to transmit data  packet = 2088 bits / 1 Mbps = 
2,088 micro seconds

Data_Packet_Time = Time to transmit empty packet + IFS + Time to transmit the actual data packet + IFS = 80 + 2*150 + 2088 = 2,468 microsecs

For comparison, in the case of 2M PHY, it would be:
Data_Packet_Time = Time to transmit empty packet + IFS + Time to transmit the actual data packet + IFS = 88/2 + 2*150 + (2 + 4 + 2 + 4 + 247 + 3)*8/2 = 
1,392 microsecs

When DLE is enabled and the ATT MTU is set to less than 247, we end up with more overhead (since now data larger than the ATT MTU gets split up into more packets). For example, say we have the ATT MTU set to 158, then in order to transfer 244 bytes of application data, we will need two packets instead of one, causing the throughput to go down due to the increased byte overhead as well as the increased IFS between the packets. In another scenario, we could have DLE disabled (Payload size up to 27 bytes) and the ATT MTU greater than 27 bytes. Here, this will also result in more packets needed to be sent for the same amount of data, causing the throughput to go down.
Note: The same method for calculating the data and empty packet sizes that we used above can be used for the LE Coded PHY.

 

728x90

+ Recent posts